Compare commits

..
Author SHA1 Message Date
SafiandClaude Opus 4.8 37d7078f8b Prototypes: repo-scoped import-first resolution + cross-language API-contract edges
Flag-gated experiments (GRAPHIFY_REPO_SCOPED_RESOLUTION, GRAPHIFY_API_CONTRACT_EDGES),
validated but intentionally NOT on v8. Parked here so the work is recoverable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:43:50 +01:00
SafiandClaude Opus 4.8 435da06c70 Release 0.8.43
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:31:01 +01:00
SafiandClaude Opus 4.8 8e6ba9d714 Parse package manifests into canonical package nodes + depends_on edges (#1377)
apm.yml was a .yml document handled by the LLM, so the same package got a
different file-anchored node id from its own manifest than from each dependent's
dependency reference and split into duplicate nodes. New manifest_ingest module
parses apm.yml/pyproject.toml/go.mod/pom.xml deterministically into ONE package
node per package, keyed by name via ids.make_id, plus depends_on edges; routed
to the AST path (CODE) so the LLM never sees them. Package nodes are exempt from
the file-stem prefix remap so the canonical id is stable across manifests and
dedup collapses references to a single hub node.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:25:09 +01:00
SafiandClaude Opus 4.8 a78956424d Reject Windows-style git hooks paths instead of creating a junk dir (#1385)
On WSL/POSIX, Path("C:\\...").is_absolute() is False, so a Windows absolute
core.hooksPath (or rev-parse --git-path output) was joined under the repo root
and mkdir'd as a literal backslash-named junk directory while install reported
success and the real .git/hooks got nothing. Both branches of _hooks_dir now
reject drive-letter / backslash paths with a clear error so the failure is loud.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:06:07 +01:00
SafiandClaude Opus 4.8 e6eaad3d7e Emit edges for markdown links so hub docs connect (#1376)
extract_markdown only emitted heading nodes + contains edges and never parsed
link syntax, so a doc full of [text](./other.md) links (index.md,
table-of-contents.md) had no edges to the docs it links and never became a hub.
Add a deterministic link pass: inline, reference-style, and [[wikilinks]],
resolved relative to the source file, external URLs/anchors/images skipped, with
the target id built via the same _make_id recipe so the edge merges onto the
real doc node instead of an orphan.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:02:27 +01:00
SafiandClaude Opus 4.8 5038129c7e Accept str paths in the semantic extract entry points (#1386)
extract_corpus_parallel and extract_files_direct are typed list[Path] but
crashed with AttributeError on str paths (f.suffix in slicing/partition, f.parent
in packing). Coerce files = [Path(f) for f in files] at both public entry points;
the AST extract() already coerced.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:01:31 +01:00
8883991c2e Unify node-ID normalization into a single source of truth (#1378)
extract._make_id and build._normalize_id were copy-pasted forks of the same
NFKC/casefold recipe kept in sync by mirrored docstrings -- the root of the
recurring ID-drift ghost-node bug class (#811/#550/#1033/#1104). Move the recipe
to graphify/ids.py and have all four producers delegate to it: extract, build,
and (completing the migration) mcp_ingest and symbol_resolution, whose
"avoid an import cycle" copies are moot now that ids.py is dependency-free. The
contract test asserts all four resolve to the shared recipe, with hypothesis
property tests for make_id == normalize_id and idempotency.

Co-Authored-By: danielnguyenfinhub <danielnguyenfinhub@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 22:55:44 +01:00
ab1e0ec588 Adaptive split-and-retry for community labeling on parse failure (#1280, #1278)
label_communities logged-and-skipped any batch whose LLM response was malformed
JSON, silently losing ~100 names per failed batch on large graphs. Split the
batch at the midpoint and retry each half (smaller prompt -> smaller output),
mirroring _extract_with_adaptive_retry; the base case re-raises so the caller
skips just that batch. Removed leftover scaffolding and corrected the docstring.

Co-Authored-By: CJdev232 <CJdev232@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 22:50:52 +01:00
9e8fa2a28c Bump vulnerable dependencies to patched versions (#1375)
pypdf 6.11.0->6.13.3 (CVE-2026-48155/48156), yt-dlp 2026.3.17->2026.6.9,
pyjwt 2.12.1->2.13.0, cryptography 48.0.0->49.0.0, python-multipart
0.0.28->0.0.32, with lower-bound floors for the direct deps (pypdf, yt-dlp) so
installs get the patched versions. Lockfile regenerated for 0.8.42.

Co-Authored-By: hypnwtykvmpr <hypnwtykvmpr@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 22:48:50 +01:00
SafiandClaude Opus 4.8 baf2410f08 Release 0.8.42
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 20:05:25 +01:00
SafiandClaude Opus 4.8 d12eb28c2d Note intra-file slicing in the JSON-truncation troubleshooting entry (#1369)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 02:26:01 +01:00
SafiandClaude Opus 4.8 4f539e729f Slice oversized text documents so the whole file is extracted (#1369)
_read_files capped every file at 20,000 chars, so a Markdown/text/rST document
longer than that lost everything past the cap with no recovery. Oversized
splittable-text files are now split at heading/paragraph boundaries into units
that each fit the cap and together cover the whole file; every slice reports its
parent file as source_file so the graph isn't fragmented per-slice, and a slice
that still overflows output is bisected and retried. Code and PDFs are never
sliced.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 01:55:56 +01:00
897483fc96 Merge #1366: prune deleted-only and root the full build so --update stops duplicating
After #1361 added root= to the --update build_merge call, build_merge's prune
(which runs after the merge) began matching freshly re-extracted changed-file
nodes and deleting them — a regression in 0.8.41 where --update on a changed
file wiped its nodes. This drops `changed` from prune_sources (replace-on-
re-extract from #1344 already reconciles changed files), passes root= to the
full build's build_from_json so its node-key base matches the update side, and
pins the extraction-spec source_file to the verbatim path so the two runs never
drift. Re-blessed skillgen expected/ snapshots.

Co-Authored-By: RelywOo <RelywOo@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 01:28:19 +01:00
SafiandClaude Opus 4.8 895a60f4e3 Model Java records as type nodes and extract constructor calls (#1373)
Add record_declaration to the Java class types so a record becomes a first-class
type node instead of an isolated file node, and add object_creation_expression
to call types with a dedicated branch that reads the callee from the `type`
field (new Foo() has no `name` field), so `new Foo(...)` emits a calls edge to
the constructed type.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 01:18:48 +01:00
SafiandClaude Opus 4.8 b2a1722903 Merge .graphifyignore with .gitignore instead of replacing it (#1363)
A .graphifyignore made graphify skip that directory's .gitignore entirely, so a
file excluded only by .gitignore (including neutrally-named secrets the
sensitive-file heuristic misses) got indexed into the graph and could leak into
committed graph artifacts. Read .gitignore first and .graphifyignore last so
their patterns merge and graphifyignore negations still win.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 01:15:24 +01:00
SafiandClaude Opus 4.8 9e0b8766f4 Release 0.8.41
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 19:09:43 +01:00
SafiandClaude Opus 4.8 c9f2ef5e48 Document this session's fixes in changelog and add JSON-truncation troubleshooting
Add changelog entries for the Swift cross-file (#1356), update prune (#1361),
obsidian canvas (#1324), and edge source_file backfill (#1279) fixes that
shipped without changelog notes, and a README troubleshooting entry for the
LLM JSON-truncation warnings and how to reduce them.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:43:08 +01:00
SafiandClaude Opus 4.8 5b0c154828 Honour configured output-token cap for OpenAI-compatible backends (#1365)
ollama/openai/deepseek/kimi set max_tokens in their backend config, but the
openai-compat dispatch read only max_completion_tokens (which only gemini
defines), so their output silently capped at the 8192 fallback and truncated
deep-mode JSON. Read either key and give the openai config an explicit cap;
GRAPHIFY_MAX_OUTPUT_TOKENS still overrides.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:35:58 +01:00
e9f8dde7af Stop fuzzy dedup over-merging numbered siblings, cross-file boilerplate, and prefix-divergent labels (#1284, #1243)
Three pass-2 guards (mirrored in the --dedup-llm pair collection): block merges
when labels' embedded numbers differ as zero-padding-insensitive multisets;
block cross-file merges of file-anchored rationale/document nodes (same-file
still merges); and score cross-file long labels on plain Jaro instead of
Jaro-Winkler so the prefix bonus can't fabricate merges of shared-prefix but
token-divergent entities (jest-native vs react-native), while genuine cross-file
duplicates still clear Jaro and same-file near-duplicates keep Jaro-Winkler.

Co-Authored-By: van4oza <van4oza@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:21:19 +01:00
RelywOoandClaude Opus 4.8 5b988974ca fix(skill): pin extraction source_file + root the full build, prune deleted-only
Completes the source_file convention fix begun in #1344 (build_merge
replace-on-re-extract) and #1361 (pass root= to build_merge in the --update
runbook). Two gaps still let the full build and incremental --update emit
different source_file bases for the same file, so the source_file-keyed replace
missed and duplicates accumulated:

1. extraction-spec(.md/-compact.md): the subagent's source_file slot was an
   unpinned "relative/path", so it invented a base per run (and the node id,
   derived from the same path, drifted too). Pin it to the verbatim FILE_LIST
   path so _norm_source_file(root) canonicalizes every run identically.

2. core.md: the full build called build_from_json WITHOUT root=, so #1361's
   update-side root= had no matching base on the full-build side. Pass
   root='INPUT_PATH' at both sites (Step 4 export, Step 5 report) so the full
   build and --update relativize to the same base.

update.md prune_sources = deleted only. Changed files are replaced by build_merge
(#1344); once root= aligns the bases, leaving `changed` in prune_sources would
delete the freshly re-extracted nodes.

Engine (build.py) unchanged. Regenerated all skill artifacts via
tools/skillgen/gen.py. Adds test_build_merge_root_collapses_convention_drift.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:07:14 +03:00
SafiandClaude Opus 4.8 8437ef465e Backfill edge source_file from endpoint nodes (#1279)
Semantic/LLM edges occasionally omit source_file, which build only normalized
when already present, so the field reached graph.json empty and downstream
validation flagged it. Backfill from the source (then target) node in
build_from_json and in the --no-cluster raw-write path, which bypasses it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 13:49:31 +01:00
SafiandClaude Opus 4.8 9c8bd4d47c Populate Obsidian canvas when no community data is present (#1324)
to_canvas built cards solely by iterating communities, so a graph with no
community data (--no-cluster builds, or a missing analysis sidecar) wrote the
empty 32-byte {"nodes":[],"edges":[]} shell while notes rendered fine. Fall back
to one synthetic community covering every node so the canvas reflects the graph.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 13:49:31 +01:00
SafiandClaude Opus 4.8 2c662c7917 Pass root to build_merge in the update runbook so stale nodes get pruned (#1361)
The /graphify --update runbook called build_merge with absolute prune_sources
but no root=, so _norm_source_file never relativized them to match the graph's
relative source_file values. Nothing was pruned and changed/deleted files left
ghost nodes that compounded on every incremental update. Fix the shared skillgen
fragment to pass root='INPUT_PATH' and re-render all platform artifacts.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 13:30:02 +01:00
SafiandClaude Opus 4.8 2e01f37c81 Resolve cross-file Swift class relationships from member calls and constructors (#1356)
Capture property/field initializer constructor calls, build a per-file Swift
type table from property/parameter declarations, and add a member-call
resolution pass that types the receiver and emits an edge only when the type
name resolves to exactly one definition. Additive and INFERRED-only; the
is_member_call drop and the #543/#1219 god-node guards stay intact.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 12:08:59 +01:00
mistic96 d8fa70e17b Harden HTML output against U+2028 XSS + two crash-on-adversarial-input fixes (#1357)
Harden HTML export against U+2028/U+2029 script-breakout XSS + two crash-on-adversarial-input fixes (non-dict LLM JSON, _extract_parallel IndexError). Validated: full suite 2107 passed, HTML export smoke clean. Thanks @mistic96.
2026-06-17 10:46:19 +01:00
RelywOo fd463deb03 fix(build_merge): replace re-extracted files instead of accumulating stale edges (#1344)
build_merge: prune a re-extracted file's stale nodes/edges before merge instead of accumulating (fixes #1283, #1285). Validated: full suite 2107 passed. Thanks @RelywOo.
2026-06-17 10:46:15 +01:00
geektan123 f117aaccc6 feat: PowerShell .psd1 manifest parsing & Import-Module / dot-source edge emission (#1331) (#1341)
Index PowerShell .psd1 manifests + emit Import-Module/dot-source edges (closes #1331). Builds on the shipped .psm1 support. Validated: full suite 2107 passed, 18 new tests. Thanks @geektan123.
2026-06-17 10:46:12 +01:00
Pavel Kudinov a16b3e1b45 fix incremental no-cluster graph updates (#1350)
Harden incremental no-cluster updates: fixes empty-write graph wipeout on no-op update --no-cluster (#1347) and git-hook subdir path resolution (#1348). Complementary to #1317. Validated: full suite 2107 passed, no-op re-run no longer wipes graph. Thanks @pkudinov.
2026-06-17 10:46:08 +01:00
balloon72 9a7dbfbb84 fix js workspace import resolution (#1352)
Fixes #1334: detect npm/yarn package.json workspaces (array + yarn object form), pnpm precedence preserved. Reviewed: full suite 2087 passed, no regressions. Thanks @balloon72.
2026-06-17 10:29:47 +01:00
balloon72 d885833112 fix node label lookup normalization (#1353)
Fixes #1338 (Unicode NFD/NFC): serve._find_node now matches tokenized labels; affected.resolve_seed NFC-normalizes + casefolds. Reviewed: full suite 2087 passed, CLI smoke clean, no regressions. Thanks @balloon72.
2026-06-17 10:29:43 +01:00
SafiandClaude Opus 4.8 be3dcfca08 Unify query skill: ship expansion + inline fallback to every platform
The query skill was split across two fragments so no platform got both
capabilities: Claude had the vocab/IDF query-expansion step but no fallback if
the CLI was unavailable; every other platform had the inline NetworkX fallback
but the weaker raw-question matcher. Merge into one unified query reference +
stub (Step 0 expansion -> CLI traversal -> inline NetworkX fallback, plus
path/explain inline) shipped to all hosts. Remove the query_variant enum, its
toml field, and the _CLI_ONLY_QUERY_HEADINGS coverage-audit exemption. Re-render
all skill artifacts and re-bless expected/. skillgen check/audit-coverage/
monolith-roundtrip/schema-singleton all pass. Refs #1325.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 03:33:23 +01:00
SafiandClaude Opus 4.8 2100b3d05b Resolve cross-file Java type references by import package
Same-named types in different packages left implements/inherits edges stuck on
bare shadow stubs, isolating the real interface (_rewire_unique_stub_nodes only
fixes the globally-unique case). New _resolve_java_type_references pass uses each
referencing file's import statements (+ package decl) to build an FQN->def index,
re-points dangling implements/inherits/imports edges to the exact definition, and
drops the orphaned stub. External/stdlib imports stay unresolved (correct). Runs
after id-disambiguation so target ids are final. Java-scoped; other _extract_generic
languages share the same bare-name fallback and remain a follow-up.

Adds tests/test_java_type_resolution.py (simple, ambiguous-by-import, build-survival).
Refs #1318.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 03:16:08 +01:00
SafiandClaude Opus 4.8 4fbb33301c Collapse Swift module imports to one shared node
Adopts the approach from #1330 (thanks @duncan-daydream) on top of the v0.8.40
Swift import fix: _import_swift returns (id,label) module pairs, the extractor
materializes a type=module anchor node per import, and _disambiguate_colliding_node_ids
exempts type=module nodes so the same module imported from N files collapses to
one shared node (enables reverse traversal "what imports CoreKit"). The --no-cluster
writer now dedupes nodes by id and edges to match the clustered build_from_json path.

Replaces the interim _import_label/synthesize_import_module_nodes mechanism.
Adds tests/test_swift_import_resolution.py (cross-file collapse, build survival)
and dedupe_nodes coverage. Refs #1327, #1330.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 03:06:43 +01:00
SafiandClaude Opus 4.8 fd152add64 Release 0.8.40
Bump version to 0.8.40; document this release in CHANGELOG (PowerShell .psm1
indexing, Swift import survival, no-cluster edge dedup, custom OpenAI/Anthropic
endpoints, JS/TS assignment-form extraction, community-name + --graph fixes,
four production bug fixes, perf, security CI); add .psm1 to the README
supported-extensions table.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 02:38:28 +01:00
SafiandClaude Opus 4.8 adb52a1ea0 Index .psm1, anchor Swift import targets, dedupe no-cluster edges
- #1315: add .psm1 to CODE_EXTENSIONS + _DISPATCH so PowerShell modules are indexed
- #1327: synthesize a module node for Swift import targets (new LanguageConfig
  flag synthesize_import_module_nodes) so imports edges survive build.py pruning;
  strengthen the Swift dangling-edge test to also assert edge targets
- #1317: dedupe parallel edges by (source,target,relation) in the --no-cluster
  and incremental update write paths so edge counts are deterministic and
  `update` is idempotent

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 02:28:16 +01:00
Siddarth Chintamani 09da5294e4 feat: extract JS/TS this.X=, exports.X=, prototype, class arrow fields, function expressions (#1323)
Extract JS/TS this.X=, exports.X=, prototype, class arrow fields, and function expressions (closes #1322). Validated locally against v8: full suite 2069 passed.
2026-06-16 02:14:31 +01:00
Timon 61836ce0e8 feat: custom endpoints via OPENAI_BASE_URL/OPENAI_MODEL and ANTHROPIC_BASE_URL/ANTHROPIC_MODEL (#1273)
Custom OPENAI/ANTHROPIC base-url + model env vars for self-hosted and proxy endpoints. CI green (3.10/3.12).
2026-06-16 01:41:15 +01:00
Safi fd470faeee docs: add --graph flag example to graphify-mcp usage (#1304) 2026-06-13 19:44:36 +01:00
Safi a4f3e862b2 changelog: document community name fix and --graph alias (#1304, #1305) 2026-06-13 19:36:12 +01:00
SafiandClaude Sonnet 4.6 85de47e121 fix: community names blank in query/MCP after cluster-only; --graph for graphify-mcp
export.py: to_json now accepts community_labels and writes community_name onto
each node. Previously cluster-only wrote labels only to GRAPH_REPORT.md,
graph.html, and .graphify_labels.json — graph.json stored only the numeric cid,
so query/MCP showed blank or numeric community values (#1305).

__main__.py: pass community_labels=labels to to_json in cluster-only path.
explain command now prefers community_name over raw numeric community field.

serve.py: query and get_node read paths prefer community_name over community,
with fallback so old graphs without the field still work. Adds --graph flag as
an alias for the positional argument in graphify-mcp/_main(), fixing
"unrecognized arguments: --graph" for users following the documented pattern
shared by every other graphify subcommand (#1304).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-13 19:34:18 +01:00
Safi b61c985c12 changelog: document #1209 security CI and #1166 node-summaries RFC 2026-06-13 16:03:58 +01:00
Safi 591cc934a7 Merge pull request #1166 from leonaburime-ucla/docs/node-summaries-rfc
docs: add RFC for file-level node summaries
2026-06-13 15:56:42 +01:00
Safi 9bed8318c6 Merge pull request #1209 from nucleusjay/ci-run-security-scanners
Wire bandit and pip-audit into CI
2026-06-13 15:56:39 +01:00
Safi 10655b92eb changelog: document four bug fixes (#1257, #1288, #1298, #1299) 2026-06-13 15:16:17 +01:00
SafiandClaude Sonnet 4.6 b83086297f fix: four production bugs — Windows crashes, ghost-merge collision, version probe
extract.py: clamp ProcessPoolExecutor max_workers to 61 on Windows (issue #1298).
Python's ProcessPoolExecutor hard-caps at 61 on Windows via WaitForMultipleObjects;
>61-core machines crashed on AST extraction. Clamp applied after all input paths
(auto-compute, GRAPHIFY_MAX_WORKERS, --max-workers) to cover all three.

build.py: skip ghost-merge when two AST nodes share (basename, label) key (issue #1257).
When same-named symbols appear in same-named files across directories (e.g. two
render() in two index.ts), last-writer-wins produced an arbitrary canonical node
and mis-pointed all edges. Now tracked in _loc_collisions; ambiguous keys are
skipped in Pass 2, leaving the ghost intact rather than merging into the wrong node.

__main__.py: ignore OSError on unreadable .graphify_version probes (issue #1299).
On restricted-permission installs or network mounts, .exists()/.read_text() raised
PermissionError and crashed every graphify query/explain/path call at startup.
All three FS probes now wrapped in try/except OSError: return.

prs.py: resolve claude.cmd on Windows in prs.py claude-cli backend (issue #1288).
The _call_llm and _call_claude_cli paths were already fixed; prs.py had the same
bare ["claude", ...] call that fails on Windows npm installs with WinError 2.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-13 15:13:23 +01:00
Safi 813db19252 Merge pull request #1295 from sirphilliptubell/perf/fix5
perf: parallelize save_manifest file hashing with ThreadPoolExecutor
2026-06-13 11:28:43 +01:00
Safi dbbf0a45a1 Merge pull request #1294 from sirphilliptubell/perf/fix4
perf: convert _walk_js_tree from recursive generator to iterative
2026-06-13 11:28:40 +01:00
Sir Phillip Tubell 0f6d46f822 perf: parallelize save_manifest file hashing with ThreadPoolExecutor
stat+MD5 across all files now fans out over a thread pool instead of running sequentially — I/O-bound work releases the GIL so this scales with available disk concurrency.
2026-06-12 16:07:51 -04:00
Safi c4689a2f47 bump version to 0.8.39 2026-06-12 20:36:47 +01:00
Sir Phillip Tubell a7c69808ac perf: convert _walk_js_tree from recursive generator to iterative
Eliminates O(depth) generator-frame chain overhead. Each leaf's value previously propagated through 26+ yield-from frames; now a single stack loop handles the full traversal.
2026-06-12 15:19:44 -04:00
Safi 3929eca450 changelog: add unreleased entries for #1289, #1207, #1208, #1176 2026-06-12 20:18:17 +01:00
Safi 70a1ad7278 Merge pull request #1176 from galshubeli/falkordb-backend
feat: add FalkorDB export backend (#1175)
2026-06-12 20:15:30 +01:00
Safi 70380b8ea0 Merge pull request #1208 from nucleusjay/pin-tree-sitter-deps
Pin tree-sitter dependency version ranges
2026-06-12 20:15:27 +01:00
Safi 3e8cd7da6d Merge pull request #1207 from nucleusjay/fix-merge-chunks-and-manifest-bugs
Fix two latent bugs: merge-chunks output and manifest data loss
2026-06-12 20:15:23 +01:00
Safi 418fab8e23 Merge pull request #1289 from sirphilliptubell/perf/fix1
perf: fix O(n^2) -> O(n) LSH neighbor lookup in dedup
2026-06-12 20:15:20 +01:00
Safi 6c2f273742 changelog: add unreleased entries for #1280, #1276, #1282, #1281 2026-06-12 19:58:49 +01:00
Safi 5a21685bf1 Merge pull request #1281 from BemoBit/docs/fa-readme
docs: add Persian (فارسی) translation and language selector link
2026-06-12 19:54:47 +01:00
Safi fb1908cc55 Merge pull request #1282 from balloon72/codex/community-label-model
feat: add --model to community labeling commands
2026-06-12 19:54:44 +01:00
Safi 90decbc4ed Merge pull request #1276 from papinto/fix/graphifyignore-negation-pruning
fix: a single negation (!) in .graphifyignore no longer disables all directory pruning
2026-06-12 19:54:41 +01:00
Safi 0ff84d8bf3 Merge pull request #1280 from s22hyun/fix/affected-edges-key
fix(affected): handle "edges"-keyed graph.json in load_graph (KeyError: 'links')
2026-06-12 19:54:38 +01:00
Sir Phillip Tubell c4d6b412ca perf: fix O(n^2) -> O(n) LSH neighbor lookup in dedup
Replaced O(n) linear scan `next((n for n in candidates if n["id"] == neighbor_id))` with O(1) dict lookup via pre-built `candidates_by_id`. Also pre-caches `_norm()` results in `norm_cache` to avoid recomputing per inner iteration.

For a 36k-file codebase (~100k high-entropy candidates) this reduces the pass-2 loop from O(n^2*B) (~30–100B iterations) to O(n*B), eliminating the multi-minute CPU hang after AST extraction completes.
2026-06-12 10:31:01 -04:00
hanmo1 b304331d24 feat: add model override for community labeling 2026-06-12 17:57:19 +08:00
Behnam Moradi 0e74c0401e docs: add Persian (فارسی) translation and language selector link
Adds complete Persian translation (README.fa-IR.md) with RTL formatting and updates main README language selector to include Persian between Arabic and Italian.
2026-06-12 11:15:32 +03:30
s22hyun 2ab2302112 fix(affected): handle "edges"-keyed graph.json in load_graph (KeyError: 'links') 2026-06-12 15:33:33 +09:00
Safi 1bb30fcc56 bump version to 0.8.38 2026-06-11 23:46:54 +01:00
SafiandClaude Sonnet 4.6 b739cf2fda changelog: document all v8 unreleased fixes and features
Covers 13 merged PRs: LLM calls-edge direction fix, JS default
imports/exports, tsconfig baseUrl paths, ghost-merge collision skip,
resolve_seed callable labels, AST cache versioning, global-graph edge
rewiring, dedup pass-2 winner, cache --out anchor, single-walk collect,
frontmatter delimiters, claude-cli Windows headless + JSON array envelope,
Cargo extractor, SystemVerilog/Dart improvements, README grammar count.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-11 23:42:11 +01:00
SafiandClaude Sonnet 4.6 3a47091021 docs: update tree-sitter grammar count from 28 to 36
Reflects languages now supported: Python, TypeScript/TSX, JavaScript/JSX,
Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig,
PowerShell, Elixir, Objective-C, Julia, Vue, Svelte, Astro, Groovy, Dart,
Verilog, SystemVerilog, SQL, Fortran, Pascal/Delphi, Shell/Bash, JSON,
DreamMaker, HCL/Terraform, R, and .NET XML project files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-11 23:38:46 +01:00
Jamie EvansandClaude Opus 4.8 6dc23db90f fix: emit symbol edges for default imports/exports
JS/TS symbol resolution only handled named imports. A default-exported
symbol (`export default class Foo`) imported as `import Foo from './foo'`
produced only a file→file `imports_from` edge; the class node received no
incoming symbol edge. On codebases that default-export most classes
(NestJS services/helpers/models, etc.) those symbols looked like isolated
leaf nodes, and `graphify affected "<Class>"` / `explain` reported no
callers.

Record default imports with imported_name="default", register a "default"
export for `export default <class|function|identifier>`, and let the
existing exported-origin resolver wire the `imports` edge — which also
resolves calls made through the local binding, even when it is renamed
(`import Bar from './foo'; new Bar()`). `export { X as default }` was
already handled via the export-clause path; anonymous defaults
(`export default class {}`) have no resolvable symbol and stay file-level.

Adds regression tests for default-export class/function/identifier import
resolution and renamed-binding call resolution.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 23:24:59 +01:00
Safi d276a5aa57 Merge pull request #1271 from giovanecesar/feat/cargo-introspect
feat(extract): add opt-in --cargo crate dependency extractor
2026-06-11 23:22:50 +01:00
Safi 60d4b4373f Merge pull request #1269 from jevans-agent/fix/tsconfig-paths-baseurl
fix: resolve tsconfig path aliases relative to baseUrl
2026-06-11 23:22:45 +01:00
Safi e16c1f37bf Merge pull request #1266 from PowPickles/fix/claude-cli-windows-spawn
fix: claude-cli backend works headlessly on Windows npm installs
2026-06-11 23:22:41 +01:00
Safi b87329496f Merge pull request #1265 from PowPickles/fix/resolve-seed-callable-decoration
fix: resolve_seed matches bare names against ()-decorated callable labels
2026-06-11 23:22:38 +01:00
Safi 0be4e81047 Merge pull request #1246 from VLDCNDN/fix/extract-out-cache-leak
fix: anchor extraction cache at --out root so external output leaves the scanned project clean
2026-06-11 23:22:35 +01:00
Safi b7b59ca9ea Merge pull request #1244 from PCeltide/fix/claude-cli-json-array-envelope
fix(claude-cli): handle JSON-array envelope from Claude Code CLI ≥ 2.1
2026-06-11 23:22:30 +01:00
Safi 5b60624acd Merge pull request #1267 from TheFedaikin/v8
uv.lock sync, SystemVerilog class-level extraction + Dart mixin fix
2026-06-11 23:22:27 +01:00
Safi 3ea6def727 Merge pull request #1262 from teemow/fix/collect-files-single-walk
fix(extract): collect files in a single pruned walk instead of one rglob per extension (#1261)
2026-06-11 23:22:23 +01:00
Safi b34902b8d7 Merge pull request #1260 from teemow/fix/frontmatter-delimiters
fix(cache): require whole --- lines as frontmatter delimiters (#1259)
2026-06-11 23:22:20 +01:00
Safi e364f72fd8 Merge pull request #1253 from teemow/fix/ast-cache-version
fix(cache): namespace AST cache by graphify version (#1252)
2026-06-11 23:22:15 +01:00
Safi 556cab3c2c Merge pull request #1251 from teemow/fix/global-graph-external-edges
fix(global-graph): rewire edges to deduplicated external nodes (#1250)
2026-06-11 23:22:11 +01:00
Safi 2117983b87 Merge pull request #1248 from teemow/fix/dedup-pass2-winner-union
fix(dedup): pick pass-2 winner from the verified pair only (#1247)
2026-06-11 23:21:39 +01:00
Paulo PintoandClaude Opus 4.8 e8ab8f4172 fix: negation pattern no longer disables all directory pruning
A single `!` rule in .graphifyignore set a blanket `has_negation` flag that
disabled directory-level pruning for EVERY ignored directory during the
os.walk in detect(). One unrelated `!docs/**` therefore made the walk descend
bin/, obj/, wwwroot/, generated/, … on large repos — a pathological slowdown.
Output stayed correct (the per-file `_is_ignored` filter still excluded those
files), but the walk visited the entire tree.

The bypass was unnecessary: `_is_ignored` already honours negations correctly —
last-match-wins lets `!dir/` un-ignore a directory (so it is not pruned), and
the gitignore parent-exclusion rule means a `!` cannot rescue a file beneath an
excluded directory, so descending an ignored dir to find a re-included file is
never needed. Prune purely on `_is_noise_dir` + `_is_ignored`.

Adds a regression test that tracks os.walk and asserts the ignored dir is never
descended while the negation still re-includes its target.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 14:50:44 -07:00
Giovane Cesar da Silva b56a415388 feat(extract): add opt-in --cargo crate dependency extractor
Closes #1264

Also fixes a narrow watch-mode path-filtering bug found while running the required local
full-suite gate for this PR. Hidden directories inside the watched corpus are still ignored;
hidden ancestors outside the watched root no longer suppress valid file events.
2026-06-11 15:08:36 -06:00
Jamie EvansandClaude Opus 4.8 ec04152a90 fix: resolve tsconfig path aliases relative to baseUrl
_read_tsconfig_aliases joined alias targets onto the tsconfig's own
directory and ignored compilerOptions.baseUrl. In the common monorepo /
NestJS layout (baseUrl "./src" with "@services/*": ["services/*"]), the
alias resolved to <dir>/services instead of <dir>/src/services, so every
aliased import failed to resolve and the import edge was silently dropped
— leaving cross-file caller graphs nearly empty on alias-heavy TS repos.

Resolve `paths` relative to `baseUrl` (TypeScript's actual semantics),
defaulting to "." so configs without baseUrl keep their current behavior.
Add a regression test covering a subdirectory baseUrl; the existing alias
test only exercised baseUrl ".", which is why this slipped through.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 14:20:09 -04:00
Danil Tarasov b525549a24 feat(extract): SystemVerilog class-level extraction; Dart with-clause mixin fix 2026-06-11 19:52:56 +03:00
Skyler SouthernandClaude Fable 5 96585badd0 fix: claude-cli backend works headlessly on Windows npm installs
Two Windows fixes for the claude-cli backend:

1. _call_llm (the label/community-naming path) spawned a bare ["claude", ...],
   which CreateProcess cannot resolve to the npm claude.cmd shim (PATHEXT does
   not apply) — every labeling batch failed with WinError 2. Mirror the
   extraction path's resolution: prefer shutil.which("claude.cmd") and pass
   the resolved path. Regression test included.

2. Both claude -p spawn sites now pass CREATE_NO_WINDOW on Windows. Without
   it, each per-batch claude.cmd spawn allocates a console — with Windows
   Terminal as the default terminal, a labeling run pops one visible window
   per batch on the user's desktop for the duration of the model call.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 09:58:39 -04:00
Skyler SouthernandClaude Fable 5 58efcebd83 fix: resolve_seed matches bare names against ()-decorated callable labels
Callable nodes are labeled with a trailing "()" (e.g. classifyProperty()),
so a bare-name query like "classifyProperty" falls through the exact-label
pass and then ties with any prefix sibling (classifyPropertySafe()) in the
contains pass, returning "No unique node match" even though exactly one
callable with that name exists.

Add a bare-name pass between exact-label and exact-source matching that
compares query and label with the trailing "()" stripped from each. Bare
queries now resolve decorated labels and vice versa; genuine duplicates
still return None.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 09:14:28 -04:00
SafiandClaude Sonnet 4.6 cce2673021 fix: LLM calls-edge direction reversal and ghost-node merge
llm.py: add explicit edge direction rule to extraction system prompt —
source = actor (caller/importer/subclass), target = acted-upon (callee/
imported/base). LLM was systematically emitting callee->caller for calls
edges because the schema never stated direction semantics.

build.py: extend ghost-node merge to catch LLM nodes that populate
source_location (bypassing the old None check). Now uses _origin=="ast"
as the canonical signal — AST nodes always win; any non-AST node sharing
(basename, label) with an AST node is collapsed into the AST canonical.
Fixes LLM bare-stem IDs (bpe_get_pairs) surviving alongside AST
parent-qualified IDs (mingpt_bpe_get_pairs) and carrying reversed edges.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-11 12:03:59 +01:00
Timo DerstappenandCursor d26a32a30c fix(extract): collect files in a single pruned walk instead of one rglob per extension (#1261)
collect_files ran one full recursive rglob pass per supported extension
(~85 walks), descending into node_modules/.git/venv and filtering those
paths only after enumerating them, and re-evaluated gitignore patterns
per file without the shared cache.

Replace the loop with a single os.walk that prunes noise dirs (and, when
no negation patterns exist, ignored dirs) in place -- the same pattern
the follow_symlinks=True branch and detect.py's scan walk already use --
and pass the shared _is_ignored cache. Extension matching switches to
p.suffix in _EXTENSIONS, matching the follow_symlinks branch and
preserving the .f/.F Fortran case distinction.

Synthetic benchmark (200 source files + 5,000-file node_modules):
0.295s -> 0.007s, identical result set.

Tests: parity oracle against the old implementation on the fixtures and
on a synthetic tree (noise dirs, hidden dirs, gitignore negation), plus
a scandir-counting test asserting each directory is read at most once
and noise dirs are never entered.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 10:58:44 +02:00
Timo DerstappenandCursor 7b5e625066 fix(cache): require whole --- lines as frontmatter delimiters (#1259)
_body_content used substring checks (startswith("---") / find("\n---")),
so `----` thematic breaks and `--- text` prose lines were mistaken for
frontmatter delimiters and everything above them was silently excluded
from the hash -- edits there never invalidated the cache.

Both delimiters must now be a whole line of exactly three dashes
(optional trailing whitespace). For well-formed frontmatter the stripped
body stays byte-identical to the previous implementation, so existing
semantic-cache hashes do not churn.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 10:49:11 +02:00
Timo DerstappenandCursor 8401c50178 fix(cache): namespace AST cache by graphify version (#1252)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 09:45:05 +02:00
Timo DerstappenandCursor 444d73e1c8 fix(global-graph): rewire edges to deduplicated external nodes (#1250)
global_add deduplicates external-library nodes (no source_file) by label
against externals already in the global graph, but dropped every edge
incident to a skipped node. Each repo after the first lost its edges to
shared externals, so cross-repo "what uses library X" queries only saw
the first-added repo.

Build a remap from each deduplicated external to the surviving global
node and rewrite edge endpoints through it before add_edge, skipping
self-loops introduced by the remapping.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 09:36:38 +02:00
Timo DerstappenandCursor 4f8de1e42b fix(dedup): pick pass-2 winner from the verified pair only (#1247)
Pass 2 selected the merge winner from the union of both normalized-label
groups, so never-compared same-label/cross-file nodes could be pulled
into the union, bypassing the #1046/#1178 guards. Pick the winner from
[node, neighbor] only; group members that belong together still merge
via pass 1 (same file) or their own verified comparison.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 09:30:36 +02:00
Vlladie Condeno 7cb5e86fc1 fix: anchor extraction cache at --out root so external output leaves the scanned project clean
graphify extract <path> --out R is documented to send all output to
R/graphify-out/, but the AST and semantic extraction caches were still
anchored at the scanned project (cache_root=target / root=target). That
re-created a graphify-out/ directory inside the project the user
explicitly asked to keep clean.

Anchor both caches at out_root instead. With --out unset, out_root
equals target, so existing in-project behavior is unchanged.

Adds test_extract_out_keeps_project_root_clean: runs extract from a
project root with --out pointing elsewhere and asserts the artifacts
land under --out while the project directory stays byte-identical.
2026-06-11 14:02:32 +08:00
PCeltide edfe5812f7 fix(claude-cli): handle JSON-array envelope from Claude Code CLI >= 2.1
`claude -p --output-format json` now emits a JSON array of streamed event
objects instead of a single envelope dict, so `_call_claude_cli` crashed
with `'list' object has no attribute 'get'` on every chunk. Add a shared
`_claude_cli_envelope` helper that normalizes both shapes (extracts the
terminal {"type":"result"} object from an array) and use it at both CLI
call sites.
2026-06-11 04:09:21 +05:30
SafiandClaude Sonnet 4.6 565026d3d1 fix(ci): add cluster-only step to generate GRAPH_REPORT.md in release-graph
extract intentionally stops at graph.json; GRAPH_REPORT.md requires cluster-only.
Use --no-label to skip LLM community naming (no API key needed in CI).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 22:01:12 +01:00
SafiandClaude Sonnet 4.6 ba1921fe76 fix(ci): skip .md/.txt files in release-graph to avoid LLM API key requirement
graphify/skills/ contains 126 markdown files that trigger semantic extraction.
Add a temporary .graphifyignore entry during CI to keep the build pure AST.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 21:55:16 +01:00
Safi e6d2dc4d6f release 0.8.37 2026-06-10 21:45:02 +01:00
SafiandClaude Sonnet 4.6 1513e6271a fix(ci): correct three bugs in release-graph workflow
- extract graphify/ (code only) instead of . to avoid LLM API key requirement;
  the repo root contains docs/skills/.md files that trigger semantic extraction
- use --out . so output writes to ./graphify-out/ not ./graphify/graphify-out/
- remove --out from export html (flag does not exist; HTML auto-written next to graph)
- drop nonexistent --code-only flag from extract command
- add comments explaining each flag's behavior

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 21:15:00 +01:00
SafiandClaude Sonnet 4.6 7182b18c35 ci: add release-graph workflow to ship self-graph as release asset
Runs graphify against its own source on every GitHub release (AST-only,
no API cost) and attaches graph.json + graph.html + GRAPH_REPORT.md as
graphify-self-graph.tar.gz to the release. Also supports manual runs via
workflow_dispatch, uploading the bundle as a 7-day workflow artifact.

Closes #1238

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 21:07:38 +01:00
SafiandClaude Sonnet 4.6 a37672f25f fix: obsidian crash, NFC/NFD dedup, JSON data nodes, OpenAI temperature, JSON config detection
- export.py: guard to_obsidian/to_canvas against dangling community member IDs
  (KeyError crash when a node in communities dict is absent from graph, #1236)
- detect.py: NFC-normalize path before hashing Office sidecar filename to fix
  macOS NFC/NFD mismatch causing --update to re-extract all Office files (#1226)
- extract.py: add _is_config_json() to skip data JSON files (only extract
  package.json, tsconfig.json, eslint, deno, JSON Schema etc.) eliminating
  561 orphan key-nodes on large repos (#1224)
- llm.py: add GRAPHIFY_LLM_TEMPERATURE env var + _resolve_temperature() helper;
  auto-omit temperature for o1/o3/o4/gpt-5 reasoning models that reject temp=0;
  mirrors GRAPHIFY_MAX_OUTPUT_TOKENS precedence pattern (#1191)
- tests: 20 new regression tests across obsidian, detect, extract, llm_backends

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 19:31:47 +01:00
SafiandClaude Sonnet 4.6 5504c84324 perf/fix: replace datasketch with pure-numpy MinHash; memoize detect ignore checks
- graphify/_minhash.py: self-contained MinHash/MinHashLSH using pure numpy,
  byte-identical hash math to datasketch (sha1_hash32, Mersenne-prime permutation).
  Drops datasketch + scipy transitive dep — eliminates EDR hang on Windows where
  numpy.testing platform.machine() subprocess spawn was intercepted at import time
- dedup.py: import from graphify._minhash instead of datasketch
- pyproject.toml: replace datasketch>=1.6 with numpy>=1.21
- detect.py: memoize _is_ignored/_eval results in a dict[Path,bool] cache per
  detect() call; each unique ancestor dir evaluated once across all sibling files,
  eliminating ~42M redundant fnmatch calls on large repos (~34% whole-run speedup)
- tests/test_minhash.py: 11 tests including import-isolation guard asserting scipy
  and numpy.testing are not loaded after import graphify.dedup
- tests/test_detect.py: 2 cache tests — correctness (cached==uncached with negation
  patterns) and hit-count (each dir evaluated exactly once across siblings)

Closes #1234, closes #1235

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 15:50:38 +01:00
SafiandClaude Sonnet 4.6 6695f0aefd fix: security hardening, dedup correctness, and large-graph support
- security.py: replace global socket.getaddrinfo monkey-patch with per-connection
  _SSRFGuardedHTTPConnection/HTTPSConnection subclasses (thread-safe, closes TOCTOU)
- security.py: add GRAPHIFY_MAX_GRAPH_BYTES env var override for 512MB cap (MB/GB suffix
  supported); improve cap error message to cite the env var
- llm.py: wrap untrusted source files in XML delimiters with sha256 fingerprint;
  neutralise jailbreak sentinel tokens to mitigate prompt injection
- dedup.py: skip code nodes in label-based dedup passes; code symbols now deduplicated
  by ID only, preventing distinct same-named symbols from merging
- extract.py: cross-file calls resolution now consults import evidence before bailing
  on ambiguous callee names; emits EXTRACTED edges when named import is unambiguous
- analyze.py: extend _BUILTIN_NOISE_LABELS with stdlib types and modules
- __main__.py: CLAUDE.md template uses MANDATORY language for graphify-first rule;
  PreToolUse hook message hardened to imperative; graphify export html auto-falls
  back to community-aggregation view when graph.json exceeds size cap
- tests/test_pg_introspect.py: add importorskip guard for tree_sitter_sql

Closes #1211, #1210, #1205, #1219, #1227; resolves discussion #1019

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 12:45:20 +01:00
nucleusjay 39afb2d8ef Wire bandit and pip-audit into CI
bandit, pip-audit, and safety are already declared in the dev dependency
group but nothing in CI invokes them, so a new HIGH-severity finding or
a newly-disclosed CVE in a pinned dep can land without anyone noticing
until the next manual audit.

Add a security-scan job that runs bandit (-ll, HIGH-severity only) and
pip-audit (--strict) on every push and PR. Marked continue-on-error so
this doesn't block PRs on pre-existing findings -- a follow-up should
do the cleanup pass and flip the flag.

safety intentionally omitted: it requires a free-tier API key for the
new commercial backend, which is a setup burden for forks. pip-audit
covers the same ground using the PyPI JSON advisory feed and OSV.
2026-06-09 03:36:44 -04:00
nucleusjay 524289fb66 Fix two latent bugs: merge-chunks output and manifest data loss
1. graphify merge-chunks dumped the entire node list to the terminal
   instead of the node count. __main__.py concatenated merged['nodes']
   (a list of dicts) into an f-string where it clearly meant
   len(merged['nodes']) -- the other two values in the same line use
   len() correctly.

2. global_graph._load_manifest silently returned a fresh empty manifest
   on any JSON parse error. That is reachable through normal interrupted
   writes (the manifest is rewritten in full on every global_add /
   global_remove, with no fsync or atomic rename), and the failure mode
   is total data loss: every tracked repo disappears from
   ~/.graphify/global-manifest.json on the next read.

   Back the corrupt file up to <path>.corrupt.<unix_ts> and print to
   stderr before returning the empty default. Users can then recover
   manually and the failure is visible rather than silent.
2026-06-09 03:36:19 -04:00
nucleusjay 6f6d74d42d Pin tree-sitter dependency version ranges
All 27 tree-sitter-* deps were unversioned in pyproject.toml. Users
installing via 'pip install graphifyy' (the README's primary install
path) bypass uv.lock entirely and resolve whatever tree-sitter-*
versions PyPI happens to serve. A breaking minor bump in any grammar
package can land in user installs without notice.

Add explicit lower bounds (matching uv.lock) and upper bounds one
minor above (or one major above for 0.x packages with frequent breaks).
Ranges chosen to allow patch updates without re-pinning while blocking
incompatible major/minor jumps.
2026-06-09 03:35:45 -04:00
SafiandClaude Sonnet 4.6 137bc2d951 release 0.8.36
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 23:58:08 +01:00
SafiandClaude Sonnet 4.6 e477825a97 fix: three correctness bugs — cycle hang, label token budget, fuzzy dedup prefix merge
- analyze.py: pass length_bound=max_cycle_length to nx.simple_cycles() so
  networkx prunes during enumeration instead of post-filtering; drops report
  generation from never-returns to ~0.1s on dense graphs (#1196)

- llm.py: replace hardcoded min(40+16*n,4096) label_communities token budget
  with _resolve_max_tokens(min(64+24*n,8192)) — 24 tok/community covers 5-word
  JSON entries; 8192 cap fits 16k-context models; env var now honoured (#1200)

- dedup.py: add prefix-extension guard in Pass 2 and _llm_tiebreak — skip merge
  when one normalised label is a strict prefix of the other (getActiveSession /
  getActiveSessions, parseConfig / parseConfigFile). Option (a) rejected: dropping
  the >=12 early-out from _short_label_blocked breaks test_typo_merged (#1201)

- tests/test_dedup.py: two new regression tests verifying prefix guard fires for
  extension pairs and does not fire for same-length typo pairs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 23:49:16 +01:00
freiit 3602c8031e fix: guard label/text normalizers against None node labels (#1195)
Guards _norm, _norm_label, and _strip_diacritics against None node labels that cause TypeError in unicodedata.normalize(). Fixes #1194. Consistent with existing security.py:270 precedent.

Co-authored-by: freiit <freiit@users.noreply.github.com>
2026-06-08 23:22:15 +01:00
EirikWolfandEirikWolf 7477b469ee feat: extra_body for custom providers + multi-batch label_communities (#1197)
Adds extra_body parameter support for custom/OpenAI-compat providers so users can pass provider-specific params (e.g. thinking budget for Claude via Bedrock compat). Adds multi-batch label_communities for 16k-context models — batches multiple community descriptions into a single LLM call instead of one per community. Partial batch failures are handled gracefully.

Co-authored-by: EirikWolf <EirikWolf@users.noreply.github.com>
2026-06-08 23:22:00 +01:00
Gal Shubeli 418604f32a refactor: rename neo4j_* push vars to push_* (shared by neo4j + falkordb)
The --push/--user/--password export flags feed both the neo4j and falkordb
dispatch branches, so the neo4j_ prefix was misleading - a neo4j_password that
reads FALKORDB_PASSWORD made no sense. Renamed to push_uri/push_user/
push_password, and the password env lookup now reads the backend-specific var
(FALKORDB_PASSWORD for falkordb, NEO4J_PASSWORD otherwise) instead of OR-ing both.
2026-06-08 13:05:24 +03:00
Gal Shubeli 12615226e4 fix: correct FalkorDB cypher.txt import guidance
The no-push 'graphify export falkordb' path advertised
'redis-cli -x GRAPH.QUERY graphify < cypher.txt', but FalkorDB rejects that
with 'query with more than one statement is not supported' - cypher.txt is a
multi-statement Neo4j script. The individual statements ARE valid OpenCypher
(verified by loading them one at a time), only bulk script import is unsupported.

Message + skill docs now say so and point to --push (the verified load path).
2026-06-08 12:59:26 +03:00
Gal Shubeli bf0ace1759 feat: add --falkordb/--falkordb-push skill shorthands, use falkordb:// URI
Makes the FalkorDB option a first-class sibling of Neo4j in the agent skill,
not just the export CLI:

- --falkordb / --falkordb-push shorthands documented in core.md + the shared
  exports.md reference, so they render into all modular platform skills and
  read exactly like --neo4j / --neo4j-push. (The aider/devin monoliths are
  diff-frozen vs v8 by skillgen's roundtrip guard, so they are left untouched.)
- README command reference switched to the /graphify ./raw --falkordb-push form.
- Documented URI scheme is now falkordb://localhost:6379; the scheme is only
  informational (host/port are parsed out), so redis:// or a bare host:port
  remain equivalent. Regenerated skill artifacts + expected/ snapshots.
2026-06-08 12:56:20 +03:00
Rasmus Bækgaardandbakgaard 29e57cd295 feat: add .slnx solution file support (#1189)
Adds support for the XML-based `.slnx` solution format (VS 2022 17.13+ replacement for `.sln`). Extracts project references as `contains` edges and build dependencies as `imports` edges. XXE-protected XML parsing with size cap. Wired into `_DISPATCH` and `CODE_EXTENSIONS`. 6 new tests passing.

Co-authored-by: bakgaard <bakgaard@users.noreply.github.com>
2026-06-08 10:35:32 +01:00
Jan 42d1b8d02f feat: add graphify-mcp console script entry point (#1190)
Adds `graphify-mcp` as a named console script pointing to `graphify.serve:_main`, making the MCP stdio server directly invocable as a first-class CLI command from uv tool / pipx installs. MCP client configs can now use `"command": "graphify-mcp"` instead of `python -m graphify.serve`.

Co-authored-by: jr2804 <jr2804@users.noreply.github.com>
2026-06-08 10:35:21 +01:00
SafiandClaude Sonnet 4.6 8a04560bf5 fix: remove non-spec trigger: field from skill frontmatter (#1180)
The Agent Skills spec only defines name, description, license,
compatibility, metadata, and allowed-tools as valid frontmatter fields.
The trigger: /graphify line was non-spec, silently ignored by spec-
following hosts, and flagged by agentskills validate CI checks.

- gen.py: removed trigger emission from _render_frontmatter; added
  _is_trigger_line() helper for roundtrip allow-list
- fragments/core/aider.md: removed hardcoded trigger: /graphify
- platforms.toml: removed trigger doc comment and trigger="" entries
- test_skillgen.py: replaced trigger-assertion tests with a single
  test asserting no host has trigger: in frontmatter
- Regenerated all 125 skill artifacts

Routing intent is preserved: the description field already contains
"treated as a graphify query first" and "graphify-out/ exists".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 15:49:52 +01:00
SafiandClaude Sonnet 4.6 6dbcb89f3d release 0.8.35
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 14:42:30 +01:00
SafiandClaude Sonnet 4.6 660d2d32cf fix(codebuddy): install SKILL.md in codebuddy install subcommand + fix README hook description
graphify codebuddy install was writing CODEBUDDY.md and settings.json
but not copying the SKILL.md. Added _copy_skill_file("codebuddy") call
to match the --platform codebuddy path. README hook description updated
from "Glob and Grep" to "Bash search and file reads" to match actual
hook matchers (Bash + Read|Glob).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 14:39:16 +01:00
9e1ad425a9 feat: add CodeBuddy platform support (#1136)
Adds graphify skill installation for CodeBuddy (https://www.codebuddy.ai/).
CodeBuddy uses the same agent+hook mechanism as Claude Code.

- graphify codebuddy install — writes ~/.codebuddy/skills/graphify/SKILL.md
  and a CODEBUDDY.md always-on section
- graphify codebuddy uninstall — removes both cleanly
- graphify install --platform codebuddy — same as above
- Registers Bash + Read|Glob PreToolUse hooks in .codebuddy/settings.json
- Full install/uninstall roundtrip tests (35 tests)

Co-authored-by: studyzy <studyzy@gmail.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 14:34:13 +01:00
SafiandClaude Sonnet 4.6 12a9b5e812 fix: prevent fuzzy dedup from collapsing distinct same-named symbols on --update (#1178)
Three-part fix:

dedup.py: Pass 1 exact-merge now skips nodes with an empty source_file.
Previously all no-source_file nodes with the same label landed in one
bucket and were merged, destroying distinct symbols (third-party deps,
standalone functions) that happened to share a short name.

update.md (skillgen + all 13 host variants): the --update merge now
passes both deleted AND changed files to prune_sources, mirroring what
watch._rebuild_code already does correctly. Old nodes for re-extracted
files are pruned before fresh AST is inserted — no fuzzy reconciliation
needed, no cross-file collapse possible.

export.py: anti-shrink guard message now names fuzzy dedup as a
possible cause (not only "missing chunk files"), and advises a full
rebuild as the safe recovery path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 14:26:14 +01:00
Gal Shubeli 7aa300709f feat: add FalkorDB export backend (#1175)
Adds FalkorDB as a sibling option to the existing Neo4j sink, selected via
`graphify export falkordb [--push redis://localhost:6379]`.

- New push_to_falkordb() in graphify/export.py mirrors push_to_neo4j; FalkorDB
  is OpenCypher-compatible so the MERGE/SET upsert queries are identical.
- export falkordb subcommand wired in graphify/__main__.py (cypher.txt when no
  --push, direct push otherwise). Auth is optional; target graph defaults to
  "graphify".
- falkordb optional extra in pyproject.toml (and in the all extra).
- Tests: CLI cypher generation (CI-safe) + real-FalkorDB integration tests that
  skip when no instance is reachable.
- README extras table + command reference and CHANGELOG updated.
2026-06-07 15:03:49 +03:00
SafiandClaude Sonnet 4.6 3744e6e220 release 0.8.34
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 12:51:33 +01:00
SafiandClaude Sonnet 4.6 6a549e42d5 fix: four bugs — affected direction, hook root, glob fish/zsh, manifest drift (#1174 #1173 #1172 #1163)
#1174: affected.py load_graph now forces directed=True before
node_link_graph, matching the identical fix in serve.py and __main__.py.
Undirected graphs (directed:false in graph.json) were causing in_edges
to fall back to a direction-blind scan, missing true callers and
reporting false positives. Regression test added.

#1173: post-commit and post-checkout hook bodies now read
graphify-out/.graphify_root before calling _rebuild_code, falling back
to Path('.') if absent. A scoped build (graphify src/) no longer gets
silently expanded to the full repo on the next commit. Tests added.

#1172: Step 9 cleanup split into rm -f for fixed files and
find -maxdepth 1 -delete for the chunk glob. Under fish/zsh an
unmatched glob aborts the entire rm -f line, leaving temp files on disk.
Fixed in the three skillgen source fragments and regenerated.

#1163: detect_incremental type guard on stored mtime — if the manifest
contains a dict-valued mtime (schema drift from older versions), coerce
to None rather than propagating a non-numeric into comparisons.
Regression test added.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 12:40:44 +01:00
SafiandClaude Sonnet 4.6 a8dbbe59cf fix: land PRs #1170 #1169 #1165 (hooks, sensitive filter, score_nodes)
#1170 — replace nohup with cross-platform Python detach in git hooks.
Git for Windows MSYS has no nohup so post-commit/post-checkout hooks
silently failed. Now uses subprocess.Popen with DETACHED_PROCESS |
CREATE_NEW_PROCESS_GROUP on Windows, start_new_session=True on POSIX.
Quoting-safe (argv list). Fixes #1161.

#1169 — fix _is_sensitive false positives on topic-mentioning filenames.
token-economics-of-recall.md and password-policy-discussion.md were
silently dropped as secrets. Generic keywords (token/secret/password)
now only fire when the keyword ends the filename stem or the stem is
≤2 words. Specific patterns (.env/.pem/id_rsa etc.) remain unconditional.

#1165 — fix multi-word endpoint resolution in _score_nodes.
graphify path "AuthService" "UserRepo" never fired the exact-match bonus
because per-token comparison never equalled the full label. Now joins
normalized tokens and compares against the full label and its tokenized
form. O(1) per node, affects query_graph and shortest_path uniformly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 12:20:36 +01:00
SafiandClaude Sonnet 4.6 f146be3ea2 fix: numpy Python 3.13 pin + codex skill dir (#1154 #1160)
#1154: scope numpy>=2.0 constraint to python_version>='3.13' only.
numpy 1.26.4 ships no cp313 wheel so uv sync falls back to a source
build requiring a C compiler. The marker avoids forcing numpy 2.x on
3.10-3.12 users who have working 1.x environments.

#1160: codex platform skill now installs to .codex/skills/graphify/
instead of .agents/skills/graphify/. The hook already wrote to .codex/
so the skill destination was inconsistent. Propagates automatically
through install/uninstall (both read _PLATFORM_CONFIG dynamically).
Updated all codex-specific test assertions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 12:11:34 +01:00
Leon Aburime 3e8afc9192 docs: detail proposed node summary contents 2026-06-06 20:36:30 -07:00
Leon Aburime 1ad47ec05e docs: add RFC for file-level node summaries 2026-06-06 20:33:35 -07:00
SafiandClaude Sonnet 4.6 079b34da78 docs: update README for Apex, Azure, and PostgreSQL additions
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 01:39:54 +01:00
SafiandClaude Sonnet 4.6 7467c1b6a4 feat/fix: land PRs #1118 #1110 #1159 #1107 #1103 (graph quality + new features)
#1118 — prune stale AST nodes on full re-extraction (#1116)
Stamps every AST-extracted node with _origin="ast" in extract(). On a
full rebuild _rebuild_code drops any AST-marked node absent from the
fresh output even when its source file survives, fixing stale symbols.
Backward-compat: marker-less nodes from pre-1118 graphs survive one
cycle then self-heal.

#1110 — stop reading images and PDFs as garbage in headless extract
Images route through per-backend vision payloads (base64/data-URI/bytes
for claude/openai/bedrock); non-vision backends get _strip_pixels for
graceful degradation. PDFs reuse pypdf. 5MB cap, 20-image chunk limit.

#1159 — Salesforce Apex extractor (.cls, .trigger)
Regex-based extractor: classes, interfaces, enums, methods, triggers,
SOQL/DML edges. No new dependency. Dispatched as .cls and .trigger.

#1107 — Azure OpenAI Service backend (--backend azure)
Uses AzureOpenAI SDK client (from existing openai package). Auto-detects
when AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT both set. Uses
max_completion_tokens (not deprecated max_tokens).

#1103 — live PostgreSQL introspection (--postgres DSN)
graphify extract --postgres "postgresql://..." introspects tables, views,
routines, and FK relations via information_schema (SERIALIZABLE READ ONLY).
Credentials sanitized on error. New graphify[postgres] extra (psycopg3).

Union-resolved llm.py conflict: Azure functions + bedrock images= param.
Fixed test_image_vision.py mock to accept timeout= kwarg (our #1112).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 01:20:38 +01:00
SafiandClaude Sonnet 4.6 7b4c8df6e9 docs: add Streamable HTTP transport section to README (#1155)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 00:47:29 +01:00
SafiandClaude Sonnet 4.6 2a683aac2e feat(serve): add Streamable HTTP transport to MCP server (#1143)
python -m graphify.serve graph.json --transport http --port 8080 serves
the same MCP tools over the Streamable HTTP transport (spec 2025-03-26)
so a single shared process can serve the graph for a whole team.

- _build_server() refactors server registration into a shared factory
  (stdio behavior is byte-for-byte unchanged — all 52 existing tests pass)
- _ApiKeyMiddleware: raw ASGI (not BaseHTTPMiddleware) preserves SSE
  streaming; constant-time compare; RFC-6750 case-insensitive Bearer;
  blank-key normalized to no-auth
- DNS-rebinding protection via TransportSecuritySettings; wildcard binds
  disable it and print an exposure warning when no api-key is set
- session_idle_timeout reaps idle stateful sessions (default 3600s) so a
  long-running shared server does not leak memory on client disconnect
- Dockerfile + .dockerignore for containerized team deployment
- 16 new tests via in-process ASGI test client (importorskip-guarded)
- stdio remains the default; no change for existing setups

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 00:43:40 +01:00
SafiandClaude Sonnet 4.6 4b06fd7bf7 release 0.8.33
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-06 09:40:14 +01:00
SafiandClaude Sonnet 4.6 a380b34739 fix(extract): three graph quality fixes (#1145 #1146 #1147)
#1147 — builtin annotation nodes inflate god-node rankings:
Add _PYTHON_ANNOTATION_NOISE frozenset (str/int/bool/float/bytes/
MagicMock/Mock/AsyncMock/...) and apply it alongside
_PYTHON_TYPE_CONTAINERS in the annotation walker so scalar builtins
and test mocks are never created as nodes or emitted as edges.
Defense-in-depth guard in analyze.god_nodes filters _BUILTIN_NOISE_LABELS
so pre-existing graphs are also protected.

#1146 — package-form imports create disconnected islands:
from pkg import submod is now resolved to a file-level imports_from
edge when submod.py or submod/__init__.py exists on disk. Fix lives
in _collect_python_symbol_resolution_facts: when target resolves to
a __init__.py, each imported name is checked as a potential submodule
file and stored in _SymbolResolutionFacts.module_imports. Applied in
_apply_symbol_resolution_facts using stem-based canonical IDs.

#1145 — AST vs semantic node ID ghost duplicates:
build_from_json now runs a two-pass merge after adding all nodes:
collect AST nodes (source_location set) then find semantic ghosts
(same basename+label, no source_location). Ghosts are removed and
their IDs added to norm_to_id so all edges re-point to the AST node.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-06 09:35:59 +01:00
SafiandClaude Sonnet 4.6 3405c1fb96 feat(install): add amber brain banner on graphify install
TTY-only (suppressed in CI/pipes). Windows ANSI enabled via ctypes.
Wrapped in try/except so it can never crash the install.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 23:46:15 +01:00
SafiandClaude Sonnet 4.6 ec1a3bc9e9 release 0.8.32
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 22:50:47 +01:00
SafiandClaude Sonnet 4.6 23acb41910 docs: bump grammar count to 28 (tree-sitter-hcl added in #1129)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 22:41:19 +01:00
SafiandClaude Sonnet 4.6 e3499e069c docs: add Terraform/HCL to file types table and optional extras (#1129)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 22:37:42 +01:00
SafiandClaude Sonnet 4.6 9c2f2f5663 docs: clarify code-only extract needs no API key (#1122)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 22:34:34 +01:00
SafiandClaude Sonnet 4.6 f85339bcb1 fix(extract): don't require LLM API key for code-only corpus (#1122)
Backend resolution now defers until after file detection. A code-only
corpus (pure AST, zero LLM calls) runs without any API key.
Key validation only fires when needs_llm=True (semantic_files non-empty
or --dedup-llm passed). Error message now names why a key is needed and
notes that code-only corpora need none.

Applied from PR #1123 with one fix: _clear_backend_keys in tests now
also clears AWS_PROFILE/REGION, OLLAMA_BASE_URL to prevent CI flakes
on machines with ambient credentials.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 22:28:57 +01:00
SafiandClaude Sonnet 4.6 3a4bdf54cc fix(install): route kiro install/uninstall through shared progressive helper (#1142)
_kiro_install was using a bare write_text that bypassed _copy_skill_file,
so the references/ sidecar and .graphify_version stamp were never written
despite kiro declaring skill_refs: "kiro". This left SKILL.md with 8 dead
references/*.md pointers on every install.

Fix: call _copy_skill_file("kiro", project=True) for the skill+sidecar+stamp,
keep the steering-file block inline. Uninstall now calls _remove_skill_file
which also cleans .graphify_version and references/.

Adds regression test asserting SKILL.md + references/ + .graphify_version +
no references.tmp + steering file, and that uninstall removes all of them.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 22:15:09 +01:00
SafiandClaude Sonnet 4.6 6e860e018a docs: clarify .graphifyignore vs .gitignore fallback behaviour (#1137)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 22:06:02 +01:00
SafiandClaude Sonnet 4.6 b368c0eb25 revert: remove importorskip now that uv.lock includes tree-sitter-hcl
CI installs --all-extras so all 8 Terraform tests run fully.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 21:46:25 +01:00
SafiandClaude Sonnet 4.6 78e70ea194 chore: update uv.lock with tree-sitter-hcl in all and terraform extras
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 21:45:34 +01:00
SafiandClaude Sonnet 4.6 30f6f6fb85 fix(tests): skip Terraform tests when tree-sitter-hcl not installed
pytest.importorskip at module level matches the pattern used for other
optional extras (sql, dm) so CI passes without the optional dep.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 21:43:30 +01:00
SafiandClaude Sonnet 4.6 200edecea5 feat(extract): add Terraform/HCL AST extraction via tree-sitter-hcl (#1129)
Adds extract_terraform() for .tf/.tfvars/.hcl files. Nodes: resources,
data sources, modules, variables, outputs, providers, locals. Edges:
contains, references (interpolation), depends_on. Node IDs are
directory-scoped for cross-file resolution. tree-sitter-hcl added as
optional extra (graphify[terraform]) matching sql/dm precedent.
8 tests including .tfvars documented no-op behaviour.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 21:38:56 +01:00
SafiandClaude Sonnet 4.6 fff1c980ac fix: correct language grammar count to 27 tree-sitter grammars in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:15:20 +01:00
SafiandClaude Sonnet 4.6 75c4de7759 honour GRAPHIFY_API_TIMEOUT in claude-cli and Anthropic SDK backends (#1112)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 10:45:01 +01:00
William Mcgrann 830f0396d8 build: add version floors to networkx, datasketch, rapidfuzz
Adds lower-bound version constraints matching tested versions in uv.lock. networkx>=3.4 is the binding constraint (edges= kwarg on node_link_data introduced in 3.4). rapidfuzz>=3.0 guards against the 2.x→3.x API break in rapidfuzz.distance. datasketch>=1.6 is conservative but correct. Also fixes stale uv.lock version metadata (0.8.30→0.8.31).
2026-06-05 10:14:46 +01:00
SafiandClaude Sonnet 4.6 863f0c1e9f update README: manifest.json is now portable, safe to commit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 23:08:55 +01:00
Safi 7a588fb1d2 release 0.8.31 2026-06-03 21:04:01 +01:00
SafiandClaude Sonnet 4.6 b7a9b8158c document query logging and hook interpreter pinning in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 21:04:01 +01:00
SafiandClaude Sonnet 4.6 3a90ac2784 add query logging to ~/.cache/graphify-queries.log (#1128)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 21:04:01 +01:00
Dennis Cornwell 25df580061 fix: relativize manifest, .graphify_root, and cache source_file fields (#777)
Fixes #777. Relativize manifest keys, .graphify_root, and cache source_file fields on persist; re-anchor on load. In-memory callers still see absolute paths. Symlink round-trip fixed in follow-up commit 8f09326.
2026-06-03 21:03:06 +01:00
SafiandClaude Sonnet 4.6 0fdfdedcaa harden hook interpreter detection against injection and unquoted exec
Per adversarial review of the #1127 fix:

- Apply the filesystem-path allowlist to sys.executable before embedding it in
  the generated hook script. Paths with metacharacters outside [a-zA-Z0-9/_.@:\-]
  (spaces, dollar signs, backticks, semicolons) are replaced with an empty string
  so the pinned probe is safely skipped rather than injecting shell commands that
  execute on every git commit.
- Change _PINNED='...' to single-quote assignment so no shell expansion can occur
  even if a character slipped through the allowlist (belt and suspenders).
- Quote $GRAPHIFY_PYTHON in both nohup exec lines so paths with spaces work
  (common in Windows C:\Program Files\... installs).
- Update test to assert the sanitized value, not raw sys.executable, so the test
  stays correct after any future sanitization changes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 15:40:06 +01:00
SafiandClaude Opus 4.8 2d5a10c0a2 also probe graphify-out/.graphify_python in hook interpreter detection
The issue reporter correctly noted that the hooks never consulted
graphify-out/.graphify_python -- the runtime interpreter source the skill and
README already rely on. Added as a second probe (after the pinned sys.executable,
before the launcher shebang and python3/python fallbacks). This covers Windows/Git
Bash where the uv-tool launcher is a binary with no parseable shebang, and where
the pinned exe may go stale after a reinstall.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 15:40:06 +01:00
SafiandClaude Opus 4.8 88bb1864aa fix hook install silent no-op for uv tool and pipx installs (#1127)
graphify hook install generated scripts that resolved the Python interpreter
purely at git-trigger time via 'command -v graphify'. GUI git clients (VS Code,
GitKraken), CI runners, and non-login shells often run with a minimal PATH that
omits ~/.local/bin -- the uv-tool / pipx launcher location. command -v graphify
returned empty, the python3/python fallbacks could not import graphify (it lives
only in the isolated venv), and the hook silently exited 0 with no output.

Fix: embed sys.executable of the currently-running install process as a pinned
first probe. Since 'graphify hook install' itself runs under the correct isolated
interpreter, sys.executable is always the right path. It is validated at
hook-runtime via 'import graphify' before use, so a stale pinned path safely
falls through to the existing dynamic detection rather than breaking the hook.

Also make the final fallback loud: print a diagnostic to stderr before exiting 0
so the failure is visible rather than invisible.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 15:40:06 +01:00
Safi 1b21368250 update .gitignore: exclude paper/ - keep local only 2026-06-03 15:40:02 +01:00
SafiandClaude Opus 4.8 724f1e3186 release 0.8.30
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 00:26:14 +01:00
SafiandClaude Opus 4.8 cb5e701c67 make incremental extract tests deterministic under a real LLM env key
test_manifest_written_after_extract assumes a docs corpus fails with no LLM
backend, but _run inherited the developer's environment. With a real
ANTHROPIC_API_KEY exported and the anthropic package present (now pulled by
[all]), the claude backend was detected and the extract succeeded, breaking the
'no backend' assertion. Strip the backend-selecting env vars in _run so the
tests hold regardless of the developer's shell. CI has no keys set, so it was
green there already.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 00:20:39 +01:00
SafiandClaude Opus 4.8 631a6d4a67 document the anthropic extra in the README and changelog the unreleased fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 00:13:25 +01:00
SafiandClaude Opus 4.8 250834a0c4 add anthropic extra and fix backend-missing hints for uv tool installs
uv tool install graphifyy runs graphify in an isolated venv, so when a backend
needs anthropic/openai/boto3 the old 'Run: pip install anthropic' advice never
reached it. Worse, claude was the only backend with no [extra] at all, so a user
with ANTHROPIC_API_KEY set could not satisfy it without --with anthropic.

Add an anthropic optional extra (and include it in [all]), and replace the
package-missing ImportError messages with a shared _backend_pkg_hint that points
at 'uv tool install graphifyy[<extra>] --force' first, then the pip/venv path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 00:08:03 +01:00
SafiandClaude Opus 4.8 5cc7ec8a23 close the Read-tool graph bypass with a Read/Glob PreToolUse hook
The Bash search hook only nudges grep/rg/find, so an agent that answers a
codebase question by Read-ing many source files one by one (the most common way
the graph gets skipped) slips right past it (#1114). Add _READ_SETTINGS_HOOK
matching Read|Glob: it fires only when graphify-out/graph.json exists, only for
a source/doc file outside graphify-out/, injects the same query-first
additionalContext, and never blocks (every branch fails open). Install and
uninstall now register and dedup both hooks idempotently.

Implemented independently rather than merging the community PR #1120; same idea,
our own hook (Read/Glob only, no fragile multi-file cat/head/tail heuristic).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 00:00:33 +01:00
SafiandClaude Opus 4.8 9a298c5a32 write antigravity rules and workflows on project-scoped install
graphify install --project --platform antigravity went through the skill-only
branch (grouped with copilot/pi/kimi), so it copied SKILL.md but never wrote
.agents/rules/graphify.md or .agents/workflows/graphify.md - antigravity's
always-on layer - even though the project uninstall path removes them. Extract
the frontmatter + rules + workflows writes into _antigravity_finalize and call
it from both the global antigravity install and the project-scoped path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 23:48:54 +01:00
SafiandClaude Opus 4.8 345e1122d3 release 0.8.29
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 23:19:48 +01:00
SafiandClaude Opus 4.8 90286ab735 document the progressive-disclosure split and security fixes in CHANGELOG
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 22:50:33 +01:00
SafiandClaude Opus 4.8 d5d49f3764 add end-to-end test that gemini install leaves no dead reference pointer
Locks the body<->refs coupling: gemini ships claude's lean skill.md body but
resolves references through a separate path, so a real install with the real
claude bundle must leave every references/ pointer in SKILL.md resolvable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 22:50:33 +01:00
SafiandClaude Opus 4.8 763b673350 tighten F2 and F3 from review: bounded decompression, ollama DNS + clean error
F2: replace the header-trust ratio check with an authoritative bounded
streaming-decompression pass. The zip central-directory sizes are
attacker-controlled, so a member that under-declares its size could dodge the
declared-size checks; now every member is stream-decompressed with a hard byte
ceiling, so actual expansion past the cap is caught regardless of the headers.
The cheap declared-size pre-filter stays as a fast reject for honest bombs.

F3: _validate_ollama_base_url now resolves the host, so an alias that points at
a link-local/metadata IP is blocked too, not just literal IPs. The extract
command gains an early gate that turns the metadata block into a clean
'error: ...' exit(2) instead of a deep traceback; a warn toggle keeps the
single user-facing LAN warning in the in-flow call.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 22:50:33 +01:00
SafiandClaude Opus 4.8 46a1d4cabb harden ollama metadata egress and cpp path handling (F3, F5)
F3: OLLAMA_BASE_URL pointing at a link-local or cloud-metadata address
(169.254.x, metadata.google.*, 0.0.0.0) now fails closed instead of only
warning, since no real Ollama host lives there and it is a classic SSRF
target. General LAN hosts still warn-and-allow.

F5: the Fortran C-preprocessor call now passes an absolute path. cpp has no
'--' end-of-options terminator, so an attacker-named corpus file like
'-I/etc/x.F90' could otherwise be parsed as a cpp option; an absolute path
always begins with '/' and cannot be.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 22:23:15 +01:00
SafiandClaude Opus 4.8 c50ffc2285 cap untrusted office/PDF parsing to stop zip-bomb DoS (F2)
.docx/.xlsx are zip+XML containers parsed during a corpus scan with no size
guard, so a few-KB zip-bomb could decompress to gigabytes and OOM-kill the
process. Screen every office/PDF file before openpyxl/python-docx/pypdf touch
it: an on-disk size cap, a total-uncompressed cap, and a compression-ratio
check on the archive members. Files that exceed the caps are skipped (treated
as empty) rather than parsed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 22:19:17 +01:00
SafiandClaude Opus 4.8 e3993e4801 validate custom-provider base_url and gate project-local providers (F1)
A custom provider's base_url is where the full corpus and the user's API key
are sent. A project-local ./.graphify/providers.json travels with a cloned or
shared repo, so loading it silently was a corpus/key exfiltration channel.
Require GRAPHIFY_ALLOW_LOCAL_PROVIDERS=1 to load the project-local file (the
user's own ~/.graphify/providers.json stays trusted), reject non-http(s)
schemes on load and on 'provider add', and warn on plaintext-http egress. We
deliberately do not apply the ingest SSRF guard here so legitimate on-prem
https LLM gateways still work.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 22:16:58 +01:00
SafiandClaude Opus 4.8 4a200159af ship the references sidecar for gemini installs
gemini has no _PLATFORM_CONFIG entry and installs claude's skill.md body
verbatim. Since #1121 that body is the lean progressive core that links to
references/, but _packaged_skill_refs_dir returned None for gemini, so the
install laid down a SKILL.md with 8 dead reference pointers. Resolve gemini
to the claude references bundle (the same body it already ships) and guard
it in test_claude_twins_ride_the_claude_bundle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 22:10:08 +01:00
SafiandClaude Opus 4.8 e35b0aca2a remove the claude skill tree on uninstall, not just the CLAUDE.md section
claude_uninstall only stripped the CLAUDE.md section, so `graphify uninstall`
and `graphify claude uninstall` orphaned the whole installed skill tree
(SKILL.md + references/ + version stamp) - gemini_uninstall already removes its
skill, this makes claude consistent. The #1121 split made the orphan a 10-file
directory; this restores the removal that the alternative PR #1119 had. Scoped
name removal preserves sibling user files; project-scope uninstall passes
project=True so it never touches the user-scope skill.

Verified: claude/bare uninstall now remove the tree and keep a sibling
user_notes.md; full suite 1755 passed; real extract still builds a clean graph.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 21:45:42 +01:00
SafiandClaude Opus 4.8 4806c1ee7e guard the last tomllib import in test_install_references for Python 3.10
Same 3.11+-stdlib issue as gen.py: this test imported tomllib directly, failing
the 3.10 job. Fall back to tomli on <3.11.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 21:36:53 +01:00
SafiandClaude Opus 4.8 097b50a5d1 give the test job full git history and lock tomli for 3.10
test_skillgen.py (added in #1121) reads pre-split skill bodies from the
immutable baseline commit via `git show`, and on Python 3.10 imports tomllib
via the tomli fallback. The test job used a shallow checkout (no baseline tree)
and the lock didn't carry tomli, so the 3.10 job failed two ways. Add
fetch-depth: 0 to the test job (mirroring skillgen-check) and lock tomli under
the python_version < 3.11 marker so --frozen sync installs it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 21:33:35 +01:00
SafiandClaude Opus 4.8 adfe8f0794 make skillgen's toml import work on Python 3.10
gen.py imported tomllib unconditionally, but that is 3.11+ stdlib only and
graphify supports (and CI tests) 3.10 - so importing tools.skillgen.gen, and
thus collecting test_skillgen.py, crashed the 3.10 test job with
ModuleNotFoundError. Fall back to the tomli backport on <3.11 and add tomli to
the dev group under that marker. Verified the fallback loads and parses with
tomllib forced absent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 21:12:43 +01:00
SafiandClaude Opus 4.8 6137cdba43 harden _always_on against missing blocks and pin skillgen baselines
R1: the 6 always-on blocks were read into module-level constants at import,
so a missing/corrupt always_on/*.md crashed `import graphify.__main__` and
bricked every CLI command, not just install. Make _always_on lazy + lru_cached,
raising a clear "reinstall" error only on the install path that needs the block;
a module __getattr__ keeps the legacy constant names importable for the tests.
Verified: deleting a block no longer crashes `graphify --version`.

skillgen baselines: the self-check guards pinned to the moving `origin/v8` ref,
which stops pointing at the pre-split state once the split lands on v8 (the
always-on-roundtrip guard then fails in CI and monolith-roundtrip goes vacuous).
Pin _v8_baseline_ref, ALWAYS_ON_BASELINE_REF, and the two monolith roundtrip_refs
to the immutable pre-split commit SHA, matching the stated "does not track HEAD"
intent; update the 4 tests that asserted the old ref string.

R2: add tests/test_wheel_packaging.py - build the wheel and assert every
references bundle and always-on block ships in it, so a package-data glob miss
can't pass the repo-tree guards yet hard-exit `graphify install` for real users.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 21:08:11 +01:00
Soham Patankar fbe1e9977f feat(skills): progressive-disclosure split for all platforms (generator + drift fence) (#1121)
All-platform progressive-disclosure skill split + generator (addresses #1106).

Splits each platform's skill into a lean core (~615 lines, full default pipeline inline) + on-demand references/, generated from a single source via tools/skillgen with a CI/pre-commit drift gate. 13 hosts split, aider/devin stay monoliths. Also fixes the stale bare-path bugs across the previously hand-maintained variants and moves the always-on blocks into packaged markdown.

Verified: all 5 generator guards pass, byte-verbatim load-bearing slices, lean cores self-sufficient on the default path across all 13 split hosts, references gated to non-default branches, description preserves the graphify-out-query-first clause. Supersedes #1119 (Claude-first subset).

Known follow-up applied on top: harden _always_on() against a missing packaged file so a partial install can't brick the CLI.
2026-06-02 20:48:13 +01:00
SafiandClaude Opus 4.8 47042beb05 use shields.io pepy badge so downloads show 1.2M not rounded 1M
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 22:23:41 +01:00
SafiandClaude Opus 4.8 6a3b9e146d switch downloads badge to pepy.tech
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 22:21:21 +01:00
SafiandClaude Opus 4.8 efda79a3b1 add community-ID stability fix to 0.8.28 changelog
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 22:16:02 +01:00
SafiandClaude Opus 4.8 f5f3a1cc59 stabilize community IDs so identical groupings get identical labels (#1090)
Follow-up to the file-ordering fix. The from-scratch build writes each node's
community field straight from cluster()'s enumerate() after a STABLE size-sort,
so the hundreds of equal-sized small communities in a sparse graph were ordered
by the partitioner's (not seed-stable) enumeration order. Their integer IDs
permuted run-to-run, which reads as 77-88% "community churn" in a per-node cid
diff even though the actual grouping is reproducible.

Add a tuple(sorted(nodes)) tiebreak to make the sort a total order, so an
identical grouping always yields identical community IDs. Verified: with the
partition returned in shuffled order across 5 runs, the node->cid map is now
identical. (A separate ~0.06% community-count drift remains - likely
non-canonical edge weights upstream - tracked separately.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 21:54:11 +01:00
SafiandClaude Opus 4.8 1d4e11226f make tree-sitter-dm an optional extra to fix default install (fixes #1104)
tree-sitter-dm (BYOND DreamMaker) publishes only a Windows wheel, so on
Linux/macOS uv/pip compiled it from source and aborted the entire
`uv tool install graphifyy` when a C toolchain or python3-dev was missing.
It is the only core grammar lacking Linux/Mac wheels. Move it from core
dependencies to an optional `dm` extra (also in `all`); the default install
now needs no compiler. extract_dm already imports the grammar lazily with a
graceful fallback, and .dmi/.dmm/.dmf use no tree-sitter, so only .dm/.dme
AST parsing is gated behind the extra.

Also: guard the .dm grammar tests with pytest.importorskip so a plain
`uv sync` (no extras) doesn't hard-fail; bump to 0.8.28 with a changelog
upgrade note; switch the README extras table + type notes from pip to
`uv tool install` (uv is the recommended installer, and pip-into-a-uv-tool-env
is the exact ModuleNotFoundError the README already warns about). 0.8.28 also
ships Kilo Code (#512) and the Dart parser modernization (#1098).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 21:44:59 +01:00
Alexey Z ec3cb5eb3e feat(dart): modernize AST parser, support nested generics and part-of redirection (#1098)
Modernizes the Dart extractor: comment stripping, `part of` redirection, nested-generic-aware extends/with/implements parsing, generic type-argument mapping, and generic call detection.

Verified against current v8: merges cleanly, full suite 1530 passed, and inheritance edges connect to same-file class nodes with no ghost-node splits or dangling edges (consistent with the #1033/#1096 node-ID invariants).
2026-06-01 16:13:36 +01:00
alacasse a8005c218a feat: add Kilo Code support (#512)
Adds Kilo Code as a supported platform: native skill + /graphify command, install/uninstall, and a .kilo tool.execute.before plugin (mirroring the OpenCode integration).

JSONC config is handled non-destructively - existing .kilo/kilo.jsonc is read but never rewritten; automated plugin registration goes to kilo.json, preserving user comments (addresses the Qodo review flag).

Verified locally: full suite 1525 passed, install/uninstall smoke test works.
2026-06-01 16:05:07 +01:00
SafiandClaude Opus 4.8 4b17f199af drop redundant labels-file write in cluster-only
The auto-labeling branch wrote .graphify_labels.json, but the unconditional
write at the end of cluster-only already persists the final labels dict
(LLM or placeholder). Removed the duplicate; no behavior change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 23:44:42 +01:00
SafiandClaude Opus 4.8 1dc5048b71 fold community labeling into llm.py instead of a standalone module
No behavior change. label_communities / generate_community_labels live next
to the backend dispatch (_call_llm, detect_backend) they use, so the lazy
import and separate file are no longer needed. Tests unchanged except the
import path; they still monkeypatch graphify.llm._call_llm.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 23:37:28 +01:00
SafiandClaude Opus 4.8 3922235eba release 0.8.27
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 23:31:50 +01:00
SafiandClaude Sonnet 4.6 c8b329d8f2 auto-name communities with the configured backend in standalone CLI (fixes #1097)
Community labeling was an agent-only step (skill.md Step 5): inside Claude Code
or Gemini CLI the agent names communities itself. Run as a bare CLI
(python -m graphify extract . --backend X), no agent does Step 5, so labels
stayed Community 0/1/2 for every backend.

Add graphify/labeling.py: one batched _call_llm asking the backend for a
{cid: name} map from each community's top node labels (god nodes first),
with per-community placeholder fallback and graceful degradation (no backend,
API error, or malformed reply -> Community N, never crashes).

Wire it in:
- cluster-only auto-labels when no .graphify_labels.json exists (the reported
  repro path); --no-label opts out, --backend=<name> overrides auto-detect
- new `graphify label <path>` subcommand force-regenerates names
- extract prints a hint pointing standalone users at cluster-only

Tests mock the backend (no network): happy path, partial/fenced/malformed
replies, no-backend and error fallback, god_nodes dict shape.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 20:46:39 +01:00
SafiandClaude Sonnet 4.6 ad0c8c0a62 relativize symbol node IDs for root-level files to match spec (fixes #1096)
The #1033 remap relativized file node IDs but symbol IDs still embedded the
absolute parent-dir stem, so a root-level file's symbols became
<rootdir>_main_run while the file node was correctly main and the skill.md
spec (and semantic subagent) wants main_run -- splitting every top-level
file's symbols into AST/semantic ghost pairs.

Extend the remap chokepoint to also canonicalize the symbol stem prefix
(old _file_node_id(path) -> new _file_node_id(rel)), gated by source_file so
two files sharing a prefix cannot cross-contaminate. raw_calls.caller_nid is
rewritten too, since the cross-file call pass consumes it after the remap and
would otherwise dangle. No-op for nested files (immediate parent identical in
absolute and relative form).

The originally-filed root cause (facts-collector path form) was a stale-cache
red herring; the real bug is the symbol-level continuation of #1033.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 17:09:30 +01:00
SafiandClaude Sonnet 4.6 88a8e3bc91 capture TS interface-extends and same-file class heritage (fixes #1095)
Two gaps in TypeScript inheritance:

1. interface heritage is an extends_type_clause node, not class_heritage,
   so the walker never saw it and interface extends produced no inherits
   edge. Add an extends_type_clause branch reusing _ts_heritage_clause_entries
   (handles multiple extends).

2. a same-file superclass has no import alias, so the use-fact resolver
   (which only consulted the import table) dropped it; only imported bases
   resolved. Add a same-file fallback against the file's own symbol_nodes,
   scoped to inherits/implements so it does not duplicate same-file calls
   that already resolve via the call-graph pass. Import resolution still
   takes precedence.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 16:47:52 +01:00
SafiandClaude Sonnet 4.6 690b4e5d3e cap obsidian/canvas filenames to avoid ENAMETOOLONG on long labels (fixes #1094)
to_obsidian and to_canvas built note filenames from node labels with no
length cap, so a label >=255 bytes crashed write_text with OSError. Add a
shared _cap_filename helper that caps on UTF-8 bytes (not chars, so CJK
labels don't slip past) and appends an 8-char hash of the full label when
truncating, so two distinct labels sharing a long prefix stay distinct.
Both safe_name builders route node, community and canvas filenames through
it; wikilinks stay consistent because they read the same filename dict.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 16:41:18 +01:00
SafiandClaude Sonnet 4.6 c898dc62cd match AST file-level node IDs to the skill.md spec (fixes #1033)
AST file nodes were ID'd from the full relative path plus extension
(match_script_pipeline_step_py) while semantic subagents follow the
{parent_dir}_{stem} spec (script_pipeline_step), so every file split
into two disconnected ghost nodes.

Fix at the single remap chokepoint in extract(): file node IDs and all
edge endpoints already funnel through the #502 relative-path remap, so
changing that remap to emit _file_node_id (one parent dir, no extension)
converts the node and every referencing edge together - Python, TS, Lua,
C and bash import edges all stay connected. symbol_resolution pre-computes
the canonical form directly (bypassing the remap) so it is synced too.

Per-site conversion (as attempted in #1038/#1065) orphans edges because
it moves the node without the edge targets; the chokepoint approach
avoids that entirely.

Backward compat for existing graphs: graphify extract --force, as the
skill.md spec already documents.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 12:23:56 +01:00
SafiandClaude Sonnet 4.6 8db19d6c85 sort file list lexicographically in detect() for deterministic graph output
os.walk order is non-deterministic across runs (filesystem b-tree order
shifts with cache/mount state), causing first-writer-wins decisions in
cross-file resolution to produce different node IDs each run; sorting
all_files and per-FileType lists stabilises graph.json without changing
any parent-child or connectivity semantics (closes #1090)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 10:20:18 +01:00
SafiandClaude Sonnet 4.6 0cf596aa8a fix test_no_incremental_without_manifest false positive
pytest derives tmp_path from the test name, so the path contained
"incremental" and the bare-word assertion always failed; check for
the actual incremental-mode phrases instead

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 00:10:19 +01:00
SafiandClaude Sonnet 4.6 31a608f73e fix Windows Unicode crash on non-UTF-8 consoles (issue #992)
reconfigure stdout/stderr to UTF-8 at startup; replace → and — in all
print statements with ASCII equivalents as belt-and-suspenders fallback

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 00:06:35 +01:00
SafiandClaude Sonnet 4.6 55d7dadb63 bump to 0.8.26
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 21:40:52 +01:00
Manoj Mishra c066511bf2 feat: detect circular import dependencies at file level (#961)
* feat: detect circular import dependencies at file level

- Add find_import_cycles() to analyze.py
- Collapses symbol nodes to parent files, builds directed file graph
- Uses nx.simple_cycles() bounded by max_cycle_length (default 5)
- Deduplicates rotations, returns shortest cycles first
- Considers both imports_from and re_exports edges

Tested on a 976-file Next.js codebase: found 4 cycles including
a known utils↔barrel circular dependency and a 4-file API cycle.

* fix: resolve import-cycle merge blockers

- use source_file-only endpoint resolution (no label fallback)
- support Graph/DiGraph orientation via edge source_file
- return structured cycle records and include self-loops
- integrate Import Cycles section into GRAPH_REPORT.md
- expand cycle tests for real-schema IDs, undirected input,
  missing source_file nodes, and non-import relations
2026-05-30 21:37:47 +01:00
SafiandClaude Sonnet 4.6 cca13aa8fd fix anchored gitignore pattern leaking basename match into subtree (closes #1087)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 18:16:01 +01:00
SafiandClaude Sonnet 4.6 a9d6be6537 add custom LLM provider registry via providers.json (closes #1084)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 13:25:02 +01:00
SafiandClaude Sonnet 4.6 006e1594eb fix extract_files_direct backend default: auto-detect instead of kimi (closes #1086)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 13:17:13 +01:00
SafiandClaude Sonnet 4.6 d4e1d4b553 fix pnpm-workspace.yaml packages:'.' crash on Python 3.10 (closes #1083)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 13:13:23 +01:00
Alexis Valentinoandalexisvalentino 5056c72e67 docs: add Filipino (fil-PH) README translation
Co-authored-by: alexisvalentino <alexisvalentino@users.noreply.github.com>
2026-05-29 23:43:56 +01:00
SafiandClaude Sonnet 4.6 a7a732290c release 0.8.25: JS/TS phantom nodes, Lua imports, Windows cli, hook lock, antigravity path
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 16:59:17 +01:00
SafiandClaude Sonnet 4.6 998594091b fix antigravity global install path to ~/.gemini/config/skills/ and uninstall symmetry (#1079)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 15:15:26 +01:00
SafiandClaude Sonnet 4.6 9db86942bd warn against pip install on Mac/Windows due to env path mismatch (#1074)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 14:13:05 +01:00
SafiandClaude Sonnet 4.6 282afaac7d add missing test coverage for #1077 scope guard and markdown fence fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 14:07:03 +01:00
SafiandClaude Sonnet 4.6 925eb81ec1 fix JS/TS phantom god-nodes from arrow-fn locals and drop markdown code-block orphan nodes (#1077)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 13:46:30 +01:00
SafiandClaude Sonnet 4.6 5642c1b533 fix Lua require() import edges lost due to wrong target ID resolution (#1075)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 13:36:04 +01:00
SafiandClaude Sonnet 4.6 f0badd9899 fix Windows claude-cli WinError 2 and post-commit hook silent drop on rapid commits
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 11:41:42 +01:00
SafiandClaude Sonnet 4.6 fd1aca480f release 0.8.24: cross-language semantics, claude-cli fix, edge direction fix, security audit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 02:28:52 +01:00
Safi 8a308519f9 Merge pull request #1063 from christophepub/fix/claude-cli-hollow-responses-v2
Fix hollow-response loop in claude-cli backend (re-targeted to v8, clean diff, with tests)
2026-05-29 01:54:37 +01:00
Safi aae027f7e6 Merge pull request #1071 from TheFedaikin/v8
Fix CI and ddd semantic contexts for ObjC, Julia, C, C++, Scala, Fortran, and PowerShell
2026-05-29 01:54:30 +01:00
Danil Tarasov 0080fbd13c feat: add objc, julia, c, c++, scala, fortran, powershell semantic contexts 2026-05-29 00:05:28 +03:00
SafiandClaude Sonnet 4.6 66acfd81aa fix calls edge direction flipping on bidirectional pairs in undirected build (#1061)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 17:40:04 +01:00
SafiandClaude Sonnet 4.6 c2de9fa72f add uv-aware install detection to all skill files
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 17:07:24 +01:00
SafiandClaude Sonnet 4.6 8e179736ce fix .graphify_python path missing graphify-out/ prefix in skill files
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 16:55:07 +01:00
christophepub 379d35e088 fix(claude-cli): eliminate hollow-response loop from system-prompt conflict
Three compounding bugs caused ~30-50% of semantic chunks to come back
as 'hollow responses' on the claude-cli backend, triggering adaptive
bisection that doubled or tripled the number of subprocess calls.

Root causes
-----------
1. _parse_llm_json only stripped markdown fences when raw.startswith('```').
   Claude frequently prepends a short preamble before the fence
   ('Here are the extracted entities:\n\n```json\n{...}```'), making
   the check fail. json.loads then drops the chunk. Each bisected half
   may exhibit the same failure, so cost compounds.

2. _call_claude_cli used --append-system-prompt, which layers graphify's
   extraction prompt on top of Claude Code's default interactive-agent
   prompt ('use markdown formatting', 'output text to communicate with
   the user'). The conflicting instructions explain ~50% of the
   preambles and fences from (1). Switching to --system-prompt (replace)
   eliminates the conflict at the source.

3. claude-cli defaults to Opus, which is overkill for the structured
   JSON extraction graphify performs. New GRAPHIFY_CLAUDE_CLI_MODEL env
   var lets users opt into haiku / sonnet for big builds. Default
   behaviour unchanged when the env var is unset.

Fix
---
- Robust _parse_llm_json: strips fences regardless of position, with a
  balanced-brace fallback that scans for the first complete JSON object
  in the response. Handles preambles, trailing prose, prose-wrapped
  JSON without fences. Diagnostic log on terminal failure includes the
  first 200 chars of the response.
- _call_claude_cli switches to --system-prompt.
- _call_claude_cli respects GRAPHIFY_CLAUDE_CLI_MODEL when set.

Tests (tests/test_llm_parser.py)
--------------------------------
- The four PR-body failure modes: preamble+fence, prose+JSON, raw JSON,
  total refusal.
- Bonus: uppercase fence tag, unclosed fence, empty response.
- argv shape: --system-prompt present, --append-system-prompt absent.
- argv shape: --model added iff GRAPHIFY_CLAUDE_CLI_MODEL is set.

19/19 tests pass (9 pre-existing in test_claude_cli_backend.py +
10 new). Verified end-to-end on a 800-file repo: 0 hollow responses
after, vs ~30-50% before; output tokens -93%; wall time 44 min -> 4 min.
2026-05-28 17:44:35 +02:00
SafiandClaude Sonnet 4.6 7c12499783 chore: install all extras in CI to catch test gaps
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 14:53:45 +01:00
SafiandClaude Sonnet 4.6 ffbe425c2f release 0.8.23
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 14:52:01 +01:00
TheFedaikin 32aa053e6c feat: semantic type-reference edges for Swift, Kotlin, PHP, Rust, and Go (#1015) 2026-05-28 14:46:03 +01:00
SafiandClaude Sonnet 4.6 cddf47d3a0 chore: commit uv.lock (regenerated for 0.8.22 with tree-sitter-dm)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 14:38:59 +01:00
Brian K 244a266c06 chore: switch CI to uv, remove uv.lock from gitignore (#885)
* chore: declare pytest as a uv dev dependency

The contributing guide currently tells contributors `pip install pytest`
as a separate step, and CI does the same. Move pytest into PEP 735
`[dependency-groups]` so it's declared in pyproject.toml and `uv sync`
installs it by default (no `--with` workaround, no separate install
line). Update CI to use astral-sh/setup-uv + `uv sync` + `uv run pytest`,
and refresh the Contributing section of the README to match.

`[dependency-groups]` is the right home (vs `[project.optional-dependencies]`)
because pytest is dev-only and shouldn't appear in the published wheel's
optional features list alongside things like `pdf` or `mcp`.

* remove uv.lock from gitignore
2026-05-28 14:38:31 +01:00
SafiandClaude Sonnet 4.6 a1706ff7fd docs: add --mode deep to graphify extract CLI reference
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 00:30:36 +01:00
SafiandClaude Sonnet 4.6 43bf3c2371 release 0.8.22
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 00:26:31 +01:00
SafiandClaude Sonnet 4.6 cfc945a507 fix: cap zlib decompression in extract_dmi, add size guard in extract_dmm
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 00:08:55 +01:00
SafiandClaude Sonnet 4.6 dacbdb539a feat: BYOND DreamMaker support, --mode deep flag, changelog fixes (#884, #1030)
- Feat: extract_dm (tree-sitter-dm), extract_dmi (PNG icon states),
  extract_dmm (tile dict uses edges), extract_dmf (window/elem hierarchy)
  for .dm .dme .dmi .dmm .dmf; 26 tests, fixtures, pyproject.toml dep
- Feat: graphify extract --mode deep flag; deep_mode threaded through all
  four LLM backends via extract_corpus_parallel
- Fix: CHANGELOG 0.8.21 entries for #1050, #1046, #1047 that were missing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 23:55:12 +01:00
Aadi c09fbef401 fix: remap hyperedges in community-aggregated meta-graph view (#1006)
When a graph exceeds the viz node limit, to_html() builds a
community-aggregated meta-graph and recursively calls itself.
The recursive call never carried hyperedges onto the meta-graph,
so graph.html always emitted const hyperedges = [] even when
graph.json contained plenty.

This fix remaps hyperedge node references from semantic node IDs
to community IDs before the recursive call, so hyperedge regions
render correctly in the aggregated view. Hyperedges that collapse
to fewer than 2 distinct communities are dropped (they wouldn't
render as a polygon anyway).

Fixes #1005
2026-05-27 22:39:01 +01:00
SafiandClaude Sonnet 4.6 9f73400cbc fix: memory-dir gitignore leak, Pass 2 dedup cross-file identical merge, decorated method node ID mismatch (#1047, #1046, #1050)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 22:30:08 +01:00
Safi 740382af51 docs: add Amp platform, .svh extension, fix opencode uninstall in README 2026-05-27 13:04:50 +01:00
SafiandClaude Sonnet 4.6 80301a06bf fix: OpenCode project path, hook loop guard, deterministic output, Amp platform, punctuation search, builtin god-node filter, .svh Verilog (#1040, #1018, #1037, #948, #994, #916, #1042)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 12:39:22 +01:00
Aleksandr TarutinandClaude Opus 4.7 a54a542b6c fix: make graph output deterministic (stop graphify-out churn) (#1010)
graphify-out regenerates differently on every `graphify update` even
when no source changed, so the committed graph is perpetually dirty and
the post-commit/post-checkout hooks fight every commit. Two independent
nondeterminism sources, each fixed here:

1. Edge direction flips. build.py builds an undirected graph and stores
   direction in _src/_tgt; collapsing two edges onto the same node pair
   is last-write-wins, and unstable edge iteration order flips them
   run-to-run. Fixed by sorting edges by (source, target, relation)
   before the add loop.

2. Clustering churn. The networkx Louvain fallback iterates string-keyed
   sets whose order is randomized per-process by PYTHONHASHSEED, so
   community assignments differ run-to-run even with seed=42. Fixed by
   exporting PYTHONHASHSEED=0 in the generated post-commit and
   post-checkout hook scripts.

With both fixes, `graphify update` is idempotent: rebuilding an
already-converged graphify-out reproduces graph.json and GRAPH_REPORT.md
byte-for-byte.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 12:20:31 +01:00
SafiandClaude Sonnet 4.6 d1d5751fa4 fix(watch): evict stale nodes in full re-extraction path when changed_paths is None (#1007)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 11:21:55 +01:00
Safi b07f0eb6a7 bump version to 0.8.20 2026-05-26 20:34:22 +01:00
SafiandClaude Sonnet 4.6 ad3f3b2d9e harden XML parsing against billion-laughs DoS in extract_csproj and extract_lpk
stdlib ET does not cap entity expansion — a crafted .csproj or .lpk with nested
internal entities can exhaust memory. Pre-screen input bytes for <!DOCTYPE and
<!ENTITY before parsing (legitimate MSBuild/Lazarus files never contain these).
Also adds the missing 2 MiB size cap to extract_lpk (csproj already had one).
No new dependencies required.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 20:32:14 +01:00
Safi e5313e73b2 add MCP config files to README file types table 2026-05-26 20:24:14 +01:00
Alexey Z baaab5f2a9 fix(extract_dart): use _file_stem instead of str(path) for child node IDs to prevent machine-specific absolute paths in graph.json (#999) 2026-05-26 20:21:27 +01:00
2c01a89b28 feat: MCP config extractor (.mcp.json, claude_desktop_config.json, mcp.json)
Adds graphify/mcp_ingest.py — extracts MCP server configurations into the
knowledge graph. Captures server nodes, NuGet/npm/pip package refs, commands,
env var requirements, and inter-server edges. Dispatched by filename before
the suffix lookup so generic .json extraction is unaffected. Env values are
discarded to prevent secret leakage. File size capped at 1 MiB. 29 tests.

Fixes: server_count budget now checked after validity guard so invalid entries
don't consume capacity; removed misleading uv run docstring example.

Co-Authored-By: adityachaudhary99 <adityachaudhary99@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 20:16:41 +01:00
Leon GyeongMan BaekandClaude Opus 4.7 9abaa77c62 fix(cli): apply remap_communities_to_previous in cluster-only path (#1028)
cluster-only re-runs Leiden clustering and then re-applies the existing
.graphify_labels.json by raw cid index, which causes labels to attach to
clusters whose members are unrelated to the label's original meaning
whenever the graph has changed between labeling and re-clustering.

Mirror the safety net already present in watch.py:_rebuild_code added in
#822 for the watch/update paths.

Adds a regression test that fails without the fix (label cids become
orphaned from graph.json community attributes after re-clustering).

Refs: #1027

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 20:12:02 +01:00
SafiandClaude Sonnet 4.6 3f8efaebc2 fix graphify update ghost nodes: as_posix() and relativize existing graph before eviction
Three issues in _rebuild_code (watch.py):
1. _relativize_source_files was called on result after eviction list was built,
   so existing nodes with absolute source_file were never normalized before comparison
2. deleted_paths and evict_sources used str() (backslashes on Windows) while
   graph.json stores forward-slash paths via _norm_source_file
3. _relativize_source_files itself used str() instead of as_posix()

Also fix extract.py source_file relativization to use as_posix(). Closes #1007.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 20:05:31 +01:00
SafiandClaude Sonnet 4.6 eef623a54a improve #1007 fix: use _norm_source_file with resolve() for symlink safety
Replace inlined path normalisation with _norm_source_file (the same function
that builds node source_file keys) so prune_set and node attrs are normalised
identically. resolve() on root handles symlinked scan roots. Keep both raw and
normalised forms in prune_set so nodes with absolute source_file also match.
Add edge pruning and Windows backslash path tests per Opus review.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 14:59:13 +01:00
SafiandClaude Sonnet 4.6 a26f24ef7b fix stale nodes persisting after file deletion when manifest uses absolute paths
prune_set in build_merge now includes relative-path variants of each deleted file
so manifest absolute paths (e.g. /home/user/corpus/module_b/utils.py) match graph
node source_file values (e.g. module_b/utils.py) regardless of OS or run context.
Fixes #1007.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 14:53:36 +01:00
Safi d9debdf39a bump version to 0.8.19 2026-05-26 12:52:04 +01:00
Safi 903fa9c141 add chinese extra to README optional extras table 2026-05-26 12:39:16 +01:00
8bcfffdf62 add .NET project file support (.sln, .csproj, .fsproj, .vbproj, .razor, .cshtml)
Adds extract_sln, extract_csproj, and extract_razor extractors. Captures NuGet
package refs, project-to-project dependencies, target frameworks, SDK attribute,
@using/@inject/@inherits/@model directives, Blazor component refs, and @code
methods. Resolves relative project paths to absolute paths so sln/csproj nodes
link correctly when the graph is assembled. Closes #515.

Co-Authored-By: aksrathore <aksrathore@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 12:27:28 +01:00
CandyandOmX c7a05d67a1 Clarify Chinese query segmentation scope (#1026)
Keep Graphify query segmentation focused on Chinese terms: rename the CJK helpers and extra to Chinese scope, cache the optional jieba import at module load, and keep a bigram fallback when jieba is unavailable.

Constraint: Reviewer asked either to broaden Hiragana/Katakana/Hangul support or rename CJK helpers; user chose Chinese-only because Japanese segmentation accuracy is uncertain.

Rejected: Broaden to Japanese and Korean segmentation | jieba is Chinese-oriented and the user explicitly limited scope to Chinese.

Confidence: high

Scope-risk: narrow

Directive: Do not label this path as CJK unless Hiragana/Katakana/Hangul segmentation is intentionally supported and tested.

Tested: uv run --with pytest pytest tests/test_serve.py tests/test_query_cli.py tests/test_benchmark.py

Tested: uv run --with pytest --with jieba pytest tests/test_serve.py -k "chinese or non_chinese"

Tested: graphify update .

Not-tested: Full test suite.

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-05-26 12:24:04 +01:00
Safi 68863a72fe Remove unused _DEVIN_RULES_MARKER constant 2026-05-26 09:19:09 +01:00
065a621fa6 feat: add Devin CLI support (graphify devin install/uninstall) (#1020)
* feat: add Devin CLI support

- Add 'devin' to _PLATFORM_CONFIG with skill-devin.md
- Override _platform_skill_destination for devin:
  user scope -> ~/.config/devin/skills/graphify/SKILL.md
  project scope -> .devin/skills/graphify/SKILL.md
- Add _DEVIN_RULES + _devin_rules_install/_uninstall:
  writes .windsurf/rules/graphify.md (always-on context)
  Devin reads .windsurf/rules/*.md the same way Windsurf IDE does
- Add graphify devin install [--project] / uninstall subcommand
- Create graphify/skill-devin.md with Devin YAML frontmatter
  (name, argument-hint, model, allowed-tools, triggers)
- Add 21 tests in tests/test_devin.py covering user/project scope
- Register _DEVIN_RULES in test_install_strings.py policy checks
- Update README.md and pyproject.toml to list Devin CLI

Generated with [Devin](https://cli.devin.ai/docs)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* expand skill-devin.md to full feature parity with skill-pi.md

Rebuilds skill-devin.md from ~267 lines to 1176 lines, matching the
depth of other mature platform skills (pi, droid, codex).

Added:
- Parallel Part A + B dispatch guidance (AST alongside semantic subagents)
- Full subagent extraction prompt with rationale, semantic similarity,
  hyperedge, and confidence_score rules
- Extraction cache check (Step B0) and cache save/load flow
- --mode deep, --svg, --graphml, --neo4j/--neo4j-push, --mcp, --watch
- /graphify path, /graphify explain, /graphify add, /graphify query
- BFS vs DFS traversal with --dfs and --budget flags
- Token reduction benchmark step
- --update (incremental) and --cluster-only pipelines with graph diff
- Video/audio transcription (Step 2.5) with Whisper domain-hint strategy
- git commit hook section
- Always-on Devin rules section referencing `graphify devin install`

Updated test_devin.py: corrected python_c_syntax assertion to match
the interpreter-detection pattern used across all mature skills.

Generated with [Devin](https://cli.devin.ai/docs)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: vishal-gandhi <ivishalgandhi@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-05-26 09:17:18 +01:00
msotnikov 336652779b Fix: support array form of tsconfig extends (TypeScript 5.0) (#1017)
TS 5.0 allows `"extends": ["./a", "./b"]`. _read_tsconfig_aliases called
`extends.startswith("@")` directly, so an array raised
`AttributeError: 'list' object has no attribute 'startswith'`. _safe_extract
caught it and skipped the WHOLE file — and since alias resolution fires on any
path-aliased import, every TS file using `@/`-style imports in a repo with
array-extends tsconfig was dropped, yielding an empty graph.

Normalize `extends` to a list (str -> [str], list kept, else []), process
entries in order (later overrides earlier, current config's paths override all
parents per TS semantics), and skip scoped npm configs (`@...`) per entry as
before.

Adds regression test test_tsconfig_array_extends_alias_resolves_existing_ts_file.
2026-05-26 09:17:14 +01:00
SafiandClaude Sonnet 4.6 4e80d8621f Fix wiki TypeError on null source_file and skip nested worktrees/ dirs (#1016, #1023)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 09:06:43 +01:00
SafiandClaude Sonnet 4.6 3efae3827f Rate-limit backup_if_protected to one folder per day via content hash
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 09:14:20 +01:00
Safi 98100f3b35 Bump version to 0.8.18 2026-05-24 20:41:31 +01:00
SafiandClaude Sonnet 4.6 a4a615da97 Fix Ukrainian README typo, Unicode vocab regex, add migration note for Java extends->inherits
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 20:40:49 +01:00
eugene-krivosheyev 238702b697 Constrained query expansion (#998)
Add constrained query expansion step to /graphify query skill

## Problem

`graphify query` matches via case-folded substring + IDF — no stemming, no synonyms, no cross-language match. When the user's question uses different vocabulary than the graph labels (Slavic → English, "handlers" → "handler", "обработчик" → "handler"), the literal matcher returns 0
hits and the LLM consumer either gets empty subgraph or improvises an ungrounded keyword list from training memory (e.g. expanding "auth" to `{passport, sso, saml, oauth, jwt, scim, …}` regardless of whether those tokens exist in the corpus).

## Fix

Adds a `Step 0 — Constrained query expansion` block to the skill's `/graphify query` section. The LLM consumer extracts vocabulary from graph labels (CamelCase/snake_case split, length-filtered) and is instructed to pick **only** tokens present in that vocabulary, explicitly forbidden from inventing terms.

Effects:
- Bounded improvisation — fantom tokens (terms not in corpus) cannot be expanded, even when LLM "knows" they're related to the intent.
- Honest negative signal — if vocab is poor on a query's topic,  expansion returns [] and the LLM tells the user, instead of  fabricating a search.
- Auditability — selected tokens are printed to the user, and saved into `save-result` for the next --update to graph as Q&A nodes.

## Scope

Patches the canonical `graphify/skill.md`. The 11 host-variant skills (skill-codex.md, skill-aider.md, …) follow the same query-section contract but inline Python rather than calling `graphify query` CLI; those need a parallel patch with the inline form. Happy to follow up in a separate PR after review on the canonical patch.

## Test

On a graph built from the graphify repo itself (1284 nodes, 1454 vocab tokens), an unconstrained expansion of "укрупненная архитектура аутентификации" yields {auth, oauth, jwt, saml, sso, ldap, scim, mfa, 2fa, pin, passport, session, login, token} — of which 11/15 are absent
from the corpus. Constrained expansion against the actual vocab yields {credential, security, token, signature, user, architecture, component, module, overview} — 9 tokens, 0 fantom. Same retrieval, dramatically higher precision.
2026-05-24 20:38:13 +01:00
TheFedaikin ab4e5424ca feat: add cross-language semantic contexts for Python, JS/TS, C#, and Java (#996) 2026-05-24 20:38:10 +01:00
Ivan Dzhulynskyi 32effb10a9 docs: update Ukrainian README translation to v8 (#995) 2026-05-24 20:38:08 +01:00
mohamadkattan12 d778e2c36b fix(cli): reconstruct communities from per-node attribute when sidecar missing (#1001)
`graphify export html|obsidian|wiki|svg|graphml|neo4j` reads `communities`
exclusively from `.graphify_analysis.json` (set to `{}` if missing). The
post-commit / watch rebuild path doesn't regenerate that sidecar — only
graph.json + GRAPH_REPORT.md. Several skill workflows also delete temp
files at the end of `graphify extract`. In both cases the per-node
`community` attribute (`to_json` writes it on every node) is intact, but
the CLI ignores it.

Observed failure: `graphify export html` on a graph that exceeds the
viz node limit prints

    Graph has 64703 nodes (above 5000 limit). Building aggregated community view...
    Single community - aggregated view not useful. Skipping graph.html.

even though the same graph.json has 2,026 distinct `community` values
on its nodes — `to_html` just received an empty `communities` dict and
the aggregator collapsed to a single meta-node.

Fix: when the analysis sidecar is absent (or its `communities` field is
empty), reconstruct the `cid -> [node_ids]` mapping from the per-node
attribute in graph.json. The sidecar remains the canonical source of
truth when present; the reconstruction is a strict fallback. Every
downstream subcommand (`html`, `obsidian`, `wiki`, `svg`, `graphml`,
`neo4j`) sees the same shape it always did, just populated from the
graph itself instead of an externally-cached sidecar.

Tests added (tests/test_cli_export.py):
- `test_export_html_falls_back_to_node_community_attribute` —
  delete the sidecar, run export html, confirm `graph.html` exists
  and the "Single community" bail-out path does NOT fire.
- `test_export_html_fallback_recovers_multiple_communities` —
  stronger guarantee that the reconstructed community count equals
  what the sidecar would have provided (no silent data loss).
- `test_export_html_no_community_data_at_all_still_succeeds` —
  hand-build a graph.json with no per-node `community` attribute
  (older `to_json` versions, manually-constructed graphs); the
  command must still exit cleanly rather than crash.

All 26 tests in test_cli_export.py pass; ruff clean on both files.
2026-05-24 20:35:21 +01:00
mohamadkattan12 6fba4e4594 fix(watch): bypass shrink-guard when caller declared explicit deletions (#1000)
The post-commit hook passes `git diff --name-only HEAD~1 HEAD` as
changed_paths to `_rebuild_code`. That list includes deletions, and
`_rebuild_code` correctly identifies them (lines 352-367 in watch.py)
and evicts the stale nodes from the preserved set. The rebuilt graph
is intentionally smaller.

`_check_shrink` then refuses to overwrite the existing graph.json
because it only sees the node-count delta, not the cause. The guard
fires with "Refusing to overwrite — you may be missing chunk files
from a previous session. Pass --force to override."

Result: every commit that deletes a tracked file silently leaves stale
nodes in graph.json. The user must either pass --force (which also
disables the guard for legitimate failure modes) or manually re-run
`graphify update . --force` after delete-heavy commits.

Fix: thread a `had_explicit_deletions` flag from `_rebuild_code` into
`_check_shrink`. When the caller has declared the deletions, the
smaller graph is the expected outcome and the guard is skipped. The
guard remains intact for SILENT shrinkage — its actual purpose —
from failed semantic chunks or corrupted runs.

The fix is opt-in by design: callers that don't pass `changed_paths`
(e.g. the post-checkout full rebuild path) keep the old conservative
behavior. Only paths that explicitly track deletions get the bypass.

Tests added (tests/test_watch.py):
- `test_check_shrink_blocks_silent_shrink` — pre-existing behavior intact
- `test_check_shrink_allows_force_override` — pre-existing behavior intact
- `test_check_shrink_allows_explicit_deletions` — new: deletion bypass
- `test_check_shrink_allows_no_existing_data` — first-run case
- `test_check_shrink_allows_growth` — sanity
- `test_check_shrink_unlinks_tmp_on_refuse` — cleanup on refusal
- `test_check_shrink_keeps_tmp_when_deletions_declared` — no spurious unlink
- `test_rebuild_code_prunes_deleted_file_nodes` — end-to-end probe of the
  exact scenario the post-commit hook triggers (git init, build, delete
  one file, re-run with the deleted path in changed_paths, verify the
  graph shrinks and the surviving file's nodes are preserved)

All 8 new tests pass; full test_watch.py + test_build.py + test_export.py
(74 tests) pass with no regressions.
2026-05-24 20:35:19 +01:00
Safi 73c3c33ac7 Bump version to 0.8.17 2026-05-23 23:36:56 +01:00
SafiandClaude Sonnet 4.6 4dce16f475 Fix case-sensitive call resolution and cross-language phantom calls (#993, #991)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 23:35:25 +01:00
SafiandClaude Sonnet 4.6 71b4e57b67 fix Husky 9 hook path, skill.md INPUT_PATH literal, per-worker exception isolation
- hooks.py: add _user_hooks_dir() to target .husky/ instead of .husky/_ on Husky 9 repos (#987)
- skill.md: replace unsubstituted 'INPUT_PATH' literal with '.' in generate() calls (#986)
- extract.py: wrap future.result() per-future so a single worker failure prints a warning instead of falling back to full sequential re-extraction (#943)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 23:17:40 +01:00
SafiandClaude Sonnet 4.6 461e346f3a fix Windows cp1252 crash, str.parent crash, mcp error message, god_nodes relative import
- Replace non-ASCII → with -> in __main__.py print statements (#992)
- Coerce paths to Path objects at extract() entry to fix str.parent crash (#988)
- Fix serve.py ImportError to recommend graphifyy[mcp] extra (#967)
- Change relative import in _tool_god_nodes to absolute to fix script invocation (#966)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 23:14:01 +01:00
SafiandClaude Sonnet 4.6 990ac706d8 bump version to 0.8.16
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 18:58:31 +01:00
balloon72andhanmo1 b3474924c2 feat(install): add project-scoped skill installs (#931)
* feat(install): add project-scoped skill installs

* fix(install): cover project-scoped antigravity install

* test(install): cover project-scoped platform subcommands

---------

Co-authored-by: hanmo1 <hanmo1@lenovo.com>
2026-05-22 14:38:35 +01:00
Jon Attree 3238b32677 Exit non-zero when all semantic-extraction chunks fail (#889)
If `graphify extract --backend claude` runs without the `anthropic`
package installed (pip install graphifyy doesn't pull it in), every
semantic chunk fails inside extract_corpus_parallel. The per-chunk
errors print to stderr but the function returns the empty merged
accumulator anyway, so extract proceeds to write an AST-only graph.json
and exit 0. CI that checks exit status sees success even though the
requested semantic pass produced no nodes.

Track per-chunk success via the existing on_chunk_done callback, which
only fires after a chunk succeeds. If fresh extraction was requested
(uncached_paths non-empty) and zero chunks completed, abort before the
merge/cluster/write phase with exit 1 and a message naming the backend.

The same shape covers other backends with optional SDK deps (openai,
google-generativeai). Cached-only runs are unaffected: uncached_paths
is empty and the guard does not fire.

Tests in tests/test_extract_cli.py simulate the all-failed and
one-succeeded paths by patching extract_corpus_parallel directly.
2026-05-22 14:38:32 +01:00
52d75bd988 fix: add .ets (ArkTS) extension to CODE_EXTENSIONS (#926)
ArkTS (.ets) is the primary language for HarmonyOS/OpenHarmony
application development, used by projects like SceneBoard. The
tree-sitter TypeScript parser already handles .ets files for AST
extraction — the detect module just wasn't recognizing them.

Without this, `detect()` silently skips all .ets source files,
missing ~90% of code in OpenHarmony codebases.

Co-authored-by: Autumn <autumn@AutumndeMacBook-Pro.local>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 14:38:15 +01:00
SherbaevandJavokhir Sherbaev 38cebd321f docs: add Uzbek (uz-UZ) README translation (#982)
Adds docs/translations/README.uz-UZ.md and inserts an entry for
🇺🇿 Oʻzbekcha into the language navigation bar of README.md and all
27 existing translations.

Co-authored-by: Javokhir Sherbaev <javokhir.sherbaev@noveogroup.com>
2026-05-22 14:38:07 +01:00
szgnewGh 86109e9f27 fix: CJK/Unicode labels silently skipped in _norm/_norm_label dedup (follow-up to #811) (#937) 2026-05-22 14:26:27 +01:00
SafiandClaude Sonnet 4.6 6efd06c54d add YC S26 badge to README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 14:17:02 +01:00
SafiandClaude Sonnet 4.6 ff14ad5245 bump version to 0.8.15
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 14:04:54 +01:00
deXterbed 1494874e25 feat: track JS/TS barrel re-exports as explicit graph edges
- Add 'export_statement' to import_types for JS/TS/TSX configs
- Extend _import_js to detect 'export { X } from ./mod' re-exports
- Emit 're_exports' edges linking barrel files to source symbols
- Preserve walk-through for 'export function/const' declarations
- Add 're_exports' to clean_edges allowlist for cross-file edges

Tested on a 976-file Next.js codebase: detects 162 re_exports edges
and 5760 symbol-level imports (previously 0 for both).
2026-05-22 13:28:35 +01:00
Danil Tarasov e44e6e986c feat: add v8 affected and import-resolution support 2026-05-22 13:24:54 +01:00
hypnwtykandvampyre b6127aa5a7 feat(multigraph): add runtime compatibility probe (#956)
* feat(bash): harden extractor — literal filtering, entrypoint nodes, AST-ancestry-aware command detection

Builds on tree-sitter-bash extractor from #866. Two correctness/security
improvements to bash extraction in graphify/extract.py:

1. Reject command/process substitutions at extraction time. Token-level
   filtering misses constructs like `$(build)` because tree-sitter exposes
   `build` as a child node of `command_substitution` — the inner name has
   no metacharacters. Added `is_inside_expansion(node)` that walks
   `node.parent` until it finds `command_substitution` or
   `process_substitution`. Used as a gate in both `walk` and `walk_calls`.
   Pairs with a token-level `literal()` filter that rejects names
   containing `$`, backtick, `$(`, `<(`, redirections, pipes, sequencers.

2. Entrypoint node. Every .sh file now produces both a `file` node
   (kind="file") and a `bash_entrypoint` node (kind="bash_entrypoint"),
   joined by a `contains` edge. A separate top-level `walk_calls(root,
   entry_nid, ...)` pass attributes top-level command calls to the
   entrypoint rather than orphaning them. Matches the entrypoint pattern
   other-language extractors use. Node metadata gains language+kind.

Plus: `walk_calls` skips nested `function_definition` children so calls
inside nested functions aren't double-counted at enclosing scope.

Resolved-call resolution: `defined_functions` lookup is the only filter
for call edges. User-defined functions named like external commands
(install, find, git, ...) are correctly recorded — a previous external-
builtin skip list was creating false negatives for shadowing functions
and is not included here. Skip list belongs with raw/unresolved call
recording (not in this PR).

Devtools (bundled): pyproject.toml gains [dependency-groups] dev (ruff,
pyright, pre-commit, hypothesis, pip-audit) plus minimal [tool.ruff],
[tool.ruff.lint], [tool.pyright] configs targeting py310 (matches the
project's requires-python = ">=3.10").

Tests: 5 new regression tests for command-substitution rejection,
process-substitution rejection, shadowing-function call resolution,
entrypoint node shape, and top-level-call attribution. 826/826 pass
(was 821); 15/15 bash-relevant tests pass (was 10).

* feat(detect): parse macOS/BSD and GNU env(1) shebang option forms

Upstream's _shebang_file_type parses shebangs via line[2:].split() and only
handles `#!/usr/bin/env <interp>`. Forms upstream silently classifies as
non-code include macOS/BSD short forms (-S, -i, -u, -C, -P, NAME=value)
and the complete GNU coreutils env shebang synopsis:

    #!/usr/bin/env -[v]S[option]... [name=value]... command [args]...

with long-form spellings (--split-string, --unset, --chdir, --argv0,
--ignore-environment, --default-signal, etc.), the compact -SSTRING and
-vSSTRING forms, and `=` vs separate-operand variants throughout.

Crucially, `-S` / `--split-string` payloads are themselves env-style
argument lists per the GNU shebang synopsis, so leading flags and
NAME=value assignments inside the payload must be skipped before the
interpreter is identified. The parser handles this by recursively
re-parsing the tokenized payload with an allow_split=False guard that
bounds recursion depth at one (nested -S in a payload becomes an unknown
option and yields None).

Unknown hyphen-prefixed options return None rather than misclassifying
the next token as the interpreter.

_shebang_file_type becomes a 4-line wrapper. Read buffer raised 128 -> 256
to accommodate longer env -S strings.

Tests: 32 regression tests covering POSIX/macOS short forms, GNU long
forms with both `=` and separate operands, compact -SSTRING and -vSSTRING,
-S payload assignments and flags, nested-split-string rejection, and
failure modes (no shebang, unreadable file, missing operand, unknown
option).

* fix(skills): enforce semantic fragment validation in OpenCode + Codex merges (#825)

Closes #825. Adds graphify.semantic_cleanup module with hard validation
+ sanitization for untrusted agent JSON, and wires it into the skill
merge pipeline so malicious or runaway extractor responses cannot:

- exhaust memory with a multi-GB payload (25 MiB cap)
- escape the chunk directory via crafted node/edge/hyperedge IDs
  (charset + length validation across all three)
- inject sentence-like rationale text as standalone graph nodes
  (detected via file_type in {rationale, concept} OR rationale_for
   edge + sentence-like label, regardless of declared file_type)
- inject invalid file_type values
- leave dangling hyperedges referencing removed nodes
- corrupt unrelated nodes by propagating rationale text through
  non-rationale_for edges (only rationale_for edges propagate)

Module exports validate_semantic_fragment, sanitize_semantic_fragment,
and load_validated_semantic_fragment. Wired into skill-opencode.md and
skill-codex.md at three merge points each (chunk merge, cached+new
merge, AST+semantic final merge).

Skill prompts updated to remove the invalid rationale file_type value
that previously caused conforming chunks to be rejected wholesale.
Valid set is now {code, document, paper, image}.

Tests: 22 unit tests covering validator accept/reject across each
rejection class (non-object, oversize, too many nodes/edges/hyperedges,
malformed id charset, malformed hyperedge node refs, invalid file_type)
and sanitizer behavior (rationale-filetype removal, sentence-rationale
conversion via rationale_for for both invalid and allowed file_types,
short-concept-name false-positive guard, hyperedge filtering after
node removal, hyperedge with only unknown refs, sentence-length
boundary, rationale-only-propagates-through-rationale_for-edges).

880/880 tests pass.

* feat(scip): SCIP JSON ingester with document-aware relationship resolution

Adds graphify.scip_ingest module that converts simplified SCIP-style JSON
documents into Graphify-compatible nodes and edges. Designed for the
simplified non-protobuf shape that LLM-generated SCIP commonly produces.

Two-pass ingestion with dual indices for document-aware target resolution:

  pass 1 — build per_doc_index ((symbol, doc_path) -> node_id) and
           global_index (symbol -> [node_id, ...]) across every valid
           symbol in every valid document. Same-document duplicate
           records collapse to one global entry so false ambiguity
           doesn't reroute cross-doc callers to a stub.
  pass 2 — emit nodes for indexed symbols, then walk relationships.
           Resolution order:
             1. same-doc match (per_doc_index)
             2. unique cross-doc match (global_index[symbol] len == 1)
             3. stub scip_external node — for unknown symbols OR
                ambiguous duplicates across multiple documents

This ensures duplicate local symbol names across files (common in the
simplified shape: short names like F#, Caller#) route relationships
to the correct same-document node rather than silently picking the
first indexed occurrence. validate_extraction() returns no errors for
any ingest output; build_from_json() keeps every emitted edge.

Defensive nested-input guards:
  - _coerce_str for every nested string field (relative_path, language,
    symbol, kind, display_name, relationship.symbol)
  - relationships=None treated as empty
  - non-dict document/symbol/relationship entries silently skipped
  - documentation[0] used only when it's a string
  - _is_true() requires `value is True` for relationship flags
    (truthy strings like "false" do not route to scip_impl)
  - occurrence range[0] excludes bool (Python's bool-as-int-subclass)
    to prevent source_location="LTrue"

Module is stdlib-only (hashlib, re, typing.Any). Not wired to the CLI
in this phase — importable as `from graphify.scip_ingest import
ingest_scip_json`.

Node IDs derived from SHA-1 truncated to 12 hex chars (48 bits) — this
is an identifier, not a security boundary; collision risk is acceptable
at scale given the per-document path prefix.

Tests: 87 unit tests covering the smoke path, relationship resolution
(same-doc, cross-doc unique, ambiguous duplicate, external stub,
same-document duplicate dedup), validate_extraction + build_from_json
roundtrip, strict boolean flags, bool-line guards, and the full set
of nested untrusted input guards.

1044/1044 tests pass.

* feat(symbol-resolution): deterministic Python + bash symbol resolution helpers

Adds graphify.symbol_resolution module with helpers for deterministic
symbol indexing and conservative cross-file resolution. Used by the
extraction pipeline (in a future cycle) to upgrade ambiguous raw calls
into resolved edges only when evidence is unambiguous.

Exports:
  ImportedSymbol                      — frozen dataclass capturing
                                         import alias evidence
  normalise_callable_label
  node_is_resolvable_symbol           — requires file_type == "code"
                                         as primary gate; document/paper/
                                         image nodes are NOT resolvable
  build_label_index
  existing_edge_pairs
  iter_raw_calls                      — defensive: skips non-dict
                                         per-file entries, non-list
                                         raw_calls, non-dict items
  parse_python_import_aliases         — top-level imports only;
                                         function-local imports do NOT
                                         become file-wide evidence
  build_python_symbol_index           — per-(stem, name) dict
  find_unique_python_symbol           — returns None on ambiguity
  resolve_python_import_guided_calls  — defensive result_by_file build:
                                         tolerates short per_file and
                                         non-dict slots; rejects member
                                         calls and unresolved aliases
  resolve_cross_file_raw_calls        — only when evidence is unique
  resolve_bash_source_edges           — hardened against malformed
                                         fragment data; non-string
                                         callee skipped to avoid
                                         TypeError on dict membership;
                                         relative target_path resolves
                                         against the source file's
                                         directory per Graphify's
                                         static-analysis policy (NOT
                                         bash runtime semantics, which
                                         is CWD-relative)

Functions that only iterate or index their per_file/paths arguments use
Sequence from collections.abc for proper covariance. Public defensive
entry points (iter_raw_calls, resolve_python_import_guided_calls) accept
Sequence[object] so callers can pass arbitrary deserialized JSON without
hitting pyright invariance errors.

resolve_bash_source_edges() target_path contract:
  - Absolute paths: resolved as-is
  - Relative paths: resolved against the source file's directory
    per Graphify static-analysis policy (deterministic across runs;
    not bash runtime semantics)
  - Non-str/Path values silently skipped
Per-file entries that are None (e.g. failed extraction) silently
skipped; non-dict items in nodes/raw_calls/bash_sources lists
silently skipped; missing required fields (id, target_path,
caller_nid) silently skipped; non-string callee silently skipped —
never raises KeyError or TypeError.

Module is stdlib-only (ast, re, dataclasses, pathlib, typing,
collections.abc). Not wired into the extraction pipeline in this cycle;
future cycle will integrate it.

Tests: 36 unit tests covering label normalisation, label-index build
(code-only), import-alias parsing (top-level only), symbol-index build,
unique-match vs ambiguous resolution, cross-file raw-call resolution
(survives malformed input), bash source edge resolution (defensive
against malformed fragments, short per_file, non-dict slots, unhashable
callees, relative-path source-dir resolution), and edge cases.

* feat(security): cap graph.json loaders at 512 MiB before parsing

exhaustion on adversarial or pathological inputs.

- graphify.security: add _MAX_GRAPH_FILE_BYTES + check_graph_file_size_cap
- graphify.serve._load_graph: call cap after existence check
- graphify.__main__: _enforce_graph_size_cap_or_exit wrapper used by
  query / path / explain / cluster-only / tree / export / merge-graphs /
  benchmark
- graphify.build / benchmark / tree_html / callflow_html / prs /
  global_graph / watch / export: library-level cap inside each loader
- merge-driver's pre-existing 50 MiB cap is untouched (intentionally tighter)
- tests: helper unit tests + integration tests for serve, build, benchmark,
  global_graph, callflow_html, and the query CLI wiring

* feat(security): sanitize_metadata at graph export boundaries

Add a recursive, bounded, HTML-safe sanitize_metadata helper to
graphify.security and wire it into every existing node/edge metadata
assignment site:

- scip_ingest.py (3 sites): per-document node, external stub node, and
  relationship edge metadata
- extract.py (1 site): bash extractor's add_node metadata
- symbol_resolution.py (1 site): Python import-guided call edge metadata

Helper policy:
- Strip control chars, html.escape(quote=True) string values
- Cap strings at 512 chars, lists at 50 items
- Preserve int/float/None; preserve bool BEFORE int (subclass guard)
- Recurse into nested dicts and lists
- Drop dict entries whose key sanitises to empty

Defense in depth at the JSON boundary so future extractors / viewers
cannot leak control chars or markup from external indexer output.

* feat(security): pin vis-network CDN with SRI hash

Pin the vis-network <script> tag in to_html() to a versioned URL
(vis-network@9.1.6) with a sha384 Subresource Integrity hash and
crossorigin="anonymous". Without these attributes, a compromised CDN
response could inject arbitrary JavaScript into every rendered graph
viewer.

Hash verified live against
https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js:

  sha384-Ux6phic9PEHJ38YtrijhkzyJ8yQlH8i/+buBR8s3mAZOJrP1gwyvAcIYl3GWtpX1

Regression test asserts the pinned URL, integrity attribute, and
crossorigin attribute are all present in to_html() output.

Follow-up: tree_html.py (D3) and callflow_html.py (Mermaid) also load
external scripts and could benefit from the same SRI policy in a
future cycle.

* fix(review): address real Copilot review findings in base stack

Resolves 7 issues found in upstream code review of PRs #893 and #954:

1. extract.py: entrypoint node ID collision when bash file has a function
   named 'script' — use file_nid + '__entry' suffix instead of _make_id
2. extract.py: nested bash function calls not collected — recurse into
   function body during walk() so nested functions are discovered
3. extract.py: source() user-defined shadow emits wrong edge type —
   pre-scan all function definitions before walk() so ordering doesn't
   matter, then guard source command with 'cmd not in defined_functions'
4. extract.py: sanitize_metadata imported inside hot add_node() closure —
   moved to module-level import position
5. symbol_resolution.py: _bash_make_id() diverged from extract._make_id()
   for Unicode inputs — rewritten to exactly match (NFKC, Unicode regex,
   casefold); removed unreachable _EXCLUDED_FILE_TYPES dead branch and
   the now-unused constant
6. semantic_cleanup.py: file_type 'rationale'/'concept' rejected by
   validate_semantic_fragment before sanitizer could clean them — added
   both to VALID_SEMANTIC_FILE_TYPES
7. scip_ingest.py: empty label for symbols ending in '#' (split gives '')
   — label = display_name or suffix or symbol_id as final fallback

All 7 issues covered by new failing-first regression tests (red → green).
Full pytest suite: 1239 passed, 4 pre-existing env-specific failures.

* fix(review): address PR #956 Copilot findings in watch.py and symbol_resolution.py

- watch.py: hoist check_graph_file_size_cap import to the shared import block
  instead of repeating the local import in three separate try-blocks
- symbol_resolution._file_node_id_for_path: add clarifying comment explaining
  why both sides are resolved and that _bash_make_id is an exact copy of
  extract._make_id (addressing reviewer concern about ID mismatch)

* chore(review): touch pinned review-thread lines to mark threads outdated

Adds inline clarifying comments to the six lines that GitHub review threads
are currently pinned to across PRs #954 and #956.  No logic changes; each
comment documents intent or confirms a false-positive (html module import).

* feat(diagnostics): report multigraph edge-collapse risk

Add graphify.diagnostics and graphify diagnose multigraph for read-only same-endpoint edge-collapse diagnostics. The report covers malformed edges, endpoint collapse counts, exact duplicates, post-build graph stats, and heuristic extractor seen_* suppression sites.

Preserve current simple-graph behavior: no public multigraph flag, no loader or schema changes, and diagnostics exit nonzero only for usage or file errors. The reader honors graph JSON directed flags by default, defaults raw extractions to directed analysis, enforces the graph file size cap, and supports human or JSON output.

* feat(multigraph): add runtime compatibility probe

New module graphify.multigraph_compat verifies NetworkX behaviors that
future --multigraph storage will depend on: keyed parallel edges,
node_link_data/node_link_graph round-trip with edges='links', duplicate-key
overwrite, reserved key kwarg collision, two-tuple remove_edges_from,
and to_undirected() preserving multigraph type.

Behavior probe, not version check. Both NX 3.4.2 (Py 3.10 lane) and
NX 3.6.1+ (Py 3.11+ lane) pass. Result cached for the process lifetime.

No call sites added — this PR adds the API surface only. Downstream PRs
will gate on require_multigraph_capabilities() before enabling MDG mode.

Refs: Wave 1 MultiDiGraph implementation order.

* test: filter known third-party analyze warnings

---------

Co-authored-by: vampyre <vampyre@local.net>
2026-05-22 13:22:51 +01:00
CandyandOmX 020cca2ebf Keep non-English query terms searchable (#964)
Graph queries filtered every token with len > 2, which dropped common two-character Chinese search terms while trying to suppress short English noise. Centralize query token selection and apply the length gate only to pure-English tokens so mixed or non-English terms remain searchable.

Constraint: Issue #962 reports space-separated Chinese query terms such as 前端, 依赖, and 安装 are lost by graphify query.

Rejected: Add Chinese segmentation now | the reported failure is fixed by preserving existing space-separated non-English tokens without expanding query behavior.

Confidence: high

Scope-risk: narrow

Directive: Keep CLI, MCP query, and benchmark query tokenization on one helper when changing query-term rules.

Tested: uv run --with pytest pytest tests/test_serve.py tests/test_query_cli.py tests/test_benchmark.py

Tested: graphify update .

Not-tested: Full test suite.

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-05-22 13:22:47 +01:00
Alex Ubillus 406bea47b5 fix swift extension nodes duplicating across files (#969)
tree-sitter-swift parses both `class Foo` and `extension Foo` as
`class_declaration`, and node ids carry the file stem, so `extension Foo`
in a sibling file produced a second `Foo` node instead of attaching to
the original. Same-file extensions already dedupe via seen_ids; only the
cross-file case leaked.

Per-file extraction now tags `extension` class_declarations, and the
corpus-level `extract()` runs a merge pass: when exactly one
non-extension declaration shares the label, the extension nodes redirect
onto it and their edges are rewritten (self-loops dropped, duplicates
collapsed). Extensions of types outside the corpus and ambiguous label
matches stay untouched.

On a 25-file Swift project this collapses Parser from 6 split nodes
(top of the god-node list, four entries) to one canonical node, and
lets the generic cross-file call resolver attach previously ambiguous
call edges to the right target.
2026-05-22 13:22:42 +01:00
dkramer-sevenbelow 06a9b72a38 fix(llm): honor GRAPHIFY_MAX_OUTPUT_TOKENS for OpenAI-compatible backends (#973)
Backends routed through _call_openai_compat (gemini, openai, kimi,
deepseek, ollama) silently ignored the documented env override when
their backend config dict carried a hardcoded max_completion_tokens.
The dispatcher used:

    cfg.get("max_completion_tokens", max_out)

which always returned the config-dict value when the key was present,
shadowing the env-var-resolved max_out.

For gemini specifically, the hardcoded cap of 16384 truncated
extracted-graph JSON mid-response on multi-document chunks (~17 specs
of 100-1500 lines each pushing the output past 16k tokens). Symptom:
cascading 'LLM returned invalid JSON, skipping chunk: Unterminated
string at column 4XXXX' followed by bisect-retry storms that bill
input tokens without producing graph nodes.

Fix: route the same _resolve_max_tokens(...) call that the Claude and
Bedrock paths already use, so the override applies uniformly across
backends.

Verified with gemini-2.5-pro over a 20-doc / 76k-input-token chunk:
output of 36008 tokens emitted without truncation, producing 193
nodes / 223 edges / 23 communities in a single chunk.
2026-05-22 13:22:27 +01:00
SafiandClaude Sonnet 4.6 076e6b7c06 fix cluster-only crash when graphify-out/ absent, add regression test (#934)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 18:27:53 +01:00
SafiandClaude Sonnet 4.6 f4da176851 bump version to 0.8.14
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 18:07:06 +01:00
SafiandClaude Sonnet 4.6 9e6192a6c2 fix stale wiki nodes (#936), gitignore fallback and --exclude flag (#945/#947), NAT64 SSRF false-positive
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 18:04:28 +01:00
SafiandClaude Sonnet 4.6 6939494b3e add backup_if_protected to snapshot graph before overwrite when semantic/curated (#834)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 21:57:09 +01:00
SafiandClaude Sonnet 4.6 4c95d02cbb bump version to 0.8.13
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 20:48:59 +01:00
SafiandClaude Sonnet 4.6 d84f07c2e7 fix node ID collisions, cache fastpath, absolute source_file paths, and failed-chunk manifest freeze
- fix SQL extractor using bare path.stem as node ID prefix — collides across same-named files in different dirs; use _file_stem() (directory-qualified) instead
- fix Python import resolver keying stem_to_entities by bare stem; add bare_to_qualified secondary index for absolute imports so cross-file edges survive duplicate filenames
- add stat-based mtime fastpath to file_hash: skip full SHA256 when size+mtime_ns unchanged, flush index atomically via atexit (same trade-off as make)
- add cache-check, merge-chunks, merge-semantic CLI subcommands so the skill pipeline can use library functions instead of inline Python
- fix absolute source_file paths from semantic subagents not being relativized before graph storage (#932): add root param to build_from_json/build/build_merge, pass scan target at both call sites
- fix failed semantic chunks permanently freezing their files in the manifest (#933): filter _manifest_files to only include doc/paper/image files that appear in sem_result nodes/edges before calling save_manifest

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 20:31:59 +01:00
SafiandClaude Sonnet 4.6 edb6e3cb98 update CHANGELOG for 0.8.12 with all post-bump fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 18:30:35 +01:00
SafiandClaude Sonnet 4.6 9f8b8b0072 docs: clarify code-only corpora skip semantic extraction (closes #836)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 18:26:11 +01:00
SafiandClaude Sonnet 4.6 a234c5238e fix skill large-corpus path and detect output
detect: add scan_root to return dict so skill can strip absolute prefix
  when computing relative subdirectory breakdown; remove stale --no-semantic
  flag reference from large-corpus warning (flag does not exist)

skill: clarify fast path checks CWD graphify-out/graph.json (project root);
  remove hardcoded --backend gemini from multi-subfolder example — users
  should pass whichever backend key they have; expand large-corpus gate
  instruction to use scan_root for relative paths, filter graphify-out/
  converted sidecars, and handle flat repos with no subdirectories

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 17:45:29 +01:00
SafiandClaude Sonnet 4.6 850c5457da skill: fast path for existing graphs, fix large-corpus gate, fix subfolder output
- Fast path: if graphify-out/graph.json exists and user is asking a question
  (not an explicit rebuild), skip detect entirely and run graphify query —
  prevents the skill from refusing large already-built corpora (#930)
- Raise FILE_COUNT_UPPER 200 → 500 so typical 200-500 file codebases no longer
  hit the large-corpus size gate on fresh extraction (#930)
- Subdirectory breakdown now strips the scan-root prefix so agent shows
  relative names (core/, service/) not absolute paths rooted at / (#930)
- Document multi-subfolder CLI pattern: graphify extract ./sub/ places
  graphify-out/ inside each subfolder; skill clobbers single root graphify-out
  when run on subfolders separately (#930)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 17:36:30 +01:00
SafiandClaude Sonnet 4.6 47e65658c7 bump version to 0.8.12 — security and wiki fixes
Security: _is_sensitive now flags underscore-prefixed names (api_token.txt, oauth_token.json) by replacing \b with lookarounds; adds _SENSITIVE_DIRS check on parent path components (parts[:-1]) so .ssh/, secrets/, .aws/ directories are always skipped; aligns both patterns to (?![a-zA-Z]) for consistent underscore-after-keyword behavior (#920)

Fix: --wiki Relationships section always empty because _cross_community_links read community from node attrs (always None) instead of the communities dict; _god_node_article had the same bug and never linked to the owning community; fixed by building a node->community map in to_wiki() and threading it through (#925)

Fix: --watch now respects .graphifyignore; patterns loaded once at startup, handler checks _is_ignored before extension filter so node_modules/, .venv/, build/ churn no longer triggers rebuilds (#928)

Fix: C++ struct inheritance edges via base_class_clause; initialize base="" per iteration to prevent stale carryover (#915)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 15:43:45 +01:00
Safi 2209a9c1e8 treat graphify <path> as graphify extract <path> — fix unknown command for direct path invocation 2026-05-18 14:54:04 +01:00
Safi a5eb15b880 bump version to 0.8.11 2026-05-18 12:09:16 +01:00
balloon72andhanmo1 a4a475c8b6 perf(analyze): reuse degrees for surprise scoring (#914)
Co-authored-by: hanmo1 <hanmo1@lenovo.com>
2026-05-18 12:05:21 +01:00
balloon72andhanmo1 f0d29a1c6d fix(codex): keep graph-first guidance with dirty graph output (#913)
* fix(codex): keep graph-first guidance with dirty graph output

* fix(codex): include dirty graph guidance in agents install

---------

Co-authored-by: hanmo1 <hanmo1@lenovo.com>
2026-05-18 12:05:17 +01:00
balloon72andhanmo1 4aa04ddc7d fix(opencode): remove invalid general-purpose agent guidance (#911)
* fix(opencode): remove invalid general-purpose agent guidance

* fix(opencode): define smaller chunk fallback

* fix(opencode): keep large-corpus chunk sizing consistent

---------

Co-authored-by: hanmo1 <hanmo1@lenovo.com>
2026-05-18 12:05:13 +01:00
balloon72 44638dd424 test(hooks): cover old git hook path output (#910) 2026-05-18 12:04:49 +01:00
Jonathan HillandClaude Sonnet 4.6 f5fea13dbc fix: guard against empty choices and None message in LLM responses (#924)
The OpenAI-compatible API can return HTTP 200 with an empty `choices`
list or with `choices[0].message = None` (e.g. content-filtered
responses on Gemini, overwhelmed Ollama instances). Without a guard,
both sites raise an unhandled IndexError or AttributeError.

`_call_openai_compat` already documents this hazard ("Ollama can return
HTTP 200 with empty/null content") and has `_response_is_hollow` logic
downstream, but `_response_is_hollow` is unreachable when the choices
list itself is empty. The new guard closes that gap.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 12:04:45 +01:00
Safi 596d800aa1 bump version to 0.8.10 2026-05-17 23:09:50 +01:00
SafiandClaude Sonnet 4.6 2d783e569a fix hooks phantom dir on git < 2.31, save_manifest incremental data loss, cohesion rounding, C++ inheritance; add --resolution and --exclude-hubs
- hooks.py: drop --path-format=absolute (added git 2.31), validate no newlines in path, anchor relative paths on repo root (#907)
- detect.py: seed save_manifest from existing manifest before loop so incremental callers don't erase untouched file entries (#917)
- cluster.py: drop round(..., 2) from cohesion_score so split threshold 0.05 fires correctly; add resolution param to _partition and cluster; add exclude_hubs_percentile to cluster with majority-vote reattachment (#919)
- report.py: format cohesion with :.2f for display
- __main__.py: wire --resolution and --exclude-hubs into extract and cluster-only commands (#919)
- C++ inheritance already written to disk by analysis agent (#915)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 23:05:48 +01:00
Safi f7160c81c5 fix Rust cross-crate spurious INFERRED edges: skip scoped_identifier and trait-method blocklist from raw_calls (#908) 2026-05-17 13:12:49 +01:00
Safi 96e17adf4d bump version to 0.8.9 2026-05-17 11:59:57 +01:00
Safi 46738a1365 add DeepSeek to README privacy section 2026-05-17 11:54:54 +01:00
Safi 9b884f7d1a add deepseek backend (deepseek-v4-flash, DEEPSEEK_API_KEY) 2026-05-17 11:49:11 +01:00
cinosandHermes Agent ec4c87c86e fix(export): accept edges-only graph JSON for wiki export (#909)
Co-authored-by: Hermes Agent <hermes-agent@users.noreply.github.com>
2026-05-17 11:32:55 +01:00
Christopher BeaulieuandClaude Sonnet 4.6 2aaa216825 fix(analyze): exclude npm dep-block keys from god-node selection (#905)
* fix(analyze): exclude npm dep-block keys from god-node selection

Extends _JSON_NOISE_LABELS in graphify/analyze.py with the six npm
package.json dependency-block keys (dependencies, devDependencies,
peerDependencies, optionalDependencies, bundledDependencies,
bundleDependencies — lowercased to match the existing .strip().lower()
comparison in _is_json_key_node).

On JS/TS corpora with non-trivial dependency counts, the dep-block key
node accumulates contains+imports edges to every package entry and was
surfacing as the top god-node in the report. The fix is a one-line
extension of the existing frozenset; no new helpers or code paths.

Includes a parametrized regression test in tests/test_analyze.py
covering all five npm keys: dependencies, devDependencies,
peerDependencies, optionalDependencies, bundledDependencies.

Validated live against rsl-siege-manager @ 6085fd66 — zero npm dep-block
keys in the top-10 god-nodes after the fix. Pre-existing failures
(Windows symlink + SQL tree-sitter): 17, unchanged.

Closes #2

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

* style: drop fork-local issue refs from analyze comments

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 11:32:53 +01:00
Christopher Beaulieu 6018831193 fix(llm): force UTF-8 encoding on _call_claude_cli subprocess + loud failure on chunk errors (#906)
* fix(extract): force UTF-8 encoding on subprocess + loud failure on chunk errors

On Windows cp1252, subprocess.run(..., text=True) without encoding= raises
UnicodeEncodeError for chars like → ✅ ≥ in chunk content. Both
_call_claude_cli (llm.py:426) and the _call_llm claude-cli branch (llm.py:959)
lacked encoding=.

- Add encoding="utf-8" to both subprocess.run sites.
- Track failed_chunks in extract_corpus_parallel merged result dict.
- Print [graphify] WARNING: N/M semantic chunk(s) failed summary to stderr at
  end of run when any chunk failed, so silent partial failures are visible.
- Add tests/test_charmap_encoding.py: 10 regression tests covering subprocess
  encoding kwarg, loud-failure summary, and substitution validation.

Closes #3

* style: drop fork-local issue refs from llm/test comments
2026-05-17 11:32:38 +01:00
Safi 0ca8d3d9f7 bump version to 0.8.8 2026-05-16 23:52:24 +01:00
Safi b4c0f01bfd update README and CHANGELOG for graphify prs (0.8.8) 2026-05-16 22:55:43 +01:00
Safi 6d54b25d20 stop tracking uv.lock (library, not app) 2026-05-16 22:38:33 +01:00
SafiandClaude Sonnet 4.6 cc9e5816a7 add graphify prs: graph-aware PR dashboard with triage, worktrees, conflict detection
- new `graphify prs` subcommand: terminal dashboard of open PRs with CI/review
  state, worktree mapping, and graph impact (blast radius / communities touched)
- `graphify prs <number>`: deep dive on a single PR
- `graphify prs --triage`: AI triage ranking via any configured backend
  (claude, kimi, openai, gemini, claude-cli, ollama — auto-detected from env)
- `graphify prs --worktrees`: worktree → branch → PR mapping
- `graphify prs --conflicts`: PRs sharing graph communities with node labels
- concurrent gh pr diff fetching via ThreadPoolExecutor (up to 8 workers)
- graph impact lazy: only fetched when needed (deep dive / triage / conflicts)
- MCP tools: list_prs, get_pr_impact, triage_prs
- auto-detects default branch via gh repo view → git symbolic-ref → main
- 41 tests, all passing; uv.lock added to .gitignore

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 22:36:58 +01:00
SafiandClaude Sonnet 4.6 d717415522 Bump version to 0.8.7, update CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:25:04 +01:00
SafiandClaude Sonnet 4.6 b82d5d147f fix review findings from #898 #895 #899 corrections
- Revert .h -> extract_c (C++ grammar rejects C++ keywords used as identifiers
  in Linux-kernel-style headers; .hpp/.hxx/.hh already route to extract_cpp)
- Fix field_declaration block: use children_by_field_name("declarator") instead
  of iterating all children with wrong type guard; replace ensure_node (undefined)
  with add_node
- Fix _import_c include resolution: use _make_id(str(resolved)) to match the
  file_nid scheme _extract_generic uses, not _make_id(_file_stem(resolved))
- Fix exact_merges counter in dedup Pass 1 to count only within-file merges
  actually performed, not the raw unpartitioned group sizes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:20:49 +01:00
SafiandClaude Sonnet 4.6 500e4a732d fix #898 #895 #899: C++ header extraction, dedup cross-file merge, include path resolution
- Route .h files through extract_cpp (was extract_c), fixing missing method nodes in C++ headers
- Extend _get_cpp_func_name to handle field_identifier, destructor_name, operator_name
- Add CPP-specific field_declaration branch in _extract_generic to emit class method/field nodes
- Partition dedup Pass 1 by source_file: only union same-label nodes within the same file;
  cross-file matches fall through to Pass 2 fuzzy, preventing generic-label god nodes
- Add _resolve_c_include_path: resolve quoted #include paths to real files on disk so
  target node IDs match what _extract_generic creates, fixing dangling include edges

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:12:09 +01:00
SafiandClaude Sonnet 4.6 a316590adc Fix query seed scoring: IDF weighting, dynamic K seeds, actionable truncation
Common terms like 'error'/'exception' were stealing BFS seed slots from
rare identifiers like 'FooBarService', burning the token budget on noise.

- _compute_idf: weights query terms by inverse document frequency, cached
  on G.graph so cost is paid once per graph load not per query
- _score_nodes: multiplies each tier bonus by IDF weight
- _pick_seeds: replaces fixed top-3 with gap-ratio selection — stops adding
  seeds when score drops below 20% of the top match
- _subgraph_to_text: truncation hint now tells Claude to narrow with
  context_filter or use get_node instead of just saying 'truncated'

Fixes #897

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 16:20:20 +01:00
SafiandClaude Sonnet 4.6 b1ade00ece Bump version to 0.8.6, update CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:37:32 +01:00
SafiandClaude Sonnet 4.6 0157d5f6ad Add pytest testpaths to stop crawling external repos in subdirs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:30:38 +01:00
SafiandClaude Sonnet 4.6 766566f6a8 Fill test gaps from PR #890 and fix case-insensitive path in _is_json_key_node
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:27:01 +01:00
SafiandClaude Sonnet 4.6 aa541a680a Suppress code-doc INFERRED edges and filter JSON key nodes from god_nodes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:23:38 +01:00
Safi 8105266800 Add .gitattributes to fix GitHub language detection showing HTML instead of Python 2026-05-16 14:16:07 +01:00
Safi f86b0309e7 Merge pull request #891 from jattree/fix/install-guidance-query-first
Clean merge — fixes real token-bloat regression where GRAPH_REPORT.md was loaded on every question. All 10 install surfaces now route to graphify query first. Also fixes hidden bug where re-running graphify install after upgrade didn't refresh stale hook text.
2026-05-16 14:13:01 +01:00
Safi c74b95c44c Merge pull request #888 from kanya-approve/feat/nuitka-build
Clean merge — PEP 735 [dependency-groups] is invisible to pip/uv tool install, zero runtime impact.
2026-05-16 14:12:58 +01:00
Safi 1ba3e37d27 Merge pull request #887 from alphanury/feat/auto-detect-symlinks-default
Clean merge — fixes real silent data-loss bug in --update on symlinked repos, backward-compatible, inherits existing cycle protection. Follow-up: consider tightening _auto_follow_symlinks to is_symlink() and is_dir() to avoid tripping on incidental symlinked files at root.
2026-05-16 14:12:54 +01:00
Safi 31a9f13cc7 Merge pull request #886 from kanya-approve/chore/commit-uv-lock
Clean merge — uv.lock is correct to commit per current uv guidance, all 152 packages from PyPI only, zero impact on pip/wheel consumers.
2026-05-16 14:12:52 +01:00
Jon Attree d1a2c3f958 Stop telling assistants to read GRAPH_REPORT.md first (#580)
The current install writes "ALWAYS read graphify-out/GRAPH_REPORT.md
before reading any source files, running grep/glob searches, or
answering codebase questions" into CLAUDE.md and equivalents, plus a
PreToolUse hook with the same instruction. On real corpora that report
is 47-91K characters, so Claude Code sessions pay roughly 12-25K tokens
of context up front for every search-able question. Three users on #580
reported this making token usage worse than no install at all.

Reproduced on a 1500-file Go monorepo: a "where is X defined" question
takes 5 tool calls and 34k agent tokens with stock graphify, 4 calls
and 30k tokens with no install, and 1 call and 30k tokens after this
patch. Stock graphify's Read of GRAPH_REPORT.md hit Claude Code's 25k
token cap and failed entirely, then recovered via a partial read plus
graphify explain.

Demote GRAPH_REPORT.md to a fallback for broad architecture review and
route first action to the existing scoped commands: graphify query,
path, explain. The 2k-budget BFS subgraph already exists in serve.py;
the install just wasn't pointing at it.

Updated across all ten install surfaces: _SETTINGS_HOOK,
_CLAUDE_MD_SECTION, _AGENTS_MD_SECTION, _GEMINI_MD_SECTION,
_GEMINI_HOOK, _VSCODE_INSTRUCTIONS_SECTION, _ANTIGRAVITY_RULES,
_KIRO_STEERING, _CURSOR_RULE, _OPENCODE_PLUGIN_JS. Plus the matching
sentence in README.md, which also fixes an inaccuracy about Codex
hooks (Codex's installed hook is intentionally a no-op because Codex
rejects additionalContext, so the guidance there comes from AGENTS.md,
not the hook).

Five installers (claude, agents, vscode, gemini, kiro, cursor) were
also writing their section only when no marker was present, so users
who installed pre-fix kept the old "ALWAYS read" text after upgrading.
Added _replace_or_append_section helper that updates in place when the
graphify marker is found. claude_install also no longer returns before
re-running _install_claude_hook, so stale settings.json hook payloads
get refreshed on upgrade.

Tests:
- tests/test_install_strings.py (3): every install constant still
  mentions `graphify query` and matches no banned report-first regex.
- tests/test_install_upgrade.py (7): seeds each platform's instruction
  file with pre-fix text, runs install, asserts the on-disk file
  reflects the new policy.
- test_claude_md.py idempotency tests still pass.

Fixes #580.
2026-05-15 20:17:52 -07:00
Brian Kanya 246f4001d2 build: add dev deps for Nuitka onefile binary builds
Run with:
  uv run python -m nuitka --project --mode=onefile \
    --output-dir=build --output-filename=graphify \
    --assume-yes-for-downloads

Produces build/graphify, a self-contained ~60 MB binary that bundles
the package's skill *.md files (picked up automatically from
[tool.setuptools.package-data] via Nuitka's --project flow). The
existing wheel-build path (uv build via setuptools.build_meta) is
unchanged.

[tool.nuitka] config in pyproject.toml is not used: in --project mode
Nuitka builds the option list from setuptools distribution metadata
(_dumpBuildConfiguration in nuitka/distutils/DistutilsCommands.py)
and never reads [tool.nuitka], so output-dir / output-filename / etc.
must be passed on the CLI.

patchelf is required at build time on Linux and macOS for Nuitka's
standalone/onefile linking; gated by sys_platform != 'win32' so
Windows dev installs skip it.
2026-05-15 21:58:16 -04:00
Alpha Nury 5e178b9cd4 feat(detect): auto-detect symlinked children when follow_symlinks is unset
When `root` has at least one direct symlinked child, default to following
symlinks instead of silently dropping their contents. This makes "fake
working dir" patterns (a folder full of symlinks pointing at scattered
source dirs) work transparently — the caller no longer has to know to
pass `follow_symlinks=True`.

Concrete motivating shape:

    ~/projects/research-corpus/
    ├── papers   -> /external/drive/papers
    ├── notes    -> /external/drive/notes
    └── code     -> /external/drive/code

Before: `--update` invoked `detect_incremental(root)` without passing
`follow_symlinks=True`, so the scan saw the small set of files actually
inside the root and missed everything reachable only through a symlink.
Result: every legitimate new file was missed, and the manifest paths
were marked as deleted.

After: when `follow_symlinks` is left at its default `None`, `detect()`
runs `_auto_follow_symlinks(root)` (one cheap `iterdir()` + `is_symlink()`
loop) and follows symlinks if any direct child is one. Behaviour is
unchanged for ordinary scans (no direct symlinks → False, as before).

Override is always possible by passing an explicit `follow_symlinks=True`
or `follow_symlinks=False`; existing tests confirming the explicit
behaviour continue to pass unchanged.

Backwards compatibility:
- Type annotation: `bool` -> `bool | None`. Callers passing `True`/`False`
  continue to work identically. Callers passing nothing get the new
  auto-detect.
- No new dependencies.
- Cheap: one `iterdir()` call once per detect() invocation.

Tests:
- 3 new tests in tests/test_detect.py:
  - test_detect_auto_detects_direct_symlink_child
  - test_detect_default_does_not_follow_when_no_symlinks
  - test_detect_explicit_false_overrides_auto_detect
- Full tests/test_detect.py + tests/test_incremental.py: 49/49 pass.
2026-05-16 02:23:02 +02:00
Brian Kanya 0b54974719 chore: commit uv.lock for reproducible installs
Removes uv.lock from .gitignore and tracks the lockfile so contributors
and CI get the same resolved dependency tree. graphify is shipped as a
CLI (uv tool install graphifyy / uvx graphifyy), so the application
convention of committing the lockfile fits better than the library
convention of ignoring it.
2026-05-15 19:36:40 -04:00
Safi d14e8a72d1 Suppress cross-language INFERRED calls/uses edges in surprising connections
In Python+TypeScript monorepos, the call and import resolvers match by
label across language boundaries (AuthError -> Member), producing false
positives that dominate 'Surprising Connections' due to cross-dir (+2)
and cross-community (+1) bonuses.

Expand the existing calls guard to also cover uses edges, and zero the
cross-dir and cross-community bonuses for these pairs — not just conf_bonus.
Leaves semantically_similar_to, EXTRACTED, and AMBIGUOUS edges unaffected.

5 new tests: calls suppressed, uses suppressed, semantically_similar_to
preserved, same-language INFERRED preserved, cross-language EXTRACTED preserved.
2026-05-16 00:07:18 +01:00
Safi fa70449d80 Suppress autogenerated module docstrings from rationale extraction (#882)
Alembic/Flask-Migrate revisions, Django migrations, and protobuf/OpenAPI
generated files produce hundreds of degree-1 rationale nodes labeled as
'possible documentation gaps'. Their module docstrings are revision
annotations or boilerplate, not architectural rationale.

- Add _is_autogenerated_python() in extract.py detecting Alembic, Django
  migrations, and generic DO-NOT-EDIT markers; skip module docstring only
- Function/class docstrings inside those files still extracted as normal
- report.py: exclude file_type=rationale nodes from isolated-node gaps
  section — rationale nodes are degree-1 by construction; flagging them
  as missing edges was always wrong
- 5 new tests covering Alembic, Django, protobuf, false-positive guard,
  and function-docstring passthrough
2026-05-16 00:01:57 +01:00
Safi 63926c5e39 Add rsl-siege-manager case study to 0.8.5 CHANGELOG 2026-05-15 23:42:12 +01:00
Safi 9ca27aad31 Update CHANGELOG for 0.8.2 through 0.8.5 2026-05-15 23:40:14 +01:00
Safi aaf66f1cee Bump version to 0.8.5 2026-05-15 23:35:36 +01:00
Safi Shamsi 8076687d52 worked(case-study): add rsl-siege-manager (Python + TypeScript monorepo)
Cherry-picked from PR #881 (merged into v7) — adds case study artifacts
matching the worked/karpathy-repos/ convention.
2026-05-15 23:28:37 +01:00
SafiandClaude Sonnet 4.6 6f8e6c59f5 fix gitignore parent-exclusion rule (#882) and dedup false merges on short labels (#878)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 22:57:36 +01:00
SafiandClaude Sonnet 4.6 299b6baa26 v0.8.4: SQL FK/trigger extraction, deletion pruning fixes, community label normalization
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 15:31:22 +01:00
SafiandClaude Sonnet 4.6 1b3296a093 Fix Windows skill temp files polluting project root
Move all intermediate data files and temp step scripts from the
project root into graphify-out/ to match the bash skill behaviour.
Also fix the > redirect on detect.json which wrote UTF-16LE in
PowerShell 5.1 - now uses Out-File -Encoding utf8 consistently.

Files moved: .graphify_detect.json, .graphify_ast.json,
.graphify_extract.json, .graphify_semantic.json,
.graphify_analysis.json, .graphify_labels.json,
.graphify_incremental.json, .graphify_old.json,
all .graphify_step_*.py temp scripts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 15:07:59 +01:00
Safi 5f2c55bc95 Bump version to 0.8.3 2026-05-15 14:12:59 +01:00
SafiandClaude Sonnet 4.6 ac9587bfda Fix antigravity Windows skill and Python detection for uv/pipx (#831)
antigravity install on Windows now installs skill-windows.md instead
of skill.md by redirecting to a new antigravity-windows platform config
at install time via sys.platform check.

Python detection in Find-GraphifyPython now uses uv tool dir (respects
UV_TOOL_DIR) and pipx environment --value PIPX_LOCAL_VENVS (respects
PIPX_HOME) instead of guessing from the shim location. The graphify.exe
shim and python.exe live in different directories for both uv and pipx
on Windows so the previous Get-Command approach was wrong.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 14:09:31 +01:00
Safi da4ec1d5e7 Bump version to 0.8.2 2026-05-15 11:29:31 +01:00
SafiandClaude Sonnet 4.6 1ac3b96897 Fix Windows skill Python detection for uv tool installs (#831)
graphify.exe and python.exe are co-located in the same Scripts\
directory for both uv tool and pipx installs. Use Get-Command graphify
to find that directory and pick up the correct Python instead of
falling through to bare python (which is a different interpreter
that doesn't have graphify).

Also replace all bare `python .graphify_*` invocations throughout
the skill with `& (Get-Content graphify-out\.graphify_python)` so
every step uses the saved interpreter, and fix the bash $(cat ...)
syntax to PowerShell & (Get-Content ...).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 11:25:59 +01:00
SafiandClaude Sonnet 4.6 df40e4d818 fix #873 index dot dirs, fix #874 MCP hot-reload on graph change
#873: Remove blanket dot-prefix exclusion from detect.py and
extract.py collect_files(). Add framework caches (.next, .nuxt,
.turbo, .angular, .idea, .cache, .parcel-cache, .svelte-kit,
.terraform, .serverless, .graphify) to _SKIP_DIRS so they stay
blocked. Meaningful dot dirs (.github, .claude, etc.) are now
indexed.

#874: Add _maybe_reload() with mtime+size stat key and threading.Lock
to serve.py. call_tool and read_resource call _maybe_reload() on
every request; the graph reloads automatically when graph.json changes
without restarting the MCP server.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 08:51:46 +01:00
SafiandClaude Sonnet 4.6 d172650065 Note callflow-html auto-regeneration in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:38:48 +01:00
SafiandClaude Sonnet 4.6 5f5b70ff91 Add 0.8.1 to CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:34:32 +01:00
SafiandClaude Sonnet 4.6 daafec20ba Update README for v0.8.1: CI badge, file types, branch references
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:25:30 +01:00
SafiandClaude Sonnet 4.6 914a32d000 Bump version to 0.8.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:23:26 +01:00
SafiandClaude Sonnet 4.6 4d6818190d Fix detect.py missing .sh/.json extensions and security harden extractors
- Add .sh, .bash, .json to CODE_EXTENSIONS in detect.py so files reach extractor
- Fix test_detect_incremental manifest path collision with new .json extension
- Update test_watch to reflect .json/.sh are now watched extensions
- B-1: only emit source imports for paths that exist on disk
- J-1: replace stat()+read() with bounded read to eliminate TOCTOU
- J-3: move pair_count cap inside loop so it is honoured exactly
- J-4: namespace $ref/extends refs with "ref_" prefix to prevent ID collision

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:18:33 +01:00
SafiandClaude Sonnet 4.6 03dd794a80 Add v8 to CI branch list
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:09:16 +01:00
SafiandClaude Sonnet 4.6 40b9b84caa Add tree-sitter bash and JSON extractors (#866)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:07:09 +01:00
485 changed files with 91333 additions and 9820 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
.git
.github
.venv
venv
__pycache__
*.pyc
.pytest_cache
.ruff_cache
.mypy_cache
dist
build
*.egg-info
graphify-out
graphify-benchmark
graphify_eval
graphify_test
worked
llm-stack-corpus
llm-stack-demo
product-site
ebook
tests
docs
*.md
!README.md
+6
View File
@@ -0,0 +1,6 @@
# Tell GitHub Linguist to ignore generated/example HTML files when calculating
# the repo's primary language. Without this, large graph.html artifacts in
# worked/ dominate the byte count and the repo shows as HTML instead of Python.
worked/**/*.html linguist-vendored=true
graphify-out/**/*.html linguist-vendored=true
*.html linguist-detectable=false
+81 -12
View File
@@ -2,12 +2,50 @@ name: CI
on:
push:
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "main"]
pull_request:
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "main"]
workflow_dispatch:
jobs:
skillgen-check:
# Fast lint-style guard: the skill files under graphify/ are generated from
# the fragments in tools/skillgen/. This fails if someone hand-edited a
# generated file or forgot to re-run the generator and bless expected/, and it
# runs the build-time validators that guard per-host coverage, the file_type
# enum, the monolith round-trips, and the always-on round-trips.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
# The audit-coverage, monolith-roundtrip, and always-on-roundtrip
# validators read blobs from origin/v8. A shallow checkout omits that
# ref, so fetch the full history here and the validators run for real
# (rather than skipping). The other jobs stay shallow.
fetch-depth: 0
- name: Install uv
uses: astral-sh/setup-uv@v8.1.0
with:
python-version: "3.12"
# --frozen keeps uv from re-resolving and rewriting uv.lock as a side
# effect of `uv run`; the lock is committed and must not churn in CI.
- name: Check generated skill artifacts are up to date
run: uv run --frozen python -m tools.skillgen --check
- name: Audit per-host v8 coverage
run: uv run --frozen python -m tools.skillgen --audit-coverage
- name: Check the file_type enum is a singleton
run: uv run --frozen python -m tools.skillgen --schema-singleton
- name: Round-trip the monoliths against v8
run: uv run --frozen python -m tools.skillgen --monolith-roundtrip
- name: Round-trip the always-on blocks against v8
run: uv run --frozen python -m tools.skillgen --always-on-roundtrip
test:
runs-on: ubuntu-latest
strategy:
@@ -15,23 +53,54 @@ jobs:
python-version: ["3.10", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
# test_skillgen.py reads pre-split skill bodies from the immutable
# baseline commit via `git show`; a shallow checkout omits that history
# and the baseline tests fail. Full history mirrors the skillgen-check job.
fetch-depth: 0
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
- name: Install uv
uses: astral-sh/setup-uv@v8.1.0
with:
python-version: ${{ matrix.python-version }}
# --frozen installs straight from the committed uv.lock without re-resolving
# or rewriting it, so CI never churns the lock.
- name: Install dependencies
run: |
pip install -e ".[mcp,pdf,watch,sql]"
pip install pytest
run: uv sync --all-extras --frozen
- name: Run tests
run: |
python -m pytest tests/ -q --tb=short
run: uv run --frozen pytest tests/ -q --tb=short
- name: Verify install works end-to-end
run: |
graphify --help
graphify install
uv run --frozen graphify --help
uv run --frozen graphify install
security-scan:
# The dev deps already include bandit, pip-audit, and safety. Run them in
# CI so a new HIGH-severity finding or vulnerable dependency is caught on
# the PR that introduces it, rather than at the next manual audit.
# Non-blocking for now (continue-on-error) to avoid breaking CI on
# pre-existing findings; remove continue-on-error after the initial
# cleanup pass.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Install uv
uses: astral-sh/setup-uv@v8.1.0
with:
python-version: "3.12"
- name: Install dependencies
run: uv sync --frozen
- name: bandit (static security analysis)
continue-on-error: true
run: uv run --frozen bandit -r graphify -ll
- name: pip-audit (dependency vulnerabilities)
continue-on-error: true
run: uv run --frozen pip-audit --strict
+64
View File
@@ -0,0 +1,64 @@
name: Release graph asset
on:
release:
types: [published]
workflow_dispatch:
jobs:
build-graph:
runs-on: ubuntu-latest
permissions:
contents: write # needed to upload release assets
steps:
- uses: actions/checkout@v6
- name: Install uv
uses: astral-sh/setup-uv@v8.1.0
with:
python-version: "3.12"
- name: Install graphify
run: uv sync --frozen
- name: Build graph of graphify source (AST-only, no API cost)
# graphify/skills/ contains 126+ .md files that trigger the LLM pass.
# Temporarily ignore all .md files so extraction stays pure AST (no API key needed).
run: |
echo "*.md" >> .graphifyignore
echo "*.txt" >> .graphifyignore
uv run --frozen graphify extract graphify/ --out .
git checkout .graphifyignore 2>/dev/null || rm -f .graphifyignore
- name: Cluster, label communities and generate GRAPH_REPORT.md
# cluster-only writes GRAPH_REPORT.md and names communities (no LLM needed
# for basic numeric labels; --no-label skips LLM labeling entirely).
run: uv run --frozen graphify cluster-only . --no-label
- name: Generate HTML viewer
run: uv run --frozen graphify export html --graph graphify-out/graph.json
- name: Bundle release asset
run: |
mkdir -p dist-graph
cp graphify-out/graph.json dist-graph/
cp graphify-out/graph.html dist-graph/
[ -f graphify-out/GRAPH_REPORT.md ] && cp graphify-out/GRAPH_REPORT.md dist-graph/ || true
tar -czf graphify-self-graph.tar.gz -C dist-graph .
echo "Asset contents:"
tar -tzf graphify-self-graph.tar.gz
- name: Upload to GitHub release
if: github.event_name == 'release'
uses: softprops/action-gh-release@v2
with:
files: graphify-self-graph.tar.gz
- name: Upload as workflow artifact (for workflow_dispatch runs)
if: github.event_name == 'workflow_dispatch'
uses: actions/upload-artifact@v4
with:
name: graphify-self-graph
path: graphify-self-graph.tar.gz
retention-days: 7
+11 -1
View File
@@ -18,12 +18,22 @@ graphify-out/
.graphify_python
.claude/
skills/
# The packaged skill bundles under graphify/skills/ are generated, committed
# artifacts (rendered by tools/skillgen). Keep them tracked even though the
# broad skills/ rule above ignores install-target skill dirs elsewhere.
!graphify/skills/
!graphify/skills/**
# The skillgen core fragments are the human-edited source of the lean SKILL.md.
# A global "core" ignore (for core dumps) would otherwise drop them.
!tools/skillgen/fragments/core/
!tools/skillgen/fragments/core/**
docs/superpowers/
.vscode/
.kilo
openspec/
uv.lock
# Local benchmark scripts — never commit
scripts/run_k2_*.py
scripts/llm.py
scripts/benchmark_kimi*.json
scripts/benchmark_kimi*.py
paper/
+22
View File
@@ -0,0 +1,22 @@
# Run with: uv run pre-commit install (pre-commit is already a dev dependency)
# One-off across the tree: uv run pre-commit run --all-files
#
# The skillgen hook is the local anti-drift guard. The skill files under
# graphify/ are generated from the fragments in tools/skillgen/; a hand-edit to
# a generated file fails this check the same way CI does. Run
# `python -m tools.skillgen` then `--bless` to regenerate after a fragment edit.
repos:
- repo: local
hooks:
- id: skillgen-check
name: skillgen --check (generated skill artifacts are up to date)
entry: python -m tools.skillgen --check
language: system
pass_filenames: false
always_run: true
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.14
hooks:
- id: ruff
args: ["--config", "pyproject.toml"]
+403
View File
@@ -2,6 +2,409 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## Unreleased
## 0.8.43 (2026-06-19)
- Feat: package manifests are now parsed deterministically into a dependency graph. `apm.yml`, `pyproject.toml`, `go.mod`, and `pom.xml` each yield ONE canonical package node per package (keyed by name) plus `depends_on` edges, routed to the AST path so the LLM never sees them. Previously `apm.yml` was an LLM-handled document, so the same package got a different file-anchored id from its own manifest than from each dependent's dependency reference and split into duplicate nodes; a package referenced from N manifests is now a single hub node (#1377).
- Feat: markdown links now become graph edges. `extract_markdown` only emitted heading nodes + `contains` edges and never parsed link syntax, so a doc full of `[text](./other.md)` links (e.g. `index.md`, `table-of-contents.md`) had no edges to what it links and never became a hub. Inline links, reference-style links, and `[[wikilinks]]` are resolved relative to the source file (external URLs / in-page anchors / images skipped) and emitted as `references` edges, with targets resolved via the same node-id recipe so they merge onto the real doc node (#1376).
- Security: bumped vulnerable dependencies to patched versions — `pypdf` 6.11.0→6.13.3 (CVE-2026-48155/48156), `yt-dlp` 2026.3.17→2026.6.9, `pyjwt` 2.12.1→2.13.0, `cryptography` 48.0.0→49.0.0, `python-multipart` 0.0.28→0.0.32 — with lower-bound floors for the direct deps (`pypdf`, `yt-dlp`) so installs get the patched versions (#1375; thanks @hypnwtykvmpr).
- Fix: the semantic extract entry points (`extract_corpus_parallel`, `extract_files_direct`) crashed with `AttributeError` when passed `str` paths instead of `pathlib.Path`. Both now coerce `files = [Path(f) for f in files]` at entry (#1386).
- Fix: community labeling now recovers from a malformed-JSON batch by splitting it at the midpoint and retrying each half (mirroring the extract path), instead of logging-and-skipping it — which silently lost ~100 community names per failed batch on large graphs (#1280, #1278; thanks @CJdev232).
- Fix: `graphify hook install` no longer creates a literal backslash-named junk directory and reports false success when `core.hooksPath` (or `git rev-parse --git-path hooks`) is a Windows-style path under WSL. Drive-letter / embedded-backslash hooks paths are now rejected with a clear error (#1385).
- Refactor: node-ID normalization is unified into a single `graphify.ids` module. `extract._make_id`, `build._normalize_id`, `mcp_ingest._make_id`, and `symbol_resolution._bash_make_id` were four hand-synced copies of the same NFKC/casefold recipe — the root of the recurring ghost-node bug class (#811/#550/#1033/#1104). All four now delegate to one implementation guarded by contract + hypothesis property tests (#1378; thanks @danielnguyenfinhub).
## 0.8.42 (2026-06-18)
- Fix: large text documents are no longer silently truncated during semantic extraction. `_read_files` capped every file at 20,000 characters, so a Markdown/text/rST document longer than that had everything past the cap dropped — the model never saw it, and the packer/adaptive-retry path couldn't recover ("packing can't shrink one big file"). Oversized splittable-text files are now sliced at heading/paragraph boundaries into units that each fit the cap and together cover the whole file; every slice reports its parent file as `source_file`, so the graph is not fragmented per-slice. A single slice that still overflows the model's output is bisected and retried. Code files and PDFs are never sliced (they keep whole-symbol / page handling). (#1369)
- Fix: `/graphify --update` no longer deletes a changed file's freshly re-extracted nodes. The `0.8.41` `root=` fix (#1361) made `build_merge`'s prune actually match relative `source_file` values — which then matched the just-re-extracted nodes of *changed* files (still listed in `prune_sources`) and removed them, so an `--update` on a changed file could wipe its nodes. The update runbook now prunes only genuinely **deleted** files; changed files are reconciled by `build_merge`'s replace-on-re-extract (#1344). The full build also now passes `root=` to `build_from_json`, and the extraction-spec `source_file` is pinned to the verbatim path, so the full build and incremental updates never drift on node-key base. (#1366; thanks @RelywOo)
- Fix: Java `record` declarations are now modeled as first-class type nodes (they share `class_declaration`'s name/body/interfaces fields), and `new Foo(...)` constructor calls now produce a `calls` edge to the constructed type. Previously a record appeared only as its file node (degree 0) with no incoming edges, and body-level `new` usages were dropped because `object_creation_expression` wasn't a recognized call type and its callee lives in the `type` field rather than `name`. (#1373)
- Security fix: `.graphifyignore` and `.gitignore` are now **merged** per directory instead of `.graphifyignore` silently replacing that directory's `.gitignore`. Previously, adding a `.graphifyignore` (e.g. to exclude media) disabled the dir's `.gitignore` entirely, so a file excluded only by `.gitignore` — including neutrally-named secrets like `prod-dump.sql` or `customer-data.json` that the sensitive-file heuristic doesn't catch — got indexed into the graph, whose artifacts embed file contents and are routinely committed. `.gitignore` is read first and `.graphifyignore` last, so `.graphifyignore` patterns (including `!` negations) still win on conflict; adding one can only ever exclude more, never re-include a `.gitignore`-excluded file. (#1363)
## 0.8.41 (2026-06-17)
- Fix: OpenAI-compatible backends (`ollama`, `openai`, `deepseek`, `kimi`) now honour their configured `16384` output-token cap instead of silently falling back to `8192`. The dispatch read a `max_completion_tokens` config key that only `gemini` defines; the others set `max_tokens`, so their advertised cap was dead and deep-mode JSON truncated mid-string (recovered by the adaptive bisect, but noisy and slower). The dispatch now reads either key, and the `openai` config gained an explicit cap. `GRAPHIFY_MAX_OUTPUT_TOKENS` still overrides. (#1365)
- Fix: fuzzy dedup no longer over-merges distinct nodes in three cases. (1) Numbered/versioned siblings whose embedded digit runs differ as zero-padding-insensitive multisets (`ADR 0011` vs `ADR 0013`, `3.1 Product Goals` vs `1.1 Product Goals`, `40%+ …` vs `<20% …`) never merge. (2) `rationale`/`document` nodes are file-anchored like code (#1205's reasoning): near-identical docstring/heading boilerplate in parallel files no longer collapses across files, while same-file duplicates still merge. (3) Cross-file labels that share a long prefix but diverge in a distinguishing token (`testing-library jest-native` vs `react-native`) are scored on plain Jaro instead of Jaro-Winkler, so the leading-prefix bonus can no longer fabricate a merge; genuine cross-file duplicates still clear the bar on Jaro alone, and same-file near-duplicates keep Jaro-Winkler. Guards are mirrored into the `--dedup-llm` ambiguous-pair collection. (#1284 thanks @van4oza, #1243)
- Fix: Swift cross-file class relationships expressed through member calls and constructors now resolve to the receiver's real definition. A per-file type table (built from property/parameter declarations and constructor inference) types the receiver of `recv.method()` / `Type.staticMethod()` / `Singleton.shared.method()` / `self.prop.method()`, and property/field initializers (`let vm = VM()`) are now walked for constructor calls. Edges are emitted only when the receiver's type resolves to exactly one definition (preserving the #543/#1219 god-node guards) and are tagged `INFERRED`; the blanket member-call skip in the shared call pass is untouched (#1356).
- Fix: `/graphify <path> --update` now prunes stale nodes correctly. The update runbook called `build_merge(prune_sources=...)` without `root=`, so the absolute prune paths were never relativized to match the graph's relative `source_file` values — nothing was pruned and changed/deleted files left ghost nodes that compounded on every incremental run. The shared skill fragment now passes `root` (the native `graphify update` CLI was already correct) (#1361).
- Fix: `export obsidian` no longer writes an empty 32-byte `graph.canvas` on a populated graph. `to_canvas` built cards solely by iterating communities, so a graph with no community data (`--no-cluster` builds, or a missing analysis sidecar) produced the empty `{"nodes": [], "edges": []}` shell while the markdown notes rendered fine. It now falls back to one synthetic community covering every node (#1324).
- Fix: edges missing a `source_file` field (occasionally emitted by the semantic/LLM extractor, which `build` only normalized when the field was already present) are now backfilled from the edge's endpoint nodes in `build_from_json` and the `--no-cluster` raw-write path, so they no longer reach `graph.json` without a file reference or trip validation (#1279).
- Fix: every platform's query skill now ships **both** the vocab/IDF query-expansion step and the inline NetworkX fallback. Previously the two capabilities were split across `cli.md` / `cli-inline.md` so no platform got both — Claude had the superior expansion but no CLI-down fallback, while all other platforms had the fallback but the weaker raw-question matcher. The two fragments are merged into one unified `query` reference (and stub) shipped to all hosts; the `query_variant` enum and its coverage-audit exemption are removed (#1325; thanks @LeanderBlume).
- Fix: cross-file Java `implements`/`inherits`/`imports` edges no longer orphan onto bare "shadow" nodes when two packages define a same-named type. The referencing file's `import` statement now disambiguates by exact package (FQN) and re-points the edge to the real definition, dropping the orphan stub. Previously `_rewire_unique_stub_nodes` could only repair the globally-unique case, so same-named interfaces (common in large Java codebases — `Handler`, `Service`, interface+impl pairs) left the real definition isolated in its own community (#1318).
- Fix: Swift imports of the same module from multiple files now collapse to a single shared `type=module` node instead of N path-qualified duplicates. The import target is tagged `type=module` and exempted from id-disambiguation, so reverse traversal ("what imports CoreKit?") works; the `--no-cluster` writer also now dedupes nodes by id (and edges) to match the clustered `build_from_json` path. Builds on the v0.8.40 Swift-import fix (#1327, #1330; thanks @duncan-daydream).
## 0.8.40 (2026-06-16)
- Feat: custom OpenAI- and Anthropic-compatible endpoints via `OPENAI_BASE_URL`/`OPENAI_MODEL` and `ANTHROPIC_BASE_URL`/`ANTHROPIC_MODEL`. Point either backend at a self-hosted or proxy server (vLLM, llama.cpp, LM Studio, LiteLLM, gateways); defaults still resolve to `api.openai.com` / `api.anthropic.com`, and `GRAPHIFY_OPENAI_MODEL` keeps precedence over `OPENAI_MODEL`. Wired through both the extraction path (`_call_claude`) and community labeling (#1273).
- Feat: PowerShell `.psm1` modules are now indexed. `.psm1` was absent from `CODE_EXTENSIONS` and the extractor dispatch table, so modules — and their dependents — were silently missing from the graph; they parse cleanly with the existing PowerShell grammar (#1315). (`.psd1` manifests and `Import-Module` / dot-source import edges remain a follow-up.)
- Fix: Swift `import` edges are no longer silently dropped. `_import_swift` emitted an edge to a bare module id with no backing node, so `build.py` pruned 100% of Swift imports. The target module node is now synthesized (new opt-in `LanguageConfig.synthesize_import_module_nodes`) so the edge survives the build (#1327).
- Fix: `--no-cluster` and incremental `graphify update` no longer accumulate duplicate edges. These paths bypass the NetworkX `DiGraph` that collapses parallel edges, so repeated `update` grew the edge count every run and counts diverged across build modes. Edges are now deduped by `(source, target, relation)` before writing — deterministic and idempotent; the no-cluster rebuild log now reports the written (deduped) edge count instead of the raw pre-merge count (#1317).
- Perf: `save_manifest` file hashing parallelized with a `ThreadPoolExecutor` (#1295).
- Perf: `_walk_js_tree` converted from a recursive generator to an iterative walk, reducing overhead on large JS/TS trees (#1294).
- Feat: JS/TS AST now extracts function symbols defined via `this.X = () => {}` / `this.X = function(){}` (constructor-assigned methods), `exports.X = fn` / `module.exports.X = fn`, `Foo.prototype.X = fn`, class arrow/function fields (`class C { onClick = (e) => {} }`), and `const f = function(){}` function expressions. Previously only top-level `function` declarations, top-level `const x = () =>` arrows, classes, and method shorthand were captured, so the majority of callable symbols in constructor-style and CommonJS codebases (DAOs, route handlers, services) never became nodes and could not be call-edge endpoints. Arbitrary `obj.x = fn` is deliberately not captured, preserving the #1077 phantom-god-node guard (#1322).
- Fix: `graphify query`, `graphify explain`, and MCP `query_graph`/`get_node` now show the human-readable community name (e.g. "FlashAttention Paper") instead of a blank or numeric ID after running `cluster-only`. `to_json` now accepts `community_labels` and embeds `community_name` on each node; read paths fall back to the numeric `community` field for backward compatibility with old graphs (#1305).
- Fix: `graphify-mcp` and `python -m graphify.serve` now accept `--graph <path>` as an alias for the positional argument, consistent with every other graphify subcommand. Previously `--graph` raised "unrecognized arguments" (#1304).
- CI: bandit (MEDIUM+ severity) and pip-audit security scans added as a non-blocking `security-scan` job. Both run with `continue-on-error: true` so they never break CI — advisory signal only, with the intent to remove the gate once pre-existing findings are triaged.
- Docs: RFC for file-level node summaries added (`docs/node-summaries-rfc.md`). Proposes inline `graph.json` attribute vs sidecar storage options with pros/cons, phased implementation plan, and open questions for maintainer decision.
- Fix: AST extraction no longer crashes on Windows machines with >61 logical cores. `ProcessPoolExecutor` on Windows is hard-capped at 61 workers via `WaitForMultipleObjects`; the clamp now applies to all three input paths (auto-compute, `GRAPHIFY_MAX_WORKERS`, `--max-workers`) (#1298).
- Fix: ghost-merge skips ambiguous `(basename, label)` collisions where two AST nodes share the same key. When same-named symbols appear in same-named files across different directories (e.g. two `render()` in two `index.ts`), the previous last-writer-wins produced an arbitrary canonical node and mis-pointed all edges. Ambiguous keys are now tracked and skipped (#1257).
- Fix: startup no longer crashes on unreadable `.graphify_version` files. On restricted-permission installs or network mounts, `.exists()` / `.read_text()` raised `PermissionError` and crashed every `graphify query/explain/path` call. All three FS probes now wrapped in `try/except OSError: return` (#1299).
- Fix: `prs.py` claude-cli backend resolves `claude.cmd` on Windows. The `_call_llm` and `_call_claude_cli` extraction paths were already fixed; `prs.py` had the same bare `["claude", ...]` subprocess call that fails on Windows npm installs with WinError 2 (#1288).
## 0.8.39 (2026-06-12)
- Perf: O(n²)→O(n) LSH neighbor lookup in `deduplicate_entities`. The inner scan `next(n for n in candidates if n["id"]==neighbor_id)` was O(n) per neighbor; replaced with a `candidates_by_id` dict built once per pass. Also adds a `norm_cache` to avoid re-normalising labels on every comparison.
- Fix: `graphify merge-chunks` summary now prints the node count instead of the raw list object. `global_graph.py` printed `merged['nodes']` (the list) instead of `len(merged['nodes'])`.
- Fix: manifest data-loss on corrupt `~/.graphify/manifest.json`. A parse error previously triggered `except Exception: pass`, silently returning an empty manifest and overwriting the file — wiping all tracked repos. The corrupt file is now renamed to a timestamped `.corrupt.<ts>` backup with a stderr warning before starting fresh.
- Fix: tree-sitter grammar packages now have pinned upper-bound version ranges in `pyproject.toml`. Grammar packages routinely break node-type and field APIs across minor bumps; ceilings prevent silent breakage on future upgrades.
- Feat: FalkorDB export backend. `graphify export falkordb --push redis://localhost:6379` pushes the graph to a FalkorDB instance. Optional dep (`uv tool install "graphifyy[falkordb]"`); lazy import; idempotent (MERGE semantics); Cypher injection guarded.
- Fix: `affected` and `graphify query` now handle graph files that use `"edges"` as the top-level key instead of `"links"`. Graphs produced by native `graphify extract` on some corpus layouts used `"edges"`; loading them in `affected.py` raised `KeyError: 'links'`. Normalised using the same established pattern already in `__main__.py` and `serve.py`.
- Fix: a single `!` negation rule in `.graphifyignore` no longer disables all directory pruning. Previously any negation pattern caused `collect_files` to descend every ignored directory to look for re-included files. Since gitignore semantics cannot rescue files beneath an excluded parent, this descent was always wasted — the per-file filter still excluded them. Pruning now proceeds unconditionally; only the final per-file `_is_ignored` check is consulted for negation.
- Feat: `--model` flag added to `graphify label-communities` and `graphify cluster-only`. Routes through `generate_community_labels` → `label_communities` → `_call_llm`; defaults to `None` (keeps existing backend default). Also fixes a latent arg-parsing bug where `--backend gemini` (space-separated) was mis-parsed as the positional path argument.
- Docs: Persian (فارسی) README translation added (`docs/translations/README.fa-IR.md`).
## 0.8.38 (2026-06-11)
- Fix: LLM-generated `calls` edges now have correct direction. The extraction prompt previously never stated that `source` = caller and `target` = callee; the LLM systematically emitted callee→caller edges. An explicit direction rule was added to the prompt. Separately, ghost-node merge was extended to collapse LLM duplicate nodes (bare-stem IDs) onto AST canonical nodes (parent-qualified IDs) even when the LLM node carries a `source_location` — the old check only caught `source_location=None` ghosts. Post-fix annotation: `calls` precision 100% (n=6), overall INFERRED precision 94% (n=16).
- Fix: default imports/exports now produce symbol-level edges. JS/TS symbol resolution only handled named imports, so a `export default class Foo` imported as `import Foo from './foo'` got just a file→file `imports_from` edge — the class node received no incoming symbol edge. On codebases that default-export most classes (NestJS services/helpers/models, etc.) this left those symbols looking like isolated leaf nodes and made `graphify affected "<Class>"` / `explain` report no callers. Default imports are now recorded with `imported_name="default"`, `export default <class|function|identifier>` registers a `"default"` export, and the existing resolver wires the `imports` edge (and resolves calls through the local binding, even when renamed). Anonymous defaults (`export default class {}`) remain file-level only.
- Fix: tsconfig `paths` aliases now resolved relative to `baseUrl`. Previously all `@/*` → `src/*` aliases were resolved from the config file's directory regardless of `baseUrl`, breaking path alias import resolution for NestJS, monorepo, and similar layouts that set `baseUrl: "./src"`.
- Fix: ghost-merge skips ambiguous `(basename, label)` keys where multiple AST nodes share the same pair. Previously the last-writer-wins pass silently mis-merged one of two same-named symbols in different files (e.g. two `render` functions across separate modules), re-pointing edges to the wrong canonical node.
- Fix: `resolve_seed` now matches bare query terms against callable-decorated node labels. A query for `"render"` failed to seed nodes whose label was stored as `".render()"` because the string comparison was exact. Bare names are now tried against stripped labels as a fallback after exact and prefix matches.
- Fix: AST cache is now namespaced by graphify version. Stale AST cache entries from a previous release no longer silently produce wrong extraction output after an upgrade — each version writes to its own subdirectory under `graphify-out/cache/ast/<version>/`. Semantic cache is deliberately unversioned (LLM calls are expensive to re-run).
- Fix: global-graph edges are now rewired to deduplicated external nodes. When two repos shared an external dependency node (e.g. both reference `requests`), one copy was pruned but edges still pointed to the removed node ID, creating dangling references. Edges are now remapped through the dedup remap table before insertion.
- Fix: dedup pass 2 now picks the winner only from the verified `(node, neighbor)` pair. The previous code unioned both normalised-label groups before calling `_pick_winner`, allowing an unrelated same-named node from a different file to be dragged into the merge and supplant the correct winner.
- Fix: extraction cache is anchored at the `--out` directory root instead of leaking a `graphify-out/` into the scanned project. Using `graphify extract ./src --out /tmp/out` previously wrote cache files into `./src/graphify-out/cache/` alongside source files. Cache now writes exclusively under the `--out` path.
- Fix: `collect_files` rewritten as a single pruned `os.walk` instead of one `rglob` per extension. On large repos this eliminated ~85 redundant filesystem traversals; noise directories (`node_modules`, `.git`, `__pycache__`, etc.) are now pruned before descent, preventing those subtrees from being scanned at all.
- Fix: frontmatter delimiter detection now requires a whole `---` line (regex `^---[ \t]*\r?$`). Thematic break lines (`----`) and YAML documents that open with `--- title: foo` were incorrectly parsed as frontmatter delimiters, causing cache hash instability on Markdown files with those constructs.
- Fix: `claude-cli` backend now spawns `claude.cmd` on Windows headless installs. `npm`-installed Claude Code ships a `.cmd` shim on Windows; `CreateProcess` cannot run it without the explicit extension. `shutil.which("claude.cmd")` is now tried first on win32, mirroring the fix already applied to the extraction path. `CREATE_NO_WINDOW` flag added to both subprocess spawn sites to prevent console windows flashing during headless runs.
- Fix: `claude-cli` backend handles JSON-array envelope from Claude Code CLI ≥ 2.1. Older CLI versions returned a single JSON object; 2.1+ wraps the response in a streaming array of events. The envelope parser now accepts both shapes, preferring the last `{"type":"result"}` event from an array.
- Feat: Cargo workspace dependency extraction. `graphify extract ./my-workspace --cargo` introspects `Cargo.toml` files across a Rust workspace and emits `crate:<name>` nodes with `crate_depends_on` edges for workspace-internal dependencies. Registry dependencies are excluded. Handles virtual workspaces, root-package workspaces, glob members, and `{workspace = true}` inherited deps.
- Fix: SystemVerilog class-level extraction improved. Classes, interfaces, enums, parameters, and their inheritance/implementation relationships are now extracted correctly from `.sv`/`.svh` files. Dart `with MyMixin` clauses now emit `mixes_in` edges (was incorrectly `implements`), consistent with PHP and Scala.
- Docs: README grammar count updated from 28 to 36, reflecting all currently supported tree-sitter language grammars.
## 0.8.37 (2026-06-10)
- Security: SSRF guard rewritten to eliminate thread-safety race. The global `socket.getaddrinfo` monkey-patch is replaced with per-connection `_SSRFGuardedHTTPConnection`/`_SSRFGuardedHTTPSConnection` subclasses that resolve DNS once, validate the IP, and connect to that exact address — closing both the concurrent-thread race window and the underlying TOCTOU gap. No global state is mutated, so sibling threads (MCP server, PR triage pool) are unaffected.
- Security: Prompt injection mitigation for LLM semantic extraction. Untrusted source file content is now wrapped in `<untrusted_source path="..." sha256="...">` XML delimiters; jailbreak sentinel tokens (`<|im_start|>`, `[INST]`, `<<SYS>>`, forged closing tags) are neutralised with a zero-width space; the extraction system prompt includes an explicit SECURITY block stating that content inside the wrapper is inert data.
- Fix: `export obsidian` and `export canvas` no longer crash with `KeyError` when a community contains a node ID absent from the graph (stale community index, merge artifacts). Dangling members are silently skipped.
- Fix: `--update` on macOS no longer re-extracts all Office files on every run. `convert_office_file()` now NFC-normalises the source path before hashing the sidecar filename, so NFD paths returned by `os.walk` (HFS+/APFS) produce the same sidecar as NFC-constructed paths. An early-return when the sidecar exists prevents mtime bumps causing spurious re-detection.
- Fix: Data `.json` files no longer explode into hundreds of orphan key-nodes. The JSON extractor now only processes config/manifest JSON (detected by filename — `package.json`, `tsconfig.json`, `.eslintrc.json`, `deno.json`, etc. — or by top-level keys such as `dependencies`, `extends`, `$ref`, `compilerOptions`). Data JSON (top-level arrays, generic key/value files) is skipped by the AST pass and left for the LLM semantic pass.
- Fix: OpenAI-compatible backends no longer send `temperature=0` to reasoning models. `_resolve_temperature()` auto-detects o1/o3/o4 and gpt-5 series and omits temperature from the request. Override with `GRAPHIFY_LLM_TEMPERATURE=<value>` (or `none` to omit explicitly for any model).
- Fix: EDR / corporate Windows hang eliminated. `datasketch` (which transitively imports `scipy` → `numpy.testing` → `platform.machine()` subprocess at import time) is replaced by a self-contained pure-numpy MinHash/MinHashLSH implementation with byte-identical hash math. Removes `datasketch` and `scipy` from the dependency tree.
- Perf: `detect()` ignore-pattern checks memoized per scan. Each ancestor directory is now evaluated once across all sibling files, eliminating ~42M redundant `fnmatch` calls on large repos (~34% whole-run speedup on 2k-file corpora).
- Fix: `dedup.py` label-based merge passes now skip code nodes entirely. Distinct same-named symbols in different files (e.g. two `Config` classes) were being merged by the exact-label and MinHash/LSH passes. Code nodes are now deduplicated by ID only, which is correct.
- Feat: `GRAPHIFY_MAX_GRAPH_BYTES` env var to override the 512 MiB `graph.json` size cap. Accepts plain bytes, `<N>MB`, or `<N>GB`. The cap error message now cites this env var. `graphify export html` auto-falls back to the community-aggregation view when over cap instead of hard-failing.
- Feat: `CLAUDE.md` template now uses mandatory language for the graphify-first rule — "MANDATORY: Before using Read/Grep/Glob/Bash to explore the codebase, you MUST run graphify first" — and explicitly requires forwarding the rule to subagent prompts. PreToolUse hook message hardened to match.
- CI: Release workflow added. Every GitHub release now ships `graphify-self-graph.tar.gz` as a downloadable asset — `graph.json` + `graph.html` + `GRAPH_REPORT.md` from running Graphify on its own source. Open `graph.html` locally with no install required to see what Graphify produces.
## 0.8.36 (2026-06-08)
- Feat: `extra_body` field in `providers.json` forwarded to OpenAI-compat calls at extraction and labeling. Lets vLLM/Qwen3/Llama endpoints pass model-specific request shapes (e.g. `{"chat_template_kwargs": {"enable_thinking": false}}`). Explicit `extra_body` also bypasses Ollama `num_ctx` auto-derive. Thanks to @EirikWolf (#1197).
- Feat: `label_communities` multi-batch for 16k-context models. Chunks of 100 communities per call (configurable `batch_size=`); `max_communities` defaults to `None` (label all); partial batch failures no longer drop the whole pass. Thanks to @EirikWolf (#1197).
- Feat: `.slnx` Visual Studio solution file support. Extracts `contains` (project references) and `imports` (build dependencies) edges from the modern XML solution format (VS 2022 17.13+). Thanks to @bakgaard (#1189).
- Feat: `graphify-mcp` console script. MCP stdio server now directly invocable as `graphify-mcp` from `uv tool install` / `pipx`. Thanks to @jr2804 (#1190).
- Fix: `label_communities` token budget raised and `GRAPHIFY_MAX_OUTPUT_TOKENS` now honoured. Hardcoded `min(40+16n, 4096)` undershooted (~16 tok/community); raised to `min(64+24n, 8192)` and wrapped in `_resolve_max_tokens()` (#1200).
- Fix: `find_import_cycles` no longer hangs on large graphs. `nx.simple_cycles()` now receives `length_bound=max_cycle_length`, pruning during enumeration rather than post-filtering — drops from never-returns to ~0.1s on dense graphs (#1196).
- Fix: fuzzy dedup no longer merges prefix-extension symbol pairs. `getActiveSession`/`getActiveSessions`, `parseConfig`/`parseConfigFile` etc. scored ~98-99 JW and were auto-merged. A prefix-extension guard now prevents merge when one normalised label is a strict prefix of the other, in both Pass 2 and the LLM tiebreaker (#1201).
- Fix: `_norm`, `_norm_label`, `_strip_diacritics` guard against `None` node labels, preventing `TypeError` crash on corpora with explicit `null` label fields (#1194). Thanks to @freiit (#1195).
- Fix: skill frontmatter `trigger:` field removed from all 14 skill variants — not part of Agent Skills spec, flagged by `agentskills validate` CI (#1180).
## 0.8.35 (2026-06-07)
- Feat: CodeBuddy platform support. `graphify codebuddy install` installs the graphify skill to `~/.codebuddy/skills/graphify/SKILL.md`, writes a `CODEBUDDY.md` always-on section, and registers Bash + Read|Glob PreToolUse hooks in `.codebuddy/settings.json` that nudge the agent toward `graphify query` instead of grepping raw files when a graph exists. `graphify install --platform codebuddy` and `graphify codebuddy uninstall` also supported. Thanks to @studyzy (#1136).
- Fix: `graphify --update` no longer destructively collapses distinct same-named symbols across files. The skill's `--update` merge now passes re-extracted (changed) files to `prune_sources` alongside deleted files, so old nodes for changed files are pruned before fresh AST is inserted — no fuzzy reconciliation needed. Separately, `dedup.py` Pass 1 now skips nodes with an empty `source_file` so label-only merging across no-source-file nodes is prevented. The anti-shrink guard message now names fuzzy dedup as a possible cause rather than only blaming missing chunk files (#1178).
## 0.8.34 (2026-06-07)
- Feat: Streamable HTTP transport for the MCP server. `python -m graphify.serve graph.json --transport http --port 8080 --api-key $SECRET` serves the graph over the MCP Streamable HTTP transport (spec 2025-03-26) so a single shared process can serve the whole team. Flags: `--host`, `--port`, `--api-key` (env `GRAPHIFY_API_KEY`), `--path`, `--json-response`, `--stateless`, `--session-timeout`. Docker image included. stdio remains the default (#1143).
- Feat: Salesforce Apex extractor. `.cls` and `.trigger` files are now AST-extracted via regex (no tree-sitter grammar exists for Apex). Extracts classes, interfaces, enums, methods, triggers, and SOQL/DML edges (#1159).
- Feat: Azure OpenAI Service backend. `--backend azure` reads `AZURE_OPENAI_API_KEY` + `AZURE_OPENAI_ENDPOINT` and auto-detects both. Uses the existing `openai` package — no new dependency (#1107).
- Feat: live PostgreSQL introspection. `graphify extract --postgres "postgresql://..."` connects directly to a running database and maps tables, views, routines, and FK relations via `information_schema` in a `SERIALIZABLE READ ONLY` transaction. New `graphify[postgres]` extra (psycopg3). Credentials are sanitized from error messages (#1103).
- Feat: vision and PDF support in headless extract. Images now route through per-backend vision payloads (base64/data-URI for claude/openai, file path for claude-cli, bytes for bedrock) instead of producing garbage binary data. Non-vision backends get a text reference via `_strip_pixels`. PDFs reuse pypdf. 5MB cap, 20-image chunk limit (#1110).
- Fix: `graphify update` now prunes symbols removed from files that still exist on disk. Previously, deleting a function left a ghost node in the graph until the source file itself was deleted. Every AST node is now stamped with `_origin="ast"`; on a full rebuild any stamped node absent from the fresh output is dropped (#1118).
- Fix: `graphify path` and `shortest_path` now fire the exact-match bonus for multi-word queries. The per-token comparison never equalled a full multi-word label, so the exact bonus was silently skipped for queries like `"AuthService"` when the label contained punctuation or spaces. The full normalized query is now compared alongside each token (#1165).
- Fix: `_is_sensitive` no longer flags topic-mentioning filenames as secrets. `token-economics-of-recall.md` and `password-policy-discussion.md` were silently dropped. Generic keywords (token/secret/password) now only fire when the keyword ends the filename stem or the stem is ≤2 words; specific patterns (`.env`, `.pem`, `id_rsa`, etc.) remain unconditional (#1169).
- Fix: git hooks no longer use `nohup` to background the rebuild. Git for Windows' MSYS shell has no `nohup`, causing the post-commit/post-checkout hook to fail silently and the graph to go stale. Replaced with a cross-platform Python launcher using `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` on Windows and `start_new_session=True` on POSIX (#1161 / #1170).
- Fix: post-commit and post-checkout hooks now respect an existing `.graphify_root`. A scoped build (`graphify src/`) was silently expanded to the full repo on the next commit because the hook hardcoded `Path('.')`. The hook body now reads `graphify-out/.graphify_root` first (#1173).
- Fix: `graphify affected` now forces a directed graph on load, matching the identical fix already applied in `serve.py` and `__main__.py`. On undirected graphs (`"directed": false` in graph.json) the traversal was direction-blind — missing true callers and reporting callees as affected (#1174).
- Fix: Step 9 skill cleanup no longer aborts under fish/zsh on pure-code corpora. The `rm -f ... .graphify_chunk_*.json` glob errored with "no matches found" when no chunk files existed, leaving other temp files on disk. Split into `rm -f` for fixed filenames and `find -maxdepth 1 -delete` for the chunk glob (#1172).
- Fix: `detect_incremental` no longer crashes on schema-drifted manifest files. A dict-valued `mtime` entry (from an older richer schema) is now coerced to `None` and the file is treated as new rather than raising a comparison error (#1163).
- Fix: numpy pinned to `>=2.0` only on Python 3.13+ in the `svg` and `all` extras. numpy 1.26.4 ships no `cp313` wheel so `uv sync` fell back to a source build requiring a C compiler (#1153 / #1154).
- Fix: Codex platform skill now installs to `.codex/skills/graphify/` (was `.agents/skills/graphify/`), aligning with where the hook already lives (#1160).
## 0.8.33 (2026-06-06)
- Feat: FalkorDB export backend — sibling to Neo4j, selected via `graphify export falkordb [--push falkordb://localhost:6379]`. FalkorDB is OpenCypher-compatible, so the MERGE/SET upsert queries match the Neo4j path; auth is optional and the target graph defaults to `graphify`. Install with `uv tool install "graphifyy[falkordb]"` (#1175).
- Feat: install banner — `graphify install` now prints an amber knowledge-graph brain in the terminal (TTY-only, silent in CI/pipes, never raises).
- Fix: Python `from pkg import submod` package-form imports now resolve to a file-level `imports_from` edge to the submodule file when it exists on disk. Previously these imports produced zero edges, leaving test files as disconnected islands in the graph (up to 66% of test nodes in some corpora). The fix lives in the symbol-resolution post-pass which has filesystem access (#1146).
- Fix: builtin type-annotation nodes (`str`, `int`, `bool`, `float`, `bytes`, `MagicMock`, `Mock`, `AsyncMock`, etc.) no longer appear as graph nodes or accumulate edges. They were being created via the annotation walker whenever used as parameter or return types, inflating degree counts ~25% and displacing real abstractions from god-node rankings. A new `_PYTHON_ANNOTATION_NOISE` filter suppresses them at extraction time; `god_nodes` also filters them as a defense for pre-existing graphs (#1147).
- Fix: AST/semantic ghost-duplicate nodes are now auto-merged at build time. When AST and semantic extraction produce different IDs for the same symbol (one with `source_location=L<n>`, one without), `build_from_json` detects the pair by `(source_file basename, label)` and collapses the semantic ghost into the AST node, re-pointing all edges. Graphs built before this release can be cleaned up with `graphify extract . --force` (#1145).
## 0.8.32 (2026-06-05)
- Feat: Terraform/HCL support. `.tf`, `.tfvars`, and `.hcl` files are now AST-extracted via `tree-sitter-hcl` into a structured infrastructure dependency graph. Nodes: resources, data sources, modules, variables, outputs, providers, and locals. Edges: `contains`, `references` (interpolation), and `depends_on`. Node IDs are directory-scoped for cross-file resolution. Requires `uv tool install "graphifyy[terraform]"` (#1129).
- Fix: `graphify extract` no longer requires an LLM API key for code-only corpora. Backend resolution is now deferred until after file detection — a corpus with only code files (pure tree-sitter AST, zero LLM calls) runs fully offline. The key is only enforced when docs, PDFs, or images are present, or when `--dedup-llm` is passed (#1122).
- Fix: `graphify kiro install` now correctly installs the `references/` sidecar and `.graphify_version` stamp. The install was using a bare `write_text` that bypassed the shared helper, shipping `SKILL.md` with 8 dead `references/*.md` pointers. Re-run `graphify kiro install` to pick up the fix (#1142).
- Fix: `GRAPHIFY_API_TIMEOUT` now applies to `claude-cli` subprocess and Anthropic SDK backend, not just the HTTP client. Both subprocess paths previously hardcoded `timeout=600` and ignored the env var and `--api-timeout` flag (#1112).
- Build: version floors added for `networkx>=3.4`, `datasketch>=1.6`, and `rapidfuzz>=3.0` to prevent silent breakage from old installs resolving incompatible versions.
## 0.8.31 (2026-06-03)
- Fix: `graphify hook install` now embeds the current interpreter (`sys.executable`) directly into the generated hook scripts. Previously, uv tool and pipx installs silently no-oped on git commit in GUI clients and CI runners where `~/.local/bin` is not on PATH — the hook could not find the graphify launcher, fell through all detection probes, and exited 0 without rebuilding. The embedded path is sanitized through a filesystem-safe allowlist before substitution. If you already have hooks installed, re-run `graphify hook install` to pick up the fix (#1127).
- Fix: hook scripts now also probe `graphify-out/.graphify_python` as a fallback interpreter source, covering Windows/Git Bash installs where the launcher is a binary with no parseable shebang, and the case where the pinned path goes stale after a reinstall.
- Security: hook script hardening — the `_PINNED=` assignment uses single quotes to prevent shell injection from a path containing metacharacters; `nohup "$GRAPHIFY_PYTHON" -c` is properly quoted to handle spaces; the fallback emits a loud stderr diagnostic instead of a bare silent `exit 0`.
- Feat: query logging. Every `graphify query`, `graphify path`, `graphify explain`, and MCP `query_graph` call is now appended to `~/.cache/graphify-queries.log` in JSON Lines format (timestamp, kind, question, corpus path, nodes returned, result size, duration). Full subgraph responses are not stored by default. Control with `GRAPHIFY_QUERY_LOG` (path override), `GRAPHIFY_QUERY_LOG_DISABLE=1` (opt out), `GRAPHIFY_QUERY_LOG_RESPONSES=1` (store full response text) (#1128).
## 0.8.30 (2026-06-03)
- Fix: `graphify install --project --platform antigravity` now writes Antigravity's always-on layer (`.agents/rules/graphify.md` + `.agents/workflows/graphify.md`), not just the skill. The project-scoped path went through the skill-only branch and skipped them, even though the project uninstall removes them.
- Feat: close the Read-tool graph bypass. The `PreToolUse` nudge previously only fired on Bash search (`grep`/`rg`/`find`); an agent answering a question by reading many source files through the native `Read` tool (or `Glob`) slipped past it. A new `Read|Glob` hook nudges toward `graphify query` when `graphify-out/graph.json` exists, only for a source/doc file outside `graphify-out/`, and never blocks (#1114).
- Feat: add an `anthropic` optional extra (and include it in `[all]`) so the `claude` backend is installable like every other one: `uv tool install "graphifyy[anthropic]"`. Previously it was the only backend with no extra, so a user with `ANTHROPIC_API_KEY` set could not satisfy it without `--with anthropic`. The backend package-missing errors now point at `uv tool install "graphifyy[<extra>]"` (the isolated-venv path) rather than only `pip install`.
## 0.8.29 (2026-06-02)
- Feat: progressive-disclosure skill files. The per-host `SKILL.md` is now a lean core (~615 lines, down from the ~1156-line monolith, about 47% less always-loaded context) that carries the full default code-build pipeline inline and links to an on-demand `references/` sidecar (extraction-spec, query, update, exports, transcribe, github-and-merge, add-watch, hooks); an agent reads a reference only when that path is actually taken, so a normal build needs none. 18 hosts go progressive (claude, codex, opencode, kilo, copilot, claw, droid, trae, trae-cn, hermes, kiro, pi, antigravity, antigravity-windows, windows, kimi, amp, gemini); aider and devin stay monolithic by design. All 15 skill bodies + sidecars are generated from one source under `tools/skillgen/`, with CI guards (`--check`, `--audit-coverage`, `--monolith-roundtrip`, `--always-on-roundtrip`) proving the references are byte-identical slices of the old monolith so nothing is lost (#1121).
- Fix: `graphify install --platform gemini` shipped a `SKILL.md` with 8 dead `references/` pointers. gemini installs claude's lean progressive core but the installer never copied claude's references sidecar; it now does, so every on-demand reference resolves (regression from the progressive-disclosure split).
- Security (F1): a project-local `./.graphify/providers.json` (which travels with a cloned or shared repo) is no longer loaded automatically, since a custom provider's `base_url` is where your corpus and API key are sent. Set `GRAPHIFY_ALLOW_LOCAL_PROVIDERS=1` to opt in; the user's own `~/.graphify/providers.json` is still trusted. Non-http(s) `base_url`s are rejected on load and on `provider add`, and plaintext-http egress warns. **Behavior change:** if you relied on an auto-loaded project-local providers file, set the opt-in env var.
- Security (F2): untrusted office/PDF files are screened before parsing (on-disk size cap, plus a bounded streaming-decompression ceiling for `.docx`/`.xlsx` zip containers) so a zip-bomb in a scanned corpus can no longer exhaust memory.
- Security (F3): `OLLAMA_BASE_URL` pointing at a link-local or cloud-metadata address (`169.254.x`, `metadata.google.*`, or any host that resolves to one) now fails closed with a clean error instead of sending the corpus there. Trusted LAN hosts still warn-and-allow.
- Security (F5): the Fortran C-preprocessor step passes an absolute path so an attacker-named corpus file cannot be interpreted as a `cpp` option.
## 0.8.28 (2026-06-01)
- Feat: Kilo Code support — `graphify install --platform kilo` installs a native skill (`~/.config/kilo/skills/graphify/SKILL.md`) and `/graphify` command, plus a `.kilo` `tool.execute.before` plugin (mirroring the OpenCode integration). Existing `.kilo/kilo.jsonc` config is read but never rewritten — plugin registration goes to `kilo.json` so user comments are preserved (#512)
- Feat: modernized Dart extractor — comment stripping, `part of` redirection, nested-generic-aware `extends`/`with`/`implements` parsing, generic type-argument mapping, and generic call detection (#1098)
- Fix: `uv tool install graphifyy` / `pip install graphifyy` no longer fails to build on Linux/macOS — `tree-sitter-dm` (BYOND DreamMaker) ships only a Windows wheel, so on other platforms it compiled from source and aborted the entire install when a C toolchain or `python3-dev` headers were missing. It is now an optional extra (`graphifyy[dm]`, also in `[all]`) instead of a core dependency, so the default install needs no compiler (#1104).
- **Upgrade note:** DreamMaker `.dm`/`.dme` users must reinstall with `graphifyy[dm]` (or `[all]`) to keep AST extraction — on `uv tool upgrade` the now-optional grammar is removed. `.dmi`/`.dmm`/`.dmf` parsing is unaffected (no tree-sitter dependency).
- Fix: community IDs are now assigned by a total order (`(-size, sorted node IDs)`) so an identical grouping always gets identical IDs across runs — previously the equal-sized small communities that dominate a sparse graph were numbered by the partitioner's (not seed-stable) enumeration order, making a per-node community diff report large spurious "churn" even though the actual grouping was reproducible (#1090 follow-up)
- Fix: `graphify amp install` now writes the skill where Amp actually looks for it. It was landing in `.amp/skills/graphify` (project) and `~/.amp/skills/graphify` (user), neither of which Amp searches, so the skill never loaded. User-scope installs now go to `~/.config/agents/skills/graphify` and project installs to `.agents/skills/graphify`, and a stale `~/.amp/skills/graphify` from an older install is cleaned up on the next run.
## 0.8.27 (2026-05-31)
- Feat: standalone CLI now auto-names communities with the configured backend instead of leaving `Community N` placeholders — community labeling was previously an agent-only step (skill.md Step 5), so bare-CLI runs never got semantic names; `cluster-only` now auto-labels when no `.graphify_labels.json` exists, new `graphify label <path>` subcommand (re)generates names on demand, `--no-label` opts out, `--backend=<name>` overrides auto-detection; one batched LLM call with per-community placeholder fallback and graceful degradation on missing backend/API error; works with all built-in and custom OpenAI-compatible backends (#1097)
- Fix: AST file-level node IDs now match the skill.md `{parent_dir}_{stem}` spec — they were derived from the full relative path plus extension (`match_script_pipeline_step_py`) while semantic subagents use `script_pipeline_step`, splitting every file into two disconnected ghost nodes; fixed at the single relative-path remap chokepoint so file nodes and all import/dependency edge endpoints (Python, TS, Lua, C, bash) convert together (#1033)
- Fix: symbol-level node IDs for root-level files now match the spec too — the #1033 remap relativized file nodes but symbols still embedded the absolute parent-dir name (`<rootdir>_main_run` vs spec `main_run`), splitting every top-level file's symbols into AST/semantic ghost pairs; the remap now canonicalizes symbol stems and `raw_calls` caller IDs, gated by `source_file` (#1096)
- Fix: TypeScript `interface A extends B` and same-file `class X extends Y` now produce `inherits`/`implements` edges — the walker only inspected `class_heritage` (missing the interface `extends_type_clause` node) and the resolver only consulted the import table (missing same-file bases); both gaps closed (#1095)
- Fix: `graphify export obsidian` no longer crashes with `OSError ENAMETOOLONG` on long node labels — `to_obsidian`/`to_canvas` now cap filenames on UTF-8 bytes (not chars, so multibyte/CJK labels are handled) with an 8-char hash suffix on truncation to keep distinct long-prefix labels from colliding; also fixes the previously-uncapped `_COMMUNITY_` notes (#1094)
- Fix: `graph.json` is now deterministic across runs — `detect()` sorts file traversal lexicographically (`os.walk` order is filesystem-dependent), which had made first-writer-wins node-ID decisions and Leiden community counts vary between identical runs (#1090)
- Fix: Windows consoles no longer crash with `UnicodeEncodeError` on non-UTF-8 code pages — `main()` reconfigures stdout/stderr to UTF-8 at startup and `→`/`—` in print statements replaced with ASCII (#992)
## 0.8.26 (2026-05-30)
- Feat: `find_import_cycles(G)` in `analyze.py` detects file-level circular import dependencies — collapses symbol graph to file-level directed import graph, finds simple cycles via Johnson's algorithm, deduplicates rotations, renders `## Import Cycles` section in `GRAPH_REPORT.md` (#961)
- Feat: custom LLM provider registry — `graphify provider add/list/show/remove` registers any OpenAI-compatible endpoint (NVIDIA NIM, vLLM, OpenRouter, Together, LiteLLM) via `~/.graphify/providers.json`; custom providers auto-detected after built-ins in `detect_backend()` priority (#1084)
- Fix: `extract_files_direct()` no longer silently defaults to kimi (Moonshot AI) — `backend=None` now calls `detect_backend()` and raises a clear `ValueError` if no key is configured, matching CLI behavior; README Privacy section updated with data-residency notes (#1086)
- Fix: `pnpm-workspace.yaml` with `packages: - '.'` no longer crashes with `IndexError: tuple index out of range` on Python 3.10 — `Path.glob('.')` replaced with `[root]` guard in `_load_workspace_packages`; `GRAPHIFY_DEBUG=1` env var added to `_safe_extract` for full traceback on extraction errors (#1083)
- Fix: anchored `.graphifyignore` patterns (leading `/`) no longer match the same directory name anywhere in the tree — `_matches()` in both `_is_ignored` and `_is_included` now gates basename/segment shortcuts on `not anchored`; anchored patterns do exact anchor-relative path match only (#1087)
- Docs: Filipino (fil-PH) README translation added (#1080)
## 0.8.25 (2026-05-29)
- Fix: JS/TS `const`/`let` inside arrow-function callbacks no longer emit phantom god-nodes — scope guard restricts `_js_extra_walk` node emission to program-level declarations only; applies uniformly to JS, TS, and TSX (#1077)
- Fix: fenced code blocks in Markdown no longer emit orphan `codeblock_N` nodes — they had only `contains` edges and no semantic meaning; fence-toggle still prevents inner content from being mis-parsed as headings (#1077)
- Fix: Lua `require("pkg.sub")` now resolves to the correct file node ID — dots converted to path separators, probes filesystem for `.lua`/`.luau`/`init.lua` variants up the directory tree (#1075)
- Fix: Windows `claude-cli` backend no longer raises `WinError 2` — prefers `claude.cmd` over bare `claude` to avoid PATHEXT `.ps1` resolution failure (#1072)
- Fix: post-commit hook no longer silently drops `changed_paths` when another rebuild holds the lock — lock-losers queue paths to a pending file; the lock-holder drains and merges on acquire (#1059)
- Fix: `graphify install antigravity` global install now writes to `~/.gemini/config/skills/` (per Antigravity docs) instead of the wrong `~/.agents/`; uninstall, version-stamp refresh, and project-scope install all updated to match (#1079)
- Docs: README warns against `pip install` on Mac/Windows due to Python env mismatch causing `ModuleNotFoundError`; `uv tool install` recommended as primary method (#1074)
## 0.8.24 (2026-05-29)
- Feat: type-reference edges for ObjC, Julia, C, C++, Scala, Fortran, and PowerShell — extends cross-language semantic context work from #1015 to a second wave of languages; CI matrix now covers Python 3.10 with `faster-whisper` version guard (#1071)
- Fix: claude-cli backend no longer loops on hollow streamed responses — handles all four documented failure modes (empty stream, no JSON, missing `result`, empty `result`) with tests (#1063)
- Fix: `calls` edges no longer flip caller/callee when the same node pair appears in both directions in an undirected build — first-seen direction preserved on bidirectional collision (#1061)
- Fix: `graphify-out/.graphify_python` path prefix was missing in 8 skill files (256 instances) causing `cat: .graphify_python: No such file or directory` on every non-Claude-Code platform
- Chore: all skill files now use uv-aware interpreter detection — `uv tool run graphifyy python` preferred over shebang parsing when uv is available
## 0.8.23 (2026-05-28)
- Feat: type-reference edges for Swift, Kotlin, PHP, Rust, and Go — `references` edges with `parameter_type`, `return_type`, `generic_arg`, `field`, and `attribute` contexts; inheritance split into `inherits` (superclass) vs `implements` (protocol/interface/trait) for all five languages (#1015)
- Chore: CI switched from pip to uv (`astral-sh/setup-uv`, `uv sync`, `uv run pytest`); `uv.lock` committed for reproducible installs; dev setup docs updated (#885)
## 0.8.22 (2026-05-28)
- Feat: BYOND DreamMaker support — `.dm`/`.dme` files extracted via tree-sitter-dm (type definitions, proc declarations, `#include` edges, in-file call resolution, `new /type()` instantiation edges); `.dmi` PNG icon files parsed for icon-state nodes; `.dmm` map files parsed for type-path `uses` edges from the tile dictionary section; `.dmf` interface files parsed for window/elem/control-type hierarchy (#884)
- Feat: `graphify extract --mode deep` flag enables richer semantic extraction using an extended system prompt; flag propagated through all four LLM backends (#1030)
## 0.8.21 (2026-05-27)
- Fix: `graphify update` (no `--changed` flag) no longer leaves ghost nodes from files deleted between runs — full re-extraction path now reconciles the existing graph against current disk state and evicts any node whose `source_file` no longer exists; `_norm_source_file` used on both sides to guarantee path format consistency (#1007)
- Fix: `graphify install --platform opencode --project` now writes `SKILL.md` to `.opencode/skills/graphify/SKILL.md` (discoverable by OpenCode) instead of the incorrect `.config/opencode/skills/` path; git-add hint updated accordingly (#1040)
- Fix: post-commit hook no longer triggers rebuild when only `graphify-out/` files were committed (avoids infinite dirty-tree loop when graph outputs are tracked in git); `GRAPHIFY_SKIP_HOOK=1` env var added for one-off skip; hook rebuild log now appends (`>>`) instead of overwriting (`>`) (#1018, #1037)
- Fix: graph output is now byte-for-byte deterministic across runs — edges sorted by `(source, target, relation)` in `build_from_json`; `PYTHONHASHSEED=0` exported in hook scripts to stabilize Louvain community ordering (#1010)
- Feat: Amp (ampcode.com) platform support — `graphify amp install/uninstall` installs the skill into `.amp/skills/graphify/SKILL.md` (#948)
- Fix: query punctuation no longer breaks node matching — `"what calls extract?"` correctly finds the `extract` node; `_search_tokens` helper strips punctuation from search terms in `_query_terms`, `_score_nodes`, and `_find_node` (#994, #978)
- Fix: language built-in globals (`String`, `Number`, `Boolean`, `Object`, `Array`, etc.) no longer accumulate spurious call edges — filtered at same-file and cross-file resolution in the AST extractor, eliminating god-node pollution from constructor-style calls (#916, #726)
- Feat: SystemVerilog header files (`.svh`) now extracted using the Verilog parser alongside `.v` and `.sv` (#1042)
- Fix: `@property`, `@staticmethod`, `@classmethod` methods no longer produce orphaned nodes without a class-qualified ID — `decorated_definition` is now treated as a transparent wrapper in the Python AST walker, preserving `parent_class_nid` through the decorator layer (#1050)
- Fix: Pass 2 dedup no longer merges nodes with identical labels that live in different files — same-file partition enforced for the identical-label subcase so `foo()` in `a.py` and `foo()` in `b.py` are not collapsed into one node (#1046)
- Fix: `graphify-out/memory/` files are no longer silently excluded by `.gitignore` pattern matching — memory dir files now bypass the gitignore filter in `detect.py`, ensuring knowledge accumulated via `graphify remember` is always scanned (#1047)
## 0.8.20 (2026-05-26)
- Fix: stale nodes persist after `graphify update` when files are deleted on Windows — `deleted_paths` and `evict_sources` in `_rebuild_code` now use `.as_posix()` for consistent forward-slash paths; `_relativize_source_files` called on the existing graph before eviction (not after); `_relativize_source_files` itself now produces forward slashes (#1007)
- Fix: `graphify extract` stale-node pruning now also handles symlinked scan roots — `prune_set` expansion uses `Path(root).resolve()` before `relative_to()` so symlinked roots produce correct relative paths (#1007)
- Feat: MCP config extractor — `.mcp.json`, `mcp.json`, `mcp_servers.json`, `claude_desktop_config.json` now extracted into the knowledge graph; captures server nodes, npm/pip package refs, env var requirements; env values discarded to prevent secret leakage (#1034)
- Fix: `cluster-only` no longer drops community label alignment after re-clustering — `remap_communities_to_previous` now applied in the `cluster-only` path, matching the behaviour of `graphify update` (#1028)
- Fix: Dart child node IDs no longer embed absolute paths — switched from `_make_id(str(path), name)` to `_make_id(_file_stem(path), name)`, consistent with all other extractors; existing Dart graphs should be rebuilt with `--force` (#999)
- Security: XML parsing in `extract_csproj` and `extract_lazarus_package` now pre-screens for `<!DOCTYPE` / `<!ENTITY` declarations before calling `ET.fromstring`, blocking billion-laughs DoS on malicious project files; `extract_lpk` also gains the missing 2 MiB size cap
## 0.8.19 (2026-05-26)
- Feat: .NET project file support — `.sln`, `.csproj`, `.fsproj`, `.vbproj`, `.razor`, `.cshtml` now extracted; captures NuGet package refs, project-to-project dependencies, target frameworks, SDK attributes, Blazor/Razor directives (`@using`, `@inject`, `@inherits`, `@model`, `@page`), component refs, and `@code` block methods (#1025)
- Feat: Chinese query segmentation — compound Chinese tokens (e.g. `页面路由`) are split into meaningful words using jieba when installed, with character bigram fallback; original compound preserved alongside segments for exact-match; new `pip install "graphifyy[chinese]"` extra (#1026)
- Fix: Wiki TypeError when `source_file` is `None` — `G.nodes[n].get("source_file") or ""` replaces `.get("source_file", "")`, which did not handle explicit `None` values (#1016)
- Fix: Nested `.claude/worktrees/` no longer indexed — `_is_noise_dir` now accepts an optional `parent` param and skips `worktrees/` directories nested inside dotted dirs like `.claude/` (#1023)
- Fix: `backup_if_protected` no longer accumulates one folder per run — uses content-hash comparison to skip identical backups and overwrite in-place when content changes; one folder per day maximum
- Feat: Devin CLI support — `graphify devin install/uninstall` installs the skill into Devin's `.devin/rules/` directory (#1020)
- Fix: TypeScript 5.0 array-form `extends` in `tsconfig.json` now handled — `_read_tsconfig_aliases` normalizes `extends` to a list before iteration (#1017)
## 0.8.18 (2026-05-24)
- Fix: post-commit hook now updates graph after delete-only commits — shrink-guard is bypassed when `changed_paths` contains explicit deletions, preventing stale nodes from accumulating indefinitely (#1000)
- Fix: `graphify export` (html/obsidian/wiki/svg/graphml/neo4j) no longer collapses to "Single community" when `.graphify_analysis.json` is absent — falls back to per-node `community` attribute already present in `graph.json` (#1001)
- Fix: Ukrainian README translation updated to v8 — all new sections, correct badges, 31 languages (#995)
- Feat: semantic context tags on `references` edges for Python/JS/TS/C#/Java — `parameter_type`, `return_type`, `generic_arg`, `attribute`, `field`; C#/Java split `inherits`/`implements`; dedup key now includes context (#996)
- **Breaking:** Java `extends` edges are now emitted as `inherits` — queries filtering on `relation="extends"` for Java nodes must be updated to `relation="inherits"`
- Feat: constrained query expansion in skill — Step 0 extracts actual graph vocab and forces LLM to pick expansion tokens only from that set, preventing hallucinated expansions; Unicode regex fix captures Cyrillic/CJK labels (#998)
- Docs: Ukrainian README updated to v8 with all new sections, correct badges, YC badge, 31 language count (#995)
## 0.8.17 (2026-05-23)
- Fix: Case-sensitive call resolution for Go, Rust, and Elixir — resolvers previously lowercased both the label index and the callee name, causing `Authorize` to match `authorize` and produce phantom edges; Ruby/C#/Java/Kotlin/Scala/PHP use the same generic resolver which now splits into case-sensitive (all languages) and case-insensitive (PHP only, where function/class names are genuinely case-insensitive) dicts (#993)
- Fix: Cross-language phantom `calls` edges from semantic extraction dropped at graph-build time — INFERRED `calls` edges whose source and target nodes belong to different language families (py/js/go/rs/jvm/c/cpp/rb/php/cs/swift/lua) are now discarded; skill.md prompt updated with an explicit anti-rule (#991)
## 0.8.16 (2026-05-22)
- Fix: CJK/Unicode labels no longer silently stripped during dedup — `_norm()` and `_norm_label()` now use Unicode-aware `[\W_]+` regex with `casefold()` and NFKC normalization; previously `道具処理クラス` and any non-ASCII label collapsed to empty string and got falsely merged (#937)
- Fix: `.ets` (ArkTS/HarmonyOS) files now recognized as code and extracted via the TypeScript parser (#926)
- Fix: `graphify` now exits non-zero when all semantic-extraction chunks fail — previously a silent empty graph was written with exit code 0, masking backend failures (#889)
- Feat: `graphify install --project` installs the skill into the current repository (`.claude/skills/`, `.agents/skills/`, etc.) instead of the user home directory; per-platform subcommands support the same flag (#931)
- Docs: Uzbek (uz-UZ) README translation (#982)
## 0.8.15 (2026-05-22)
- Fix: `cluster-only` subcommand crashed with `FileNotFoundError` when `graphify-out/` did not yet exist — output directory is now created before any write (#934)
- Fix: `GRAPHIFY_MAX_OUTPUT_TOKENS` env var now respected for all OpenAI-compatible backends — previously the token limit was hardcoded, causing truncated responses on high-context queries (#973)
- Fix: Swift extension nodes no longer duplicated across files — `_merge_swift_extensions` deduplicates by canonical name before graph insertion (#969)
- Fix: Non-Latin query terms (CJK, Arabic, Cyrillic, etc.) now preserved through query preprocessing — previous normalization stripped non-ASCII chars, making multi-lingual codebases unsearchable (#964)
- Feat: Multigraph runtime compatibility probe — emits a warning if a `MultiDiGraph` is passed where a `Graph` is expected by any downstream consumer (analyze, cluster, wiki, export, report) (#956)
- Feat: JS/TS barrel re-exports tracked as explicit `re_exports` graph edges — `export { X } from './mod'` emits typed edges with `context="re-export"` and `confidence=EXTRACTED`; file-level `imports_from` edges also emitted (#960)
- Feat: `--affected` and `--import-resolution` flags for the `v8` subcommand — impact analysis and cross-file import resolution exposed as first-class CLI options
## 0.8.14 (2026-05-20)
- Fix: `--wiki` crash when community node IDs are stale after dedup or re-extract — stale IDs are now silently dropped with a stderr warning; raises a clear error only if every ID is stale (#936)
- Fix: `.gitignore` patterns now respected when no `.graphifyignore` exists — previous behaviour silently ignored the project's gitignore, causing expected exclusions to be skipped (#945)
- Feat: `--exclude <pattern>` CLI flag to pass extra gitignore-style exclusion patterns at runtime without modifying `.graphifyignore` (#947)
- Fix: `.worktrees/` directory now skipped during scan — git worktree sibling checkouts inside `.worktrees/` were previously indexed as duplicate source (#947)
- Security: NAT64 IPv6 addresses (`64:ff9b::/96`) no longer false-positive as blocked reserved IPs — affects hosts like `arxiv.org` on IPv6-only networks where the ISP uses RFC 6052 NAT64
## 0.8.13 (2026-05-18)
- Fix: node ID collisions across same-named files in different directories — SQL extractor and Python import resolver now use directory-qualified stems (`dir_file_entity`) instead of bare filename stems, preventing silent node merging on repos with duplicate filenames (#1A, #1B)
- Perf: stat-based mtime fastpath for `file_hash` — skips full SHA256 read when file size+mtime_ns unchanged, same trade-off as make; index flushed atomically via atexit
- Fix: absolute `source_file` paths from semantic subagents no longer stored in graph — `build_from_json`, `build`, and `build_merge` accept a `root` param and relativize paths at build time (#932)
- Fix: failed semantic chunks no longer permanently freeze their files in the manifest — only files that appear in extraction output get `semantic_hash` stamped; failed-chunk files keep empty `semantic_hash` and are re-queued on next run (#933)
- Feat: `graphify cache-check`, `graphify merge-chunks`, `graphify merge-semantic` CLI subcommands expose cache and merge logic as library-callable commands for skill pipelines
## 0.8.12 (2026-05-18)
- Security: `_is_sensitive` now correctly flags underscore-prefixed secret filenames (`api_token.txt`, `oauth_token.json`) — `\b` word boundary was treating `_` as a word char, so names like `api_token` never matched (#920)
- Security: `_is_sensitive` now checks parent directories against a `_SENSITIVE_DIRS` blocklist (`.ssh`, `.aws`, `.gcloud`, `secrets`, etc.) so any file inside those dirs is skipped regardless of name; root-level files named `credentials` or `secrets` are no longer falsely flagged (#920)
- Fix: `--wiki` Relationships section was always empty — `_cross_community_links` read `community` from node attributes (always None) instead of the `communities` dict; `_god_node_article` had the same bug and never linked to the owning community (#925)
- Fix: `--watch` now respects `.graphifyignore` — the event handler was checking extensions before the ignore filter, so paths inside `node_modules/`, `.venv/`, etc. triggered rebuilds (#928)
- Fix: `graphify <path>` now correctly dispatches to `graphify extract <path>` — previously a bare path argument returned "unknown command" instead of starting extraction
- Fix: skill fast path — if `graphify-out/graph.json` already exists and the request is a natural-language question, extraction steps are skipped entirely and `graphify query` runs immediately; previously the skill re-ran detect and hit the corpus-size gate on every question
- Fix: large-corpus gate raised from 200 to 500 files; `detect()` now returns `scan_root` so the skill correctly computes relative subdirectory breakdowns instead of showing absolute paths; flat repos with no subdirectories no longer ask the user to pick a subfolder that doesn't exist
- Docs: clarify that code-only corpora skip the LLM semantic extraction pass entirely — AST handles code, Pass 3 is reserved for docs, papers, images, and transcripts (#836)
## 0.8.11 (2026-05-18)
- Fix: LLM empty choices / None message guard — Gemini and other providers return `choices=[]` on content-filtered HTTP 200 responses; now raises a clean error instead of crashing with IndexError (#924)
- Fix: OpenCode skill removed invalid `general-purpose` agent reference and headless-incompatible interactive halt (#911, closes #825)
- Fix: Codex skill now uses graphify query/explain/path even when graph artifacts are dirty in worktree (#913, closes #860)
- Perf: precompute degrees once in surprise scoring — ~11x speedup per lookup on large graphs (#914)
## 0.8.10 (2026-05-17)
- Fix: git hooks phantom directory on git < 2.31 — drop `--path-format=absolute`, validate path contains no newlines, anchor relative paths on repo root (#907)
- Fix: `save_manifest` incremental data loss — seed from existing manifest before loop so untouched files aren't erased on partial runs (#917)
- Fix: C++ class/struct inheritance edges missing — extract `base_class_clause` for `class_specifier` and `struct_specifier` (#915)
- Fix: cohesion split threshold unreachable due to rounding — `cohesion_score` now returns raw float, display rounds to 2dp (#919)
- Fix: Rust cross-crate spurious INFERRED edges — skip `Type::method()` scoped calls and common trait-method names from cross-file resolver (#908)
- Feat: `--resolution N` for `extract` and `cluster-only` — control Leiden/Louvain community granularity (>1 = more smaller, <1 = fewer larger) (#919)
- Feat: `--exclude-hubs P` for `extract` and `cluster-only` — exclude degree-percentile super-hubs from partitioning, reattach by majority-vote neighbour community (#919)
## 0.8.9 (2026-05-17)
- Feat: DeepSeek backend support — set `DEEPSEEK_API_KEY` and use `--backend deepseek`; default model `deepseek-v4-flash`
## 0.8.8 (2026-05-16)
- Feat: `graphify prs` — graph-aware PR dashboard: CI state, review decision, worktree mapping, and graph blast radius per PR; `--triage` ranks your queue via any configured LLM backend (claude, kimi, openai, gemini, claude-cli, ollama — auto-detected); `--conflicts` shows PRs sharing graph communities with node labels; `--worktrees` maps worktree paths to branches to open PRs; MCP tools `list_prs`, `get_pr_impact`, `triage_prs` for agent access
## 0.8.7 (2026-05-16)
- Fix: query seed selection now uses IDF weighting — common terms like `error` or `handle` that match dozens of nodes are down-weighted so a rare identifier like `FooBarService` ranks first and BFS expands from the right node (#897)
- Fix: seed count is now dynamic — a dominant match (score gap >80% vs next candidate) gets one seed rather than always picking three, preventing noise nodes from consuming BFS slots alongside the target (#897)
- Fix: truncation message in `query_graph` now tells Claude what to do (call `get_node` or add a `context_filter`) rather than just saying "truncated" (#897)
- Fix: C++ class data members (`int x;`, `static const int MAX = 100;`) now extracted as nodes with `defines` edges from the parent class — previously the field_declaration branch was a no-op due to a wrong child type guard (#898)
- Fix: dedup Pass 1 now partitions same-label groups by source_file before merging — nodes with generic labels (`handle`, `init`, `run`) from different files no longer collapse into artificial god nodes; cross-file matches are routed to Pass 2 fuzzy (#895)
- Fix: C/C++ `#include "path/to/file.h"` edges now resolve the include path relative to the including file and use the full resolved path as the target node ID, matching what extraction creates for the included file — previously all include edges dangled with a basename-only ID (#899)
- Fix: `exact_merges` counter in dedup now reports only merges actually performed rather than counting all same-label nodes across files (#895)
## 0.8.6 (2026-05-16)
- Fix: cross-language INFERRED `calls`/`uses` edges (e.g. Python → TypeScript) are suppressed in Surprising Connections — label-matching across language boundaries in monorepos is resolver pollution, not structural insight; all structural bonuses zeroed for these edges
- Fix: code-to-doc INFERRED `calls`/`uses` edges suppressed in Surprising Connections — the LLM seeing a symbol name in a README and emitting a `calls` edge is documentation cross-reference noise, not a real architectural connection (#890)
- Fix: generic JSON key nodes (`name`, `id`, `type`, `start`, `end`, `key`, `value`, `data`, `items`, `title`, `description`, `version`, `properties`) filtered from god_nodes — their degree is positional (every sibling record in the same JSON file references them), not architectural (#890)
- Fix: Alembic migrations, Django migrations, and protobuf-generated files now have their module-level docstrings suppressed from rationale extraction — these are boilerplate headers, not design intent; function docstrings inside migration files are still captured
- Feat: `--follow-symlinks` is now auto-detected — if symlinked children are present in the target directory, follow-symlinks is enabled automatically without requiring an explicit flag (#887)
- Fix: install guidance now directs users to run `/graphify query` interactively rather than reading `GRAPH_REPORT.md` first; the report is a summary, not a starting point (#891)
## 0.8.5 (2026-05-15)
- Fix: `.graphifyignore` parent-exclusion rule now correctly blocks files under an excluded directory even when a `!` negation exists elsewhere in the file — previously any negation pattern disabled directory pruning entirely (#882)
- Fix: dedup no longer false-merges chip/model SKU variants like `ASR1603`/`ASR1605` or `M1`/`M1 Pro` — Jaro-Winkler prefix bonus is now gated by `_is_variant_pair` and `_short_label_blocked` guards; real typos on short labels still merge (#878)
- Docs: added `worked/rsl-siege-manager/` — case study on a real-world Python + TypeScript monorepo (FastAPI backend, React/Vite frontend, Discord bot); covers god node behaviour with tests included, cross-language INFERRED edges, community cohesion, and Alembic migration noise (#881)
## 0.8.4 (2026-05-15)
- Feat: Firebird SQL — trigger and stored procedure extraction via `CREATE TRIGGER` and regex fallback; FK detection via global regex covering `REFERENCES` and `FOREIGN KEY` clauses (#875)
- Fix: SQL extraction regex fallback now decodes source as UTF-8 instead of latin-1, preventing non-ASCII identifier hash mismatches (#875)
- Fix: `--update` deletion pruning now matches on full source file paths instead of basenames, preventing false node removal when different directories contain files with the same name (#876)
- Fix: `--update` now also prunes edges whose `source_file` attr points to deleted files, not just nodes (#876)
- Fix: community label keys from `graph.json` (stored as strings) are now coerced to int before lookup, fixing blank community names in GRAPH_REPORT.md and graph.html (#877)
## 0.8.3 (2026-05-15)
- Fix: Windows skill temp files (chunk JSONs, `.graphify_python`, `.graphify_root`) no longer pollute the project root — all written under `graphify-out/` (#831)
- Fix: `--update` with deletions-only no longer errors when `.graphify_extract.json` does not yet exist — creates an empty extraction file before merging (#876)
## 0.8.2 (2026-05-15)
- Fix: Python interpreter detection for `uv tool` and `pipx` installs on Windows — `graphify install` and all skill steps now find the correct executable (#831)
- Fix: antigravity Windows skill path resolution (#831)
- Fix: dot directories (e.g. `.github/`, `.vscode/`) are now indexed when explicitly included via `.graphifyignore` (#873)
- Fix: MCP server hot-reloads the graph when `graph.json` changes on disk (#874)
## 0.8.1 (2026-05-15)
- Feat: Bash extractor — `.sh` and `.bash` files now indexed via tree-sitter; extracts functions, cross-function calls, `source`/`.` imports resolved to real file paths, and `export`/`declare` variable declarations (#866)
- Feat: JSON extractor — `.json` files now indexed via tree-sitter; extracts key/value `contains` tree, `dependencies`/`devDependencies` blocks as `imports` edges, `extends` edges (tsconfig, eslintrc), and `$ref` references (#866)
- Feat: `.sh`, `.bash`, `.json` added to `CODE_EXTENSIONS` in `detect.py` so files are picked up during corpus scan (#866)
- Feat: Mermaid callflow HTML auto-regenerates on every graph rebuild when `*-callflow.html` exists in `graphify-out/` — works with `--watch` and `graphify hook install`
- Fix: `coverage/`, `lcov-report/`, `visual-tests/`, `visual-test/`, `__snapshots__/`, `snapshots/`, `storybook-static/`, `dist-protected/` added to `_SKIP_DIRS` — generated artefact dirs no longer appear in the corpus (#869, #870)
- Fix: `graphify hook install` now works in git linked worktrees — uses `git rev-parse --git-path hooks` instead of constructing `.git/hooks/` directly (#865)
- Fix: office sidecar files in `graphify-out/converted/` are now checked against `.graphifyignore` before being added to the file list (#861)
- Fix: `save_manifest()` accepts a `kind` parameter (`ast`, `semantic`, `both`) — incremental AST-only `graphify update` no longer overwrites `semantic_hash` entries, preventing spurious full re-extracts on the next run (#857)
- Fix: five paths in `skill-windows.md` Step B3 were missing the `graphify-out/` prefix, causing chunk files to be written to the wrong directory (#862)
## 0.7.19 (2026-05-14)
- Feat: `.astro` files now extracted as code — frontmatter static imports, dynamic imports, and `<script>` block imports all produce edges; tsconfig path aliases resolved (#850, PR #852)
+25
View File
@@ -0,0 +1,25 @@
# graphify MCP server as a shared HTTP service (issue #1143).
#
# Build: docker build -t graphify .
# Run: docker run -p 8080:8080 -v "$(pwd)/graphify-out:/data" graphify \
# /data/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
#
# Builds from source so the image includes the Streamable HTTP transport even
# before it lands on PyPI. The graph.json is mounted at runtime (-v), never
# baked into the image.
FROM python:3.12-slim
WORKDIR /app
COPY . /app
# The [mcp] extra pulls mcp + starlette + uvicorn, which the HTTP transport needs.
RUN pip install --no-cache-dir ".[mcp]"
# Run as a non-root user — the server is network-exposed.
RUN useradd --create-home --uid 10001 graphify
USER graphify
EXPOSE 8080
ENTRYPOINT ["python", "-m", "graphify.serve"]
CMD ["/data/graph.json", "--transport", "http", "--host", "0.0.0.0", "--port", "8080"]
+229 -70
View File
@@ -3,14 +3,15 @@
</p>
<p align="center">
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇷 <a href="docs/translations/README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="docs/translations/README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="docs/translations/README.fil-PH.md">Filipino</a>
</p>
<p align="center">
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></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://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" 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://clickpy.clickhouse.com/dashboard/graphifyy"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsql-clickhouse.clickhouse.com%2F%3Fquery%3DSELECT%2520concat%2528toString%2528round%2528sum%2528count%2529%2F1000%2529%2529%2C%2520%2527k%2527%2529%2520AS%2520c%2520FROM%2520pypi.pypi_downloads%2520WHERE%2520project%253D%2527graphifyy%2527%2520FORMAT%2520JSON%26user%3Ddemo&query=%24.data%5B0%5D.c&label=downloads&color=blue" alt="Downloads"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
@@ -24,7 +25,7 @@
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.
Works in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, and Google Antigravity.
Works in Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, Devin CLI, and Google Antigravity.
```
/graphify .
@@ -86,7 +87,7 @@ uv tool install graphifyy
# Alternatives:
pipx install graphifyy
pip install graphifyy
pip install graphifyy # may need PATH setup — see note below
```
**Step 2 — register the skill with your AI assistant:**
@@ -97,18 +98,39 @@ graphify install
That's it. Open your AI assistant and type `/graphify .`
To install the assistant skill into the current repository instead of your user
profile, add `--project`:
```bash
graphify install --project
graphify install --project --platform codex
```
Project-scoped installs write under the current directory, for example
`.claude/skills/graphify/SKILL.md` or `.agents/skills/graphify/SKILL.md` (plus a
`references/` sidecar the skill loads on demand), and
print a `git add` hint for files that can be committed.
Per-platform commands that support project-scoped installs accept the same flag,
for example `graphify claude install --project` or `graphify codex install --project`.
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell.
> **`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`.
> **Avoid `pip install` on Mac/Windows** if possible. The skill resolves Python at runtime from `graphify-out/.graphify_python`; if that points to a different environment than where `pip` installed the package, you'll get `ModuleNotFoundError: No module named 'graphify'`. `uv tool install` and `pipx install` isolate the package in their own env and avoid this entirely.
> **Git hooks and uv tool / pipx:** `graphify hook install` embeds the current interpreter path directly into the hook scripts at install time, so the post-commit hook fires correctly even in GUI git clients and CI runners where `~/.local/bin` is not on PATH. If you reinstall or upgrade graphify, re-run `graphify hook install` to refresh the embedded path.
### Pick your platform
| Platform | Install command |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install --platform windows` |
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| Kilo Code | `graphify install --platform kilo` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
@@ -119,12 +141,15 @@ That's it. Open your AI assistant and type `/graphify .`
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify install --platform pi` |
| Cursor | `graphify cursor install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
> Codex users: also add `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as Claude Code. 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 uses `$graphify` instead of `/graphify`.
### Optional extras
@@ -133,20 +158,27 @@ Install only what you need:
| Extra | What it adds | Install |
|---|---|---|
| `pdf` | PDF extraction | `pip install "graphifyy[pdf]"` |
| `office` | `.docx` and `.xlsx` support | `pip install "graphifyy[office]"` |
| `google` | Google Sheets rendering | `pip install "graphifyy[google]"` |
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `pip install "graphifyy[video]"` |
| `mcp` | MCP stdio server | `pip install "graphifyy[mcp]"` |
| `neo4j` | Neo4j push support | `pip install "graphifyy[neo4j]"` |
| `svg` | SVG graph export | `pip install "graphifyy[svg]"` |
| `leiden` | Leiden community detection (Python < 3.13 only) | `pip install "graphifyy[leiden]"` |
| `ollama` | Ollama local inference | `pip install "graphifyy[ollama]"` |
| `openai` | OpenAI / OpenAI-compatible APIs | `pip install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `pip install "graphifyy[gemini]"` |
| `bedrock` | AWS Bedrock (uses IAM, no API key) | `pip install "graphifyy[bedrock]"` |
| `sql` | SQL schema extraction | `pip install "graphifyy[sql]"` |
| `all` | Everything above | `pip install "graphifyy[all]"` |
| `pdf` | PDF extraction | `uv tool install "graphifyy[pdf]"` |
| `office` | `.docx` and `.xlsx` support | `uv tool install "graphifyy[office]"` |
| `google` | Google Sheets rendering | `uv tool install "graphifyy[google]"` |
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` |
| `mcp` | MCP stdio server | `uv tool install "graphifyy[mcp]"` |
| `neo4j` | Neo4j push support | `uv tool install "graphifyy[neo4j]"` |
| `falkordb` | FalkorDB push support | `uv tool install "graphifyy[falkordb]"` |
| `svg` | SVG graph export | `uv tool install "graphifyy[svg]"` |
| `leiden` | Leiden community detection (Python < 3.13 only) | `uv tool install "graphifyy[leiden]"` |
| `ollama` | Ollama local inference | `uv tool install "graphifyy[ollama]"` |
| `openai` | OpenAI / OpenAI-compatible APIs | `uv tool install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
| `anthropic` | Anthropic Claude API (`--backend claude`, uses `ANTHROPIC_API_KEY`) | `uv tool install "graphifyy[anthropic]"` |
| `bedrock` | AWS Bedrock (uses IAM, no API key) | `uv tool install "graphifyy[bedrock]"` |
| `azure` | Azure OpenAI Service (`--backend azure`, uses `AZURE_OPENAI_API_KEY` + `AZURE_OPENAI_ENDPOINT`) | `uv tool install "graphifyy[openai]"` |
| `sql` | SQL schema extraction | `uv tool install "graphifyy[sql]"` |
| `postgres` | Live PostgreSQL introspection (`--postgres DSN`) | `uv tool install "graphifyy[postgres]"` |
| `dm` | BYOND DreamMaker `.dm`/`.dme` AST extraction (may need a C compiler + `python3-dev` if no wheel matches your platform) | `uv tool install "graphifyy[dm]"` |
| `terraform` | Terraform / HCL `.tf`/`.tfvars`/`.hcl` AST extraction | `uv tool install "graphifyy[terraform]"` |
| `chinese` | Chinese query segmentation (jieba) | `uv tool install "graphifyy[chinese]"` |
| `all` | Everything above | `uv tool install "graphifyy[all]"` |
---
@@ -157,8 +189,10 @@ Run this once in your project after building a graph:
| Platform | Command |
|----------|---------|
| Claude Code | `graphify claude install` |
| CodeBuddy | `graphify codebuddy install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| Kilo Code | `graphify kilo install` |
| GitHub Copilot CLI | `graphify copilot install` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify aider install` |
@@ -170,16 +204,26 @@ Run this once in your project after building a graph:
| Gemini CLI | `graphify gemini install` |
| Hermes | `graphify hermes install` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify pi install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
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.
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions — preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files. On platforms that support payload-bearing hooks (Claude Code, Gemini CLI), a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path. On the others (Codex, OpenCode, Cursor, etc.), the persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance. `GRAPH_REPORT.md` is still available for broad architecture review.
**CodeBuddy** does the same two things as Claude Code: writes a `CODEBUDDY.md` section telling CodeBuddy to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs **PreToolUse hooks** (`.codebuddy/settings.json`) that fire before Bash search commands and file reads, nudging toward `graphify query` instead.
**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.
To remove graphify from all platforms at once: `graphify uninstall` (add `--purge` to also delete `graphify-out/`). Or use the per-platform command (e.g. `graphify claude uninstall`).
---
**Kilo Code** installs the Graphify skill to `~/.config/kilo/skills/graphify/SKILL.md` and a native `/graphify` command to `~/.config/kilo/command/graphify.md`. `graphify kilo install` also writes `AGENTS.md` plus a native **`tool.execute.before` plugin** (`.kilo/plugins/graphify.js` + `.kilo/kilo.json` or `.kilo/kilo.jsonc` registration) so Kilo gets the same always-on graph reminder behavior through native `.kilo` config.
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
## What's in the report
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
@@ -194,14 +238,18 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| Type | Extensions |
|------|-----------|
| Code (29 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk` |
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (requires `pip install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `pip install graphifyy[google]`) |
| Code (36 tree-sitter grammars) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .psm1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .slnx .csproj .fsproj .vbproj .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`) |
| Salesforce Apex | `.cls .trigger` (regex-based; classes, interfaces, enums, methods, triggers, SOQL/DML edges) |
| Terraform / HCL | `.tf .tfvars .hcl` (requires `uv tool install graphifyy[terraform]`) |
| MCP configs | `.mcp.json` `mcp.json` `mcp_servers.json` `claude_desktop_config.json` — extracts server nodes, package refs, env var requirements |
| Package manifests | `apm.yml` `pyproject.toml` `go.mod` `pom.xml` — one canonical package node per package (by name) plus `depends_on` edges, so a package referenced from many manifests is a single hub |
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` (markdown `[text](./other.md)` links and `[[wikilinks]]` become `references` edges between docs) |
| Office | `.docx .xlsx` (requires `uv tool install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `uv tool install graphifyy[google]`) |
| 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]`) |
| Video / Audio | `.mp4 .mov .mp3 .wav` and more (requires `uv tool install graphifyy[video]`) |
| YouTube / URLs | any video URL (requires `uv tool install graphifyy[video]`) |
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
@@ -211,7 +259,7 @@ in a headless extraction, install and authenticate the
[`gws` CLI](https://github.com/googleworkspace/cli), then run:
```bash
pip install "graphifyy[google]" # needed for Google Sheets table rendering
uv tool install "graphifyy[google]" # needed for Google Sheets table rendering
gws auth login -s drive
graphify extract ./docs --google-workspace
```
@@ -227,9 +275,11 @@ You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into
/graphify . # build graph for current folder
/graphify ./docs --update # re-extract only changed files
/graphify . --cluster-only # rerun clustering without re-extracting
/graphify . --cluster-only --resolution 1.5 # more granular communities
/graphify . --cluster-only --exclude-hubs 99 # suppress utility super-hubs from god-node rankings
/graphify . --no-viz # skip the HTML, just the report + JSON
/graphify . --wiki # build a markdown wiki from the graph
graphify export callflow-html # architecture/call-flow HTML from graphify-out/
graphify export callflow-html # Mermaid architecture/call-flow HTML (auto-regenerates on every git commit if hook is installed)
/graphify query "what connects auth to the database?"
/graphify path "UserService" "DatabasePool"
@@ -240,6 +290,11 @@ graphify export callflow-html # architecture/call-flow HTML from graphify-o
graphify hook install # auto-rebuild on git commit
graphify merge-graphs a.json b.json # combine two graphs
graphify prs # PR dashboard: CI state, review status, worktree mapping
graphify prs 42 # deep dive on PR #42 with graph impact
graphify prs --triage # AI ranks your review queue (uses whatever backend is configured)
graphify prs --conflicts # PRs sharing graph communities — merge-order risk
```
See the [full command reference](#full-command-reference) below.
@@ -248,7 +303,9 @@ See the [full command reference](#full-command-reference) below.
## Ignoring files
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation:
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation.
**`.gitignore` is respected automatically.** graphify reads the `.gitignore` in each directory. If a `.graphifyignore` is also present, the two are **merged** — `.graphifyignore` patterns are evaluated last, so they win on conflicts (including `!` negations). Adding a `.graphifyignore` only ever excludes more; it never re-includes a file your `.gitignore` already excluded. Subdirectory scoping works the same way as git — an ignore file only affects its own subtree.
```
# .graphifyignore
@@ -270,11 +327,12 @@ dist/
**Recommended `.gitignore` additions:**
```
graphify-out/manifest.json # mtime-based, breaks after git clone
graphify-out/cost.json # local only
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
```
> `manifest.json` is now portable — keys are stored as relative paths and re-anchored on load, so committing it is safe and avoids a full rebuild on first checkout.
**Workflow:**
1. One person runs `/graphify .` and commits `graphify-out/`.
2. Everyone pulls — their assistant reads the graph immediately.
@@ -292,12 +350,40 @@ graphify query "what connects DigestAuth to Response?" --graph graphify-out/grap
# expose the graph as an MCP server (for repeated tool-call access)
python -m graphify.serve graphify-out/graph.json
python -m graphify.serve --graph graphify-out/graph.json # --graph flag also accepted
# register with Kimi Code:
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
# or serve over HTTP so a whole team points at one URL (no local graphify needed):
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
```
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`.
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
### Shared HTTP server
`--transport stdio` (the default) spawns one local server per developer. `--transport http` serves the same tools over the MCP Streamable HTTP transport, so a single shared process can serve the graph for the whole team — clients point their IDE MCP config at `http://<host>:8080/mcp` instead of running graphify locally.
| Flag | Default | Purpose |
|---|---|---|
| `--transport {stdio,http}` | `stdio` | Transport to serve on |
| `--host` | `127.0.0.1` | HTTP bind host (use `0.0.0.0` to expose beyond localhost) |
| `--port` | `8080` | HTTP bind port |
| `--api-key` | env `GRAPHIFY_API_KEY` | Require `Authorization: Bearer <key>` (or `X-API-Key`) |
| `--path` | `/mcp` | HTTP mount path |
| `--json-response` | off | Return plain JSON instead of SSE streams |
| `--stateless` | off | No per-session state (for load-balanced / CI deployments) |
| `--session-timeout` | `3600` | Reap idle stateful sessions after N seconds (`0` disables) |
The default `127.0.0.1` bind is loopback-only. Set `--host 0.0.0.0` **and** `--api-key` together when exposing on a shared host. Run it in a container:
```bash
docker build -t graphify .
docker run -p 8080:8080 -v "$(pwd)/graphify-out:/data" graphify \
/data/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
```
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Use a venv to avoid conflicts:
> ```bash
@@ -313,28 +399,46 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
| Variable | Used for | When required |
|---|---|---|
| `ANTHROPIC_API_KEY` | Claude (Anthropic) backend | `--backend claude` |
| `ANTHROPIC_BASE_URL` | Anthropic-compatible endpoint URL (LiteLLM proxy, gateways, ...) | `--backend claude` (default: `https://api.anthropic.com`) |
| `ANTHROPIC_MODEL` | Model name for the Claude backend — for custom endpoints, use the model name/alias your server exposes | `--backend claude` (default: `claude-sonnet-4-6`) |
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Google Gemini backend | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` |
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` (local servers accept any non-empty value) |
| `OPENAI_BASE_URL` | OpenAI-compatible server URL (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (default: `https://api.openai.com/v1`) |
| `OPENAI_MODEL` | Model name for the OpenAI backend — for self-hosted servers, use the model name/alias your server exposes (check its `/v1/models` endpoint), e.g. `LFM2.5-8B-A1B-UD-Q4_K_XL` for llama.cpp | `--backend openai` (default: `gpt-4.1-mini`) |
| `DEEPSEEK_API_KEY` | DeepSeek backend | `--backend deepseek` |
| `MOONSHOT_API_KEY` | Kimi Code backend | `--backend kimi` |
| `OLLAMA_BASE_URL` | Ollama local inference URL | `--backend ollama` (default: `http://localhost:11434`) |
| `OLLAMA_MODEL` | Ollama model name | `--backend ollama` (default: auto-detect) |
| `GRAPHIFY_OLLAMA_NUM_CTX` | Override Ollama KV-cache window size | optional — auto-sized by default |
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | Minutes to keep Ollama model loaded | optional — set `0` to unload after each chunk |
| `AZURE_OPENAI_API_KEY` | Azure OpenAI Service backend | `--backend azure` |
| `AZURE_OPENAI_ENDPOINT` | Azure resource endpoint URL | `--backend azure` (required alongside API key) |
| `AZURE_OPENAI_API_VERSION` | Azure API version override | optional — default `2024-12-01-preview` |
| `AZURE_OPENAI_DEPLOYMENT` or `GRAPHIFY_AZURE_MODEL` | Azure deployment name | optional — default `gpt-4o` |
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — standard credential chain | `--backend bedrock` (no API key, uses IAM) |
| `GRAPHIFY_MAX_WORKERS` | AST parallelism thread count | optional — also `--max-workers` flag |
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Raise output cap for dense corpora | optional — e.g. `32768` for large files |
| `GRAPHIFY_API_TIMEOUT` | HTTP timeout in seconds (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_API_TIMEOUT` | Per-call timeout in seconds for HTTP, claude-cli, and Anthropic SDK backends (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_FORCE` | Force graph rebuild even with fewer nodes | optional — also `--force` flag |
| `GRAPHIFY_GOOGLE_WORKSPACE` | Auto-enable Google Workspace export | optional — set to `1` |
| `GRAPHIFY_TRIAGE_BACKEND` | Backend for `graphify prs --triage` | optional — auto-detected from available keys |
| `GRAPHIFY_TRIAGE_MODEL` | Model override for triage | optional — e.g. `claude-opus-4-7` |
| `GRAPHIFY_QUERY_LOG` | Override query log path (default: `~/.cache/graphify-queries.log`) | optional — set to empty or `/dev/null` to silence |
| `GRAPHIFY_QUERY_LOG_DISABLE` | Set to `1` to disable query logging entirely | optional |
| `GRAPHIFY_QUERY_LOG_RESPONSES` | Set to `1` to also log full subgraph responses (off by default) | optional |
| `GRAPHIFY_MAX_GRAPH_BYTES` | Override the 512 MiB graph.json size cap — e.g. `700MB`, `2GB`, or plain bytes | optional — useful for very large corpora |
| `GRAPHIFY_LLM_TEMPERATURE` | Override LLM temperature for semantic extraction — e.g. `0.7`, or `none` to omit | optional — auto-omitted for o1/o3/o4/gpt-5 reasoning models |
---
## Privacy
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine.
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine. A code-only corpus requires no API key — `graphify extract` runs fully offline.
- **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), a running Ollama instance (`OLLAMA_BASE_URL`), AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM), or the `claude` CLI binary (Claude Code - no API key needed, uses your Claude subscription). The `--dedup-llm` flag uses the same key.
- **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), `DEEPSEEK_API_KEY` (DeepSeek), a running Ollama instance (`OLLAMA_BASE_URL`), AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM), or the `claude` CLI binary (Claude Code - no API key needed, uses your Claude subscription). The `--dedup-llm` flag uses the same key.
- **Data residency** — `graphify extract` auto-detects which provider to use based on which API key is set (priority: Gemini → Kimi → Claude → OpenAI → DeepSeek → Azure → Bedrock → Ollama). For code with data-residency requirements, use `--backend ollama` (fully local) or pass an explicit `--backend` flag. Kimi (`MOONSHOT_API_KEY`) routes to Moonshot AI servers in China.
- No telemetry, no usage tracking, no analytics.
- **Query logging** — every `graphify query`, `graphify path`, `graphify explain`, and MCP `query_graph` call is logged to `~/.cache/graphify-queries.log` in JSON Lines format (timestamp, question, corpus, nodes returned, duration). Full subgraph responses are **not** stored by default. Set `GRAPHIFY_QUERY_LOG_DISABLE=1` to opt out, or `GRAPHIFY_QUERY_LOG=/dev/null` to silence without disabling the code path.
---
@@ -356,7 +460,7 @@ PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash)
If a refactor deleted files, the old nodes linger. Pass `--force` (or set `GRAPHIFY_FORCE=1`) to overwrite even when the rebuild has fewer nodes.
**Graph has duplicate nodes for the same entity (ghost duplicates)**
This happens when semantic and AST extraction disagreed on the node ID format. Run a full re-extract to clean up:
Ghost duplicates (same symbol appearing twice — once from AST extraction with a source location, once from semantic extraction without) are now automatically merged at build time. If you see this in a graph built before v0.8.33, run a full re-extract to clean up:
```bash
graphify extract . --force
```
@@ -367,6 +471,14 @@ The KV-cache window is auto-sized but may be too large for your GPU. Reduce it:
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
```
**`LLM returned invalid JSON` / `Unterminated string` warnings**
The model's JSON response hit its output-token limit and was cut off mid-string. graphify auto-recovers (it splits the chunk and re-extracts the halves, and an oversized single document is first sliced at heading/paragraph boundaries so the whole file is still covered), so these warnings are noisy but not data loss. To reduce the churn, raise the output cap or shrink each chunk's output:
```bash
GRAPHIFY_MAX_OUTPUT_TOKENS=16384 graphify extract . --mode deep # lift the cap
graphify extract . --mode deep --token-budget 4000 # smaller input chunks -> smaller output
```
With a cloud gateway like OpenRouter, prefer `--backend openai` (set `OPENAI_BASE_URL`) over the Ollama shim — it's a cleaner OpenAI-compatible path. If the model has its own max-output ceiling, lowering `--token-budget` is the reliable lever.
**Graph HTML is too large to open in a browser (>5000 nodes)**
Skip HTML generation and use the JSON directly:
```bash
@@ -378,7 +490,7 @@ graphify query "..."
Run `graphify hook install` — it sets up a git merge driver that union-merges `graph.json` automatically so conflicts never happen.
**Extraction returns empty nodes/edges for docs or PDFs**
Docs and PDFs require an LLM call. Check that your API key is set and the backend is correct:
Docs, PDFs, and images require an LLM call — code-only corpora need no key. Check that your API key is set and the backend is correct:
```bash
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
@@ -408,6 +520,8 @@ graphify install # overwrites the skill file
/graphify ./raw --graphml # export for Gephi / yEd
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687
/graphify ./raw --falkordb # generate cypher.txt for FalkorDB
/graphify ./raw --falkordb-push falkordb://localhost:6379
/graphify ./raw --watch # auto-sync as files change
/graphify ./raw --mcp # start MCP stdio server
@@ -422,39 +536,69 @@ graphify install # overwrites the skill file
graphify uninstall # remove from all platforms in one shot
graphify uninstall --purge # also delete graphify-out/
graphify uninstall --project --platform codex # remove project-scoped install files only
graphify hook install # post-commit + post-checkout hooks
graphify hook uninstall
graphify hook status
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
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codebuddy install # CODEBUDDY.md + PreToolUse hook (CodeBuddy)
graphify codebuddy uninstall
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify kilo install # native Kilo skill + /graphify command + AGENTS.md + .kilo plugin
graphify kilo uninstall
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 claw uninstall
graphify droid install # AGENTS.md (Factory Droid)
graphify droid uninstall
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 amp install # skill file (Amp)
graphify amp uninstall
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
graphify kiro uninstall
graphify pi install # skill file (Pi coding agent)
graphify pi uninstall
graphify devin install # skill file + .windsurf/rules/graphify.md (Devin CLI)
graphify devin uninstall
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
graphify antigravity uninstall
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, ollama, bedrock, or claude-cli
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock, or claude-cli
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL) - no API key needed for loopback
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # any OpenAI-compatible server (llama.cpp, vLLM, LM Studio)
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # any Anthropic-compatible endpoint (LiteLLM proxy, gateways)
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # override KV-cache window (auto-sized by default)
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # unload model after each chunk (saves VRAM on small GPUs)
graphify extract ./docs --backend bedrock # AWS Bedrock via IAM - no API key, uses AWS credential chain
graphify extract ./docs --backend claude-cli # route through Claude Code CLI - no API key, uses your Claude subscription
graphify extract ./docs --backend azure # Azure OpenAI (set AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT)
graphify extract ./docs --max-workers 16 # AST parallelism (also GRAPHIFY_MAX_WORKERS)
graphify extract --postgres "postgresql://user:pass@host/db" # introspect live PostgreSQL schema directly
graphify extract ./my-workspace --cargo # introspect Rust Cargo workspace dependencies directly
graphify extract ./docs --token-budget 30000 # smaller semantic chunks for local/small models
graphify extract ./docs --max-concurrency 2 # fewer parallel LLM calls (useful for local inference)
graphify extract ./docs --api-timeout 900 # longer HTTP timeout for slow local models (default 600s)
graphify extract ./docs --google-workspace # export .gdoc/.gsheet/.gslides via gws before extraction
graphify extract ./docs --mode deep # richer semantic extraction via extended system prompt
graphify extract ./docs --no-cluster # raw extraction only, skip clustering
graphify extract ./docs --force # overwrite graph.json even if new graph has fewer nodes (use after refactors or to clear ghost duplicates)
graphify extract ./docs --dedup-llm # LLM tiebreaker for ambiguous entity pairs (uses same API key)
@@ -471,6 +615,15 @@ graphify global remove myrepo # remove a project from th
graphify global list # show all registered repos + node/edge counts
graphify global path # print path to the global graph file
graphify prs # PR dashboard: CI, review, worktree, graph impact
graphify prs 42 # deep dive on PR #42
graphify prs --triage # AI triage ranking (auto-detects backend from env)
graphify prs --worktrees # worktree → branch → PR mapping
graphify prs --conflicts # PRs sharing graph communities (merge-order risk)
graphify prs --base main # filter to PRs targeting a specific base branch
graphify prs --repo owner/repo # run against a different GitHub repo
GRAPHIFY_TRIAGE_BACKEND=kimi graphify prs --triage # use a specific backend for triage
graphify clone https://github.com/karpathy/nanoGPT
graphify merge-graphs a.json b.json --out merged.json
graphify --version # print installed version
@@ -481,8 +634,17 @@ graphify update ./src --no-cluster # skip reclustering, write raw AST graph onl
graphify update ./src --force # overwrite even if new graph has fewer nodes
graphify cluster-only ./my-project
graphify cluster-only ./my-project --graph path/to/graph.json # custom graph location
graphify cluster-only ./my-project --resolution 1.5 # more, smaller communities
graphify cluster-only ./my-project --exclude-hubs 99 # exclude p99 degree nodes from partitioning
graphify cluster-only ./my-project --no-label # keep "Community N" placeholders
graphify cluster-only ./my-project --backend=gemini # backend for community naming
graphify cluster-only ./my-project --backend=gemini --model gemini-2.5-pro # specific model
graphify label ./my-project # (re)name communities with the configured backend
graphify label ./my-project --backend=openai --model gpt-4o # force a specific backend and model
```
> **Community names:** inside an agent (Claude Code, Gemini CLI) the agent names communities itself. When you run the bare CLI, `cluster-only` auto-names them with the configured backend (built-in or custom OpenAI-compatible provider) — pass `--no-label` to keep `Community N`, or run `graphify label` to (re)generate names on demand.
---
## Learn more
@@ -508,43 +670,40 @@ Built for people whose work lives across hundreds of conversations and documents
### Development setup
Clone the repo and install in editable mode:
The project uses [uv](https://docs.astral.sh/uv/) for dev workflow. Install it once, then:
```bash
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v7 # active development branch
git checkout v8 # active development branch
# Create a virtual environment (Python 3.10+ required):
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install in editable mode with all optional extras:
pip install -e ".[all]"
# Create the project venv and install graphify + all extras + the dev group
# (pytest). uv installs the dev dependency group by default; pass --no-dev to
# skip it.
uv sync --all-extras
```
Verify the editable install:
```bash
graphify --version
python -c "import graphify; print(graphify.__file__)"
uv run graphify --version
uv run python -c "import graphify; print(graphify.__file__)"
```
### Running tests
```bash
pip install pytest
pytest tests/ -q # run the full suite
pytest tests/test_extract.py -q # one module
pytest tests/ -q -k "python" # filter by name
uv run pytest tests/ -q # run the full suite
uv run pytest tests/test_extract.py -q # one module
uv run pytest tests/ -q -k "python" # filter by name
```
> macOS note: the test suite includes both `sample.f90` and `sample.F90` fixtures. These collide on case-insensitive HFS+ / APFS file systems. Run on Linux or in a Docker container if you need to test both Fortran variants simultaneously.
### Git workflow
- Active development happens on the `v7` branch.
- Active development happens on the `v8` branch.
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
- Before opening a PR, run `pytest tests/ -q` and confirm it passes.
- Before opening a PR, run `uv run pytest tests/ -q` and confirm it passes.
- Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py` for any new language extractor.
### What to contribute
+1
View File
@@ -34,6 +34,7 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
| Prompt injection via source file content | During the semantic pass, source files are attacker-controlled text mixed into the LLM context. `_read_files()` in `llm.py` wraps every file in a hash-stamped `<untrusted_source path=... sha256=...>` delimiter block, the extraction system prompt instructs the model to treat that block as inert data and never as instructions, and `_neutralise_injection_sentinels()` defangs known chat-template/jailbreak tokens (`<\|im_start\|>`, `[INST]`, `<<SYS>>`, forged `</untrusted_source>`, etc.) before insertion. This is the table-stakes defense (issue #1210): it does not make injection impossible, but changes it from "works on first try" to "requires evasion." |
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
+5
View File
@@ -7,6 +7,8 @@ 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.
Code files are not sent to the LLM semantic extractor in the normal pipeline. If a corpus contains only code files, Pass 3 is skipped entirely; semantic extraction is reserved for docs, papers, images, and transcripts.
**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.
@@ -86,6 +88,9 @@ The output `graph.json` uses NetworkX's node-link format. Each node has:
- `file_type` — `code`, `document`, `paper`, `image`, `rationale`
- `source_file` — where it came from
See [RFC: file-level node summaries](node-summaries-rfc.md) for two proposed
ways to add compact optional summaries for AI navigation.
Each edge has:
- `source`, `target` — node IDs
- `relation` — verb phrase (e.g. `calls`, `imports`, `implements`, `semantically_similar_to`)
+186
View File
@@ -0,0 +1,186 @@
# RFC: file-level node summaries
This RFC proposes an optional way for graphify to expose compact file-level
summaries for AI coding agents.
## Problem
`graph.json` gives agents graph structure, source files, node labels, and
relationships. That helps avoid reading an entire repository, but agents still
often need to inspect raw files just to answer a basic navigation question:
> What is this file or node responsible for?
A short summary near the graph node could reduce repeated file reads during
`graphify query`, `graphify explain`, MCP node lookup, and graph navigation.
## Goals
- Help agents choose relevant files with less context.
- Preserve graphify's offline, deterministic behavior by default.
- Keep the first implementation small and reviewable.
- Avoid adding long prose to `GRAPH_REPORT.md`.
- Leave room for a future opt-in LLM-generated summary backend.
## Non-goals
- Summarizing every function, method, or local symbol in the first version.
- Calling an LLM or remote API by default.
- Replacing `graphify explain`; summaries should make `explain` more useful.
- Turning `GRAPH_REPORT.md` into a full per-file index.
## Shared constraints for either option
- Start with file-level nodes only.
- Keep each summary bounded, for example one sentence or roughly 200-300
characters.
- Generate deterministic summaries first from existing local signal:
module docstrings, top comments, exported symbols, imports, relation counts,
and community/context data.
- Do not emit summaries by default until the storage model is agreed on.
- Display a summary in `graphify explain <node>` when one exists.
- Include summaries in `graphify serve` / MCP node lookup when one exists.
## Proposed summary contents
Each file-level summary should give an agent enough signal to decide whether to
inspect the file, without replacing the file or bloating graph output.
Recommended fields:
| Field | Why it helps agents |
| --- | --- |
| `summary` | One bounded sentence describing the file's responsibility. This is the main token-saving field. |
| `source_file` | Lets the agent jump to the right file without resolving a node ID manually. |
| `label` | Keeps the summary readable in CLI, MCP, and UI contexts. |
| `generated_by` | Distinguishes deterministic summaries from future LLM-generated summaries. |
| `summary_version` | Allows the format to evolve without guessing how an older summary was produced. |
Recommended signal inside the `summary` sentence:
| Signal | Why it belongs in the sentence |
| --- | --- |
| Module docstring or top comment | Usually the highest-quality human-authored purpose statement. |
| Exported classes/functions/symbols | Tells the agent what API surface the file provides. |
| Important imports or dependencies | Reveals whether the file belongs to auth, database, UI, CLI, test, etc. |
| Dominant graph relations | Shows whether the file mainly calls, imports, defines, contains, or references other nodes. |
| Community or nearby hub label | Gives architectural context without reading the whole community report. |
| Source location coverage when available | Helps distinguish a file-level summary from a symbol-level explanation. |
Example:
```json
{
"label": "extract.py",
"source_file": "graphify/extract.py",
"summary": "Extracts source files into graph nodes and relationships; defines language parsers and import/call extraction helpers.",
"generated_by": "deterministic",
"summary_version": 1
}
```
The summary should not include long call chains, full dependency lists, raw code,
or every symbol in the file. Those details already belong in the graph and can
be fetched through `graphify explain`, `graphify query`, or direct file reads
when needed.
## Option A: `summary` attribute in `graph.json`
Add an optional `summary` field to file-level nodes:
```json
{
"id": "graphify_extract",
"label": "extract.py",
"file_type": "code",
"source_file": "graphify/extract.py",
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
}
```
Possible user flow:
```bash
graphify . --summarize-nodes
graphify explain "extract.py"
```
Pros:
- Single artifact for graph consumers.
- Matches NetworkX node attributes and existing node metadata.
- Easy for `explain`, `serve`, visualizers, and MCP tools to consume.
- No sidecar freshness or node-ID join logic.
Cons:
- Adds text to the core graph artifact.
- Expands the graph schema surface.
- Consumers that dump all of `graph.json` into an LLM context would pay for all
summaries at once.
## Option B: sidecar `node-summaries.json`
Write summaries to a separate artifact keyed by node ID:
```json
{
"version": 1,
"generator": "deterministic",
"nodes": {
"graphify_extract": {
"label": "extract.py",
"source_file": "graphify/extract.py",
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
}
}
}
```
Possible user flow:
```bash
graphify summarize
graphify explain "extract.py"
```
Pros:
- Keeps `graph.json` lean and topology-focused.
- Makes summaries clearly optional.
- Can be regenerated independently.
- Provides a natural place for future generator metadata.
Cons:
- Adds a second artifact that consumers must discover and load.
- Introduces freshness and synchronization questions.
- Every consumer that wants summaries must join by node ID.
## Suggested first implementation once storage is chosen
1. Add deterministic file-level summary generation.
2. Store summaries using the selected option.
3. Surface summaries in `graphify explain`.
4. Surface summaries in `graphify serve` / MCP node lookup.
5. Add tests for default behavior, generated summaries, missing summaries, and
bounded summary length.
## Follow-up ideas
- Add opt-in LLM-generated summaries with explicit provider/backend selection.
- Extend summaries to class or module-level nodes if file-level summaries prove
useful.
- Allow `graphify query` to include summaries for returned nodes under a budget.
- Add cache/freshness metadata if summaries are generated separately from the
main graph.
## Questions for maintainers and users
1. Should graphify prefer one artifact (`graph.json`) or keep generated text in a
sidecar?
2. Should deterministic file-level summaries be generated during graph creation,
or only through an explicit command such as `graphify summarize`?
3. Is `summary` the right term, or would `synopsis` better communicate a short,
bounded description?
4. What summary length budget would be acceptable for large repositories?
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+572
View File
@@ -0,0 +1,572 @@
<p align="center">
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇷 <a href="README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a>
</p>
<p align="center">
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></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=v8" 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://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
</p>
<div dir="rtl">
**یک مهارت برای دستیار کدنویسی هوش مصنوعی.** `/graphify` را در Claude Code، Codex، OpenCode، Kilo Code، Cursor، Gemini CLI، GitHub Copilot CLI، VS Code Copilot Chat، Aider، Amp، OpenClaw، Factory Droid، Trae، Hermes، Kimi Code، Kiro، Pi، Devin CLI یا Google Antigravity تایپ کنید — تمام پروژه‌تان را می‌خواند، یک گراف دانش می‌سازد، و ساختاری که نمی‌دانستید وجود دارد را به شما بازمی‌گرداند. کدبیس را سریع‌تر درک کنید. «چرا»ی پشت تصمیمات معماری را کشف کنید.
کاملاً چندوجهی. کد، PDF، مارک‌داون، اسکرین‌شات، نمودار، عکس وایت‌بورد، تصاویر به زبان‌های دیگر، یا فایل‌های ویدئو و صوتی بریزید — graphify مفاهیم و روابط را از همه آن‌ها استخراج کرده و در یک گراف به هم متصل می‌کند. ویدئوها به‌صورت محلی با Whisper رونویسی می‌شوند. ۳۶ زبان برنامه‌نویسی از طریق tree-sitter AST پشتیبانی می‌شوند.
> Andrej Karpathy یک پوشه `/raw` نگه می‌دارد که در آن مقالات، توییت‌ها، اسکرین‌شات‌ها و یادداشت‌ها می‌ریزد. graphify پاسخ آن مشکل است — **۷۱.۵ برابر** کمتر توکن در هر پرس‌وجو در مقایسه با خواندن فایل‌های خام، در طول جلسات پایدار، و صادق در مورد آنچه پیدا شده در برابر آنچه استنباط شده است.
</div>
```
/graphify .
```
<div dir="rtl">
همین. سه فایل دریافت می‌کنید:
</div>
```
graphify-out/
├── graph.html در هر مرورگری باز کنید — روی گره‌ها کلیک کنید، فیلتر کنید، جستجو کنید
├── GRAPH_REPORT.md نکات کلیدی: مفاهیم محوری، اتصالات شگفت‌انگیز، سؤالات پیشنهادی
└── graph.json گراف کامل — هر زمان بدون نیاز به بازخوانی فایل‌ها پرس‌وجو کنید
```
<div dir="rtl">
برای یک صفحه معماری خوانا با نمودارهای جریان فراخوانی Mermaid، اجرا کنید:
</div>
```bash
graphify export callflow-html
```
---
<div dir="rtl">
## پیش‌نیازها
</div>
| پیش‌نیاز | حداقل | بررسی | نصب |
|---|---|---|---|
| Python | ۳.۱۰+ | `python --version` | [python.org](https://www.python.org/downloads/) |
| uv *(پیشنهادی)* | هر نسخه | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| pipx *(جایگزین)* | هر نسخه | `pipx --version` | `pip install pipx` |
<div dir="rtl">
**نصب سریع macOS (Homebrew):**
</div>
```bash
brew install python@3.12 uv
```
<div dir="rtl">
**نصب سریع Windows:**
</div>
```powershell
winget install astral-sh.uv
```
<div dir="rtl">
**Ubuntu/Debian:**
</div>
```bash
sudo apt install python3.12 python3-pip pipx
# یا نصب uv:
curl -LsSf https://astral.sh/uv/install.sh | sh
```
---
<div dir="rtl">
## نصب
> **بسته رسمی:** بسته PyPI به نام `graphifyy` است (با دو y). سایر بسته‌های `graphify*` در PyPI وابسته به این پروژه نیستند. دستور CLI همچنان `graphify` است.
**مرحله ۱ — نصب بسته:**
</div>
```bash
# پیشنهادی (uv به‌طور خودکار graphify را در PATH قرار می‌دهد):
uv tool install graphifyy
# جایگزین‌ها:
pipx install graphifyy
pip install graphifyy # ممکن است نیاز به تنظیم PATH داشته باشد — یادداشت زیر را ببینید
```
<div dir="rtl">
**مرحله ۲ — ثبت مهارت در دستیار هوش مصنوعی:**
</div>
```bash
graphify install
```
<div dir="rtl">
همین. دستیار هوش مصنوعی‌تان را باز کنید و `/graphify .` تایپ کنید.
برای نصب مهارت دستیار در مخزن جاری به‌جای پروفایل کاربری، `--project` اضافه کنید:
</div>
```bash
graphify install --project
graphify install --project --platform codex
```
<div dir="rtl">
> **یادداشت PowerShell:** از `graphify .` استفاده کنید نه `/graphify .` — اسلش ابتدایی در PowerShell جداکننده مسیر است.
> **`graphify: command not found`؟** از `uv tool install graphifyy` یا `pipx install graphifyy` استفاده کنید — هر دو CLI را به‌طور خودکار در PATH قرار می‌دهند.
### انتخاب پلتفرم
</div>
| پلتفرم | دستور نصب |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install` (تشخیص خودکار) یا `graphify install --platform windows` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| Kilo Code | `graphify install --platform kilo` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify install --platform pi` |
| Cursor | `graphify cursor install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
<div dir="rtl">
### افزونه‌های اختیاری
فقط آنچه نیاز دارید نصب کنید:
</div>
| افزونه | چه چیزی اضافه می‌کند | نصب |
|---|---|---|
| `pdf` | استخراج PDF | `uv tool install "graphifyy[pdf]"` |
| `office` | پشتیبانی از `.docx` و `.xlsx` | `uv tool install "graphifyy[office]"` |
| `google` | رندرینگ Google Sheets | `uv tool install "graphifyy[google]"` |
| `video` | رونویسی ویدئو/صوت | `uv tool install "graphifyy[video]"` |
| `mcp` | سرور MCP stdio | `uv tool install "graphifyy[mcp]"` |
| `neo4j` | پشتیبانی از Neo4j | `uv tool install "graphifyy[neo4j]"` |
| `ollama` | استنتاج محلی Ollama | `uv tool install "graphifyy[ollama]"` |
| `openai` | OpenAI / APIهای سازگار با OpenAI | `uv tool install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
| `anthropic` | Anthropic Claude API | `uv tool install "graphifyy[anthropic]"` |
| `bedrock` | AWS Bedrock (از IAM استفاده می‌کند) | `uv tool install "graphifyy[bedrock]"` |
| `sql` | استخراج طرح SQL | `uv tool install "graphifyy[sql]"` |
| `all` | همه موارد بالا | `uv tool install "graphifyy[all]"` |
---
<div dir="rtl">
## دستیار را همیشه از گراف استفاده کنید
پس از ساخت گراف، یک بار در پروژه‌تان اجرا کنید:
</div>
| پلتفرم | دستور |
|----------|---------|
| Claude Code | `graphify claude install` |
| CodeBuddy | `graphify codebuddy install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| Kilo Code | `graphify kilo install` |
| GitHub Copilot CLI | `graphify copilot install` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify aider install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Amp | `graphify amp install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
<div dir="rtl">
این یک فایل پیکربندی کوچک می‌نویسد که به دستیارتان می‌گوید برای سؤالات مربوط به کدبیس، گراف دانش را مشورت بگیرد. برای حذف graphify از همه پلتفرم‌ها به یکباره: `graphify uninstall` (با `--purge` برای حذف `graphify-out/` نیز).
---
## محتوای گزارش
- **گره‌های اصلی** — پرارتباط‌ترین مفاهیم پروژه. همه چیز از این‌ها عبور می‌کند.
- **اتصالات شگفت‌انگیز** — پیوندهایی بین چیزهایی که در فایل‌ها یا ماژول‌های مختلف زندگی می‌کنند. بر اساس میزان غیرمنتظره بودن رتبه‌بندی شده.
- **«چرا»** — نظرات درون‌خطی (`# NOTE:`، `# WHY:`، `# HACK:`)، داک‌استرینگ‌ها و منطق طراحی از اسناد به‌عنوان گره‌های جداگانه مرتبط با کدی که توضیح می‌دهند استخراج می‌شوند.
- **سؤالات پیشنهادی** — ۴ تا ۵ سؤال که گراف به‌طور منحصربه‌فرد می‌تواند پاسخ دهد.
- **برچسب‌های اطمینان** — هر رابطه استنباط‌شده با `EXTRACTED`، `INFERRED` یا `AMBIGUOUS` علامت‌گذاری می‌شود. همیشه می‌دانید چه چیزی پیدا شده در برابر چه چیزی حدس زده شده.
---
## فایل‌های پشتیبانی‌شده
</div>
| نوع | پسوندها |
|------|-----------|
| کد (۳۶ دستور زبان tree-sitter) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .vue .svelte .dart` و بیشتر |
| اسناد | `.md .mdx .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (نیاز به `graphifyy[office]`) |
| PDF | `.pdf` |
| تصاویر | `.png .jpg .webp .gif` |
| ویدئو / صوت | `.mp4 .mov .mp3 .wav` و بیشتر (نیاز به `graphifyy[video]`) |
| YouTube / URLها | هر URL ویدئویی (نیاز به `graphifyy[video]`) |
<div dir="rtl">
کد به‌صورت محلی با tree-sitter بدون هیچ فراخوانی API استخراج می‌شود. بقیه از طریق API مدل دستیار هوش مصنوعی شما پردازش می‌شوند.
---
## دستورات رایج
</div>
```bash
/graphify . # ساخت گراف برای پوشه جاری
/graphify ./docs --update # فقط فایل‌های تغییریافته را مجدداً استخراج کن
/graphify . --cluster-only # خوشه‌بندی مجدد بدون استخراج مجدد
/graphify . --no-viz # فقط گزارش + JSON، بدون HTML
/graphify . --wiki # ساخت ویکی مارک‌داون از گراف
graphify export callflow-html # HTML معماری/جریان فراخوانی Mermaid
/graphify query "چه چیزی auth را به پایگاه داده متصل می‌کند؟"
/graphify path "UserService" "DatabasePool"
/graphify explain "RateLimiter"
/graphify add https://arxiv.org/abs/1706.03762 # یک مقاله را واکشی و اضافه کن
/graphify add <youtube-url> # رونویسی و اضافه کردن ویدئو
graphify hook install # بازسازی خودکار پس از هر commit
graphify merge-graphs a.json b.json # ترکیب دو گراف
graphify prs # داشبورد PR: وضعیت CI، بررسی، تأثیر گراف
graphify prs 42 # بررسی عمیق PR شماره ۴۲
graphify prs --triage # رتبه‌بندی صف بررسی با هوش مصنوعی
```
<div dir="rtl">
[مرجع کامل دستورات](#full-command-reference) را ببینید.
---
## نادیده گرفتن فایل‌ها
یک `.graphifyignore` در ریشه پروژه بسازید — همان سینتکس `.gitignore`، از جمله نفی با `!`.
**`.gitignore` به‌طور خودکار رعایت می‌شود.** اگر `.graphifyignore` در یک دایرکتوری وجود نداشته باشد، graphify به `.gitignore` آن دایرکتوری بازمی‌گردد.
</div>
```
# .graphifyignore
node_modules/
dist/
*.generated.py
# فقط src/ را ایندکس کن، بقیه را نادیده بگیر
*
!src/
!src/**
```
---
<div dir="rtl">
## تنظیمات تیمی
`graphify-out/` برای commit شدن در git طراحی شده تا همه در تیم با یک نقشه شروع کنند.
**افزودن‌های پیشنهادی به `.gitignore`:**
</div>
```
graphify-out/cost.json # فقط محلی
# graphify-out/cache/ # اختیاری: برای سرعت commit کنید، برای کوچک نگه داشتن repo حذف کنید
```
<div dir="rtl">
**جریان کار:**
۱. یک نفر `/graphify .` اجرا می‌کند و `graphify-out/` را commit می‌کند.
۲. همه pull می‌کنند — دستیارشان فوراً گراف را می‌خواند.
۳. `graphify hook install` را اجرا کنید تا پس از هر commit به‌طور خودکار بازسازی شود.
۴. وقتی اسناد یا مقالات تغییر کردند، `/graphify --update` اجرا کنید.
---
## استفاده مستقیم از گراف
</div>
```bash
# پرس‌وجو از گراف در ترمینال
graphify query "جریان احراز هویت را نشان بده"
graphify query "چه چیزی DigestAuth را به Response متصل می‌کند؟" --graph graphify-out/graph.json
# نمایش گراف به‌عنوان سرور MCP
python -m graphify.serve graphify-out/graph.json
# یا سرویس‌دهی از طریق HTTP برای دسترسی تیمی:
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
```
<div dir="rtl">
سرور MCP دسترسی ساختاریافته می‌دهد: `query_graph`، `get_node`، `get_neighbors`، `shortest_path`، `list_prs`، `get_pr_impact`، `triage_prs`.
---
## متغیرهای محیطی
اینها فقط برای **استخراج بدون نمایشگر / CI** (`graphify extract`) لازم هستند. هنگام اجرا از طریق مهارت `/graphify` داخل IDE، API مدل توسط جلسه IDE شما تأمین می‌شود.
</div>
| متغیر | استفاده | شرط لزوم |
|---|---|---|
| `ANTHROPIC_API_KEY` | بک‌اند Claude (Anthropic) | `--backend claude` |
| `GEMINI_API_KEY` یا `GOOGLE_API_KEY` | بک‌اند Google Gemini | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI یا APIهای سازگار | `--backend openai` |
| `DEEPSEEK_API_KEY` | بک‌اند DeepSeek | `--backend deepseek` |
| `MOONSHOT_API_KEY` | بک‌اند Kimi Code | `--backend kimi` |
| `OLLAMA_BASE_URL` | URL استنتاج محلی Ollama | `--backend ollama` |
| `AZURE_OPENAI_API_KEY` | بک‌اند Azure OpenAI | `--backend azure` |
| `GRAPHIFY_MAX_WORKERS` | تعداد thread های موازی AST | اختیاری |
| `GRAPHIFY_FORCE` | بازسازی اجباری گراف | اختیاری |
| `GRAPHIFY_QUERY_LOG_DISABLE` | برای غیرفعال کردن ثبت پرس‌وجو `1` تنظیم کنید | اختیاری |
---
<div dir="rtl">
## حریم خصوصی
- **فایل‌های کد** — به‌صورت محلی از طریق tree-sitter پردازش می‌شوند. هیچ چیزی دستگاه شما را ترک نمی‌کند.
- **ویدئو / صوت** — به‌صورت محلی با faster-whisper رونویسی می‌شوند. هیچ چیزی دستگاه شما را ترک نمی‌کند.
- **اسناد، PDF‌ها، تصاویر** — برای استخراج معنایی به API مدل دستیار هوش مصنوعی شما ارسال می‌شوند.
- بدون تله‌متری، بدون ردیابی استفاده، بدون آنالیتیکس.
---
## عیب‌یابی
**`graphify: command not found` پس از `pip install graphifyy`**
pip اسکریپت‌ها را در دایرکتوری bin کاربر نصب می‌کند که ممکن است در PATH نباشد:
- macOS: `~/Library/Python/3.x/bin` را به PATH در `~/.zshrc` اضافه کنید
- Linux: `~/.local/bin` را به PATH در `~/.bashrc` اضافه کنید
- یا از `uv tool install graphifyy` / `pipx install graphifyy` استفاده کنید.
**`/graphify .` در PowerShell "path not recognized" نشان می‌دهد**
PowerShell `/` ابتدایی را به‌عنوان جداکننده مسیر در نظر می‌گیرد. از `graphify .` (بدون اسلش) در Windows استفاده کنید.
**گراف پس از `--update` یا بازسازی گره کمتری دارد**
اگر یک refactor فایل‌ها را حذف کرده، گره‌های قدیمی باقی می‌مانند. `--force` (یا `GRAPHIFY_FORCE=1`) را پاس دهید:
</div>
```bash
graphify extract . --force
```
<div dir="rtl">
**استخراج برای اسناد یا PDF‌ها گره/یال خالی برمی‌گرداند**
اسناد، PDF‌ها و تصاویر به یک فراخوانی LLM نیاز دارند. بررسی کنید API key تنظیم شده و بک‌اند صحیح است:
</div>
```bash
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
---
<div dir="rtl">
## مرجع کامل دستورات
</div>
```
/graphify # اجرا روی دایرکتوری جاری
/graphify ./raw # اجرا روی پوشه مشخص
/graphify ./raw --mode deep # استخراج رابطه‌های عمیق‌تر
/graphify ./raw --update # فقط فایل‌های تغییریافته را مجدداً استخراج کن
/graphify ./raw --directed # حفظ جهت یال‌ها
/graphify ./raw --cluster-only # خوشه‌بندی مجدد روی گراف موجود
/graphify ./raw --no-viz # بدون HTML بصری‌سازی
/graphify ./raw --obsidian # تولید Obsidian vault
/graphify ./raw --wiki # ساخت ویکی مارک‌داون قابل خزیدن برای agent
/graphify ./raw --svg # خروجی graph.svg
/graphify ./raw --graphml # خروجی برای Gephi / yEd
/graphify ./raw --neo4j # تولید cypher.txt برای Neo4j
/graphify ./raw --watch # همگام‌سازی خودکار با تغییر فایل‌ها
/graphify ./raw --mcp # شروع سرور MCP stdio
/graphify add https://arxiv.org/abs/1706.03762
/graphify add <video-url>
/graphify query "چه چیزی attention را به optimizer متصل می‌کند؟"
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
graphify uninstall # حذف از همه پلتفرم‌ها
graphify uninstall --purge # همچنین graphify-out/ را حذف کن
graphify hook install # hook های post-commit + post-checkout
graphify hook uninstall
graphify hook status
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify codex install # AGENTS.md + PreToolUse hook (Codex)
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
graphify amp install # فایل مهارت (Amp)
graphify kiro install # .kiro/skills/ + .kiro/steering/ (Kiro)
graphify devin install # فایل مهارت + .windsurf/rules/ (Devin CLI)
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
graphify extract ./docs # استخراج بدون نمایشگر برای CI
graphify extract ./docs --backend gemini # بک‌اند صریح
graphify extract ./docs --backend ollama # Ollama محلی - بدون نیاز به API key
graphify extract ./docs --backend bedrock # AWS Bedrock از طریق IAM
graphify extract --postgres "postgresql://user:pass@host/db" # طرح PostgreSQL زنده
graphify prs # داشبورد PR
graphify prs 42 # بررسی عمیق PR شماره ۴۲
graphify prs --triage # رتبه‌بندی هوش مصنوعی
graphify prs --conflicts # PR هایی که جوامع گراف را به اشتراک می‌گذارند
graphify export callflow-html # HTML معماری/جریان فراخوانی
graphify merge-graphs a.json b.json --out merged.json
graphify --version
```
---
<div dir="rtl">
## بیشتر بدانید
- [نحوه عملکرد](../../docs/how-it-works.md) — پایپ‌لاین استخراج، تشخیص جامعه، امتیازدهی اطمینان، معیارها
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — تقسیم‌بندی ماژول‌ها، نحوه اضافه کردن زبان جدید
- [یکپارچه‌سازی‌های اختیاری](../../docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
---
## ساخته‌شده روی graphify — Penpax
[**Penpax**](https://graphifylabs.ai) لایه همیشه‌روشن ساخته‌شده روی graphify است — همان رویکرد گراف را بر کل زندگی کاری شما اعمال می‌کند: جلسات، تاریخچه مرورگر، ایمیل‌ها، فایل‌ها و کد، به‌صورت مداوم در پس‌زمینه به‌روزرسانی می‌شود.
ساخته‌شده برای کسانی که کارشان در صدها مکالمه و سند پراکنده است. بدون ابر، کاملاً روی دستگاه.
**آزمایش رایگان به‌زودی راه‌اندازی می‌شود.** [به لیست انتظار بپیوندید ←](https://graphifylabs.ai)
---
</div>
<details>
<summary>مشارکت در پروژه</summary>
<div dir="rtl">
### راه‌اندازی محیط توسعه
این پروژه از [uv](https://docs.astral.sh/uv/) برای جریان کار توسعه استفاده می‌کند. یک بار آن را نصب کنید، سپس:
</div>
```bash
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v8 # شاخه توسعه فعال
uv sync --all-extras
```
<div dir="rtl">
### اجرای تست‌ها
</div>
```bash
uv run pytest tests/ -q # اجرای کل مجموعه
uv run pytest tests/test_extract.py -q # یک ماژول
```
<div dir="rtl">
### جریان کار Git
- توسعه فعال روی شاخه `v8` انجام می‌شود.
- سبک commit: `fix: <توضیح>` / `feat: <توضیح>` / `docs: <توضیح>`
- قبل از باز کردن PR، `uv run pytest tests/ -q` اجرا کنید و از موفقیت آن مطمئن شوید.
### چه چیزی مشارکت کنیم
**نمونه‌های کاری** مفیدترین نوع مشارکت هستند. `/graphify` را روی یک corpus واقعی اجرا کنید، خروجی را در `worked/{slug}/` ذخیره کنید، یک `review.md` صادقانه بنویسید که چه چیزهایی درست و نادرست بوده، و یک PR باز کنید.
**باگ‌های استخراج** — یک issue با فایل ورودی، آیتم کش (`graphify-out/cache/`) و آنچه اشتباه یا حذف شده باز کنید.
برای مسئولیت‌های ماژول و نحوه اضافه کردن زبان جدید [ARCHITECTURE.md](../../ARCHITECTURE.md) را ببینید.
</div>
</details>
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+77
View File
@@ -0,0 +1,77 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a>
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
</p>
**Kasanayan para sa mga AI coding assistant.** I-type ang `/graphify` sa Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, o Google Antigravity — binabasa nito ang iyong mga file, gumagawa ng knowledge graph, at ibinabalik sa iyo ang mga istrukturang hindi mo alam na nandoon pala. Maunawaan ang codebase nang mas mabilis. Tuklasin ang "bakit" sa likod ng mga desisyon sa arkitektura.
Ganap na multimodal. Magdagdag ng code, PDF, markdown, mga screenshot, diagram, larawan ng whiteboard, mga imahe sa ibang wika, o mga video at audio file — kine-extract ng graphify ang mga konsepto at relasyon mula sa lahat ng ito at pinag-uugnay ang mga ito sa iisang graph. Ang mga video ay tina-transcribe nang lokal gamit ang Whisper. Sumusuporta ng 25 na programming language sa pamamagitan ng tree-sitter AST.
> Si Andrej Karpathy ay nagpapanatili ng `/raw` folder kung saan nilalagay niya ang mga papel, tweet, screenshot, at tala. Ang graphify ang sagot sa problemang iyon — **71.5x** na mas kaunting token bawat query kumpara sa pagbasa ng mga raw file, at persistent sa pagitan ng mga session.
```
/graphify .
```
```
graphify-out/
├── graph.html interactive na graph — buksan sa kahit anong browser
├── GRAPH_REPORT.md mga god node, nakakagulat na koneksyon, mga iminumungkahing tanong
├── graph.json persistent na graph — maaaring i-query kahit pagkalipas ng mga linggo
└── cache/ SHA256 cache — ang mga pag-uulit ay nagpo-proseso lang ng mga nabagong file
```
## Paano Gumagana
Gumagana ang graphify sa tatlong pass. Una, isang deterministikong AST pass ang nag-e-extract ng istruktura mula sa mga code file nang walang LLM. Pagkatapos, ang mga video at audio file ay tina-transcribe nang lokal gamit ang faster-whisper. Panghuli, mga Claude sub-agent ang tumatakbo nang magkakasabay sa mga dokumento, papel, imahe, at transkripsyon. Ang mga resulta ay pinagsasama sa isang NetworkX graph, naka-cluster gamit ang Leiden, at ine-export bilang interactive na HTML, queryable na JSON, at audit report.
Ang bawat relasyon ay may label na `EXTRACTED`, `INFERRED` (may confidence score), o `AMBIGUOUS`.
## Pag-install
**Mga Kinakailangan:** Python 3.10+ at isa sa mga sumusunod: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) at iba pa.
```bash
uv tool install graphifyy && graphify install
# o gamit ang pipx
pipx install graphifyy && graphify install
# o pip
pip install graphifyy && graphify install
```
> **Opisyal na package:** Ang PyPI package ay pinangalanang `graphifyy`. Ang tanging opisyal na repository ay [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Paggamit
```
/graphify .
/graphify ./raw --update
/graphify query "ano ang nagkokonekta sa Attention at sa optimizer?"
/graphify path "DigestAuth" "Response"
graphify hook install
graphify update ./src
```
## Ano ang Makukuha Mo
**Mga god node** — mga konsepto na may pinakamataas na degree · **Mga nakakagulat na koneksyon** — naka-rank ayon sa score · **Mga iminumungkahing tanong** · **"Bakit"** — mga docstring at disenyo na rason ay ine-extract bilang mga node · **Token benchmark** — **71.5x** na mas kaunting token sa mixed corpus.
## Privacy
Ang mga code file ay prinoseso nang lokal sa pamamagitan ng tree-sitter AST. Ang mga video ay tina-transcribe nang lokal gamit ang faster-whisper. Walang telemetry.
## Binuo sa ibabaw ng graphify — Penpax
Ang [**Penpax**](https://graphifylabs.ai) ay ang enterprise layer sa ibabaw ng graphify. **Malapit nang magkaroon ng libreng trial.** [Sumali sa waitlist →](https://graphifylabs.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -1,6 +1,6 @@
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
+1 -1
View File
@@ -1,6 +1,6 @@
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+550 -35
View File
@@ -1,77 +1,592 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></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=v8" 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://clickpy.clickhouse.com/dashboard/graphifyy"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsql-clickhouse.clickhouse.com%2F%3Fquery%3DSELECT%2520concat%2528toString%2528round%2528sum%2528count%2529%2F1000%2529%2529%2C%2520%2527k%2527%2529%2520AS%2520c%2520FROM%2520pypi.pypi_downloads%2520WHERE%2520project%253D%2527graphifyy%2527%2520FORMAT%2520JSON%26user%3Ddemo&query=%24.data%5B0%5D.c&label=downloads&color=blue" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
</p>
**Навичка для ШІ-асистентів кодування.** Введіть `/graphify` у Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro або Google Antigravity — він читає ваші файли, будує граф знань і повертає вам структуру, про яку ви не знали. Розумійте кодову базу швидше. Знайдіть «чому» за архітектурними рішеннями.
<p align="center">
<a href="https://star-history.com/#safishamsi/graphify&Date">
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
</a>
</p>
Повністю мультимодальний. Додавайте код, PDF, markdown, знімки екрана, діаграми, фотографії дошок, зображення іншими мовами або відео- та аудіофайли — graphify витягує концепції та зв'язки з усього і з'єднує їх в один граф. Відео транскрибуються локально за допомогою Whisper. Підтримує 25 мов програмування через tree-sitter AST.
Введіть `/graphify` у своєму ШІ-асистенті для кодингу, і він нанесе весь ваш проект — код, документи, PDF, зображення, відео — на граф знань, який можна запитувати замість того, щоб шукати по файлах.
> Андрій Карпатій веде папку `/raw`, куди кладе статті, твіти, знімки екрана та нотатки. graphify — відповідь на цю проблему — **71,5x** менше токенів на запит порівняно з читанням сирих файлів, зберігається між сесіями.
Працює в Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi та Google Antigravity.
```
/graphify .
```
Це все. Ви отримуєте три файли:
```
graphify-out/
├── graph.html інтерактивний граф — відкрийте в будь-якому браузері
├── GRAPH_REPORT.md вузли-боги, несподівані зв'язки, запропоновані питання
├── graph.json постійний граф — можна запитувати через тижні
└── cache/ SHA256-кеш — повторні запуски обробляють лише змінені файли
├── graph.html відкрийте в будь-якому браузері — клікайте по вузлах, фільтруйте, шукайте
├── GRAPH_REPORT.md основне: ключові концепції, неочікувані зв’язки, запропоновані запитання
└── graph.json повний граф — запитуйте його будь-коли без повторного перечитування ваших файлів
```
## Як це працює
Для читабельної сторінки архітектури з діаграмами викликів Mermaid виконайте:
graphify працює в три проходи. Спочатку детерміністичний прохід AST витягує структуру з файлів коду без LLM. Потім відео та аудіофайли транскрибуються локально за допомогою faster-whisper. Нарешті субагенти Claude працюють паралельно над документами, статтями, зображеннями та транскрипціями. Результати об'єднуються в граф NetworkX, кластеризуються з Leiden і експортуються як інтерактивний HTML, JSON для запитів і звіт аудиту.
```bash
graphify export callflow-html
```
Кожен зв'язок позначений як `EXTRACTED`, `INFERRED` (з оцінкою впевненості) або `AMBIGUOUS`.
---
## Вимоги
| Вимога | Мінімум | Перевірка | Встановлення |
|---|---|---|---|
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
| uv *(рекомендовано)* | будь-яка | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| pipx *(альтернатива)* | будь-яка | `pipx --version` | `pip install pipx` |
**Швидке встановлення на macOS (Homebrew):**
```bash
brew install python@3.12 uv
```
**Швидке встановлення на Windows:**
```powershell
winget install astral-sh.uv
```
**Ubuntu/Debian:**
```bash
sudo apt install python3.12 python3-pip pipx
# або встановити uv:
curl -LsSf https://astral.sh/uv/install.sh | sh
```
---
## Встановлення
**Вимоги:** Python 3.10+ та одне з: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) та інші.
> **Офіційний пакет:** Пакет PyPI — `graphifyy` (подвійна y). Інші пакети `graphify*` на PyPI не є афілійованими. Команда CLI залишається `graphify`.
**Крок 1 — встановити пакет:**
```bash
uv tool install graphifyy && graphify install
# або з pipx
pipx install graphifyy && graphify install
# або pip
pip install graphifyy && graphify install
# Рекомендовано (uv автоматично додає graphify до PATH):
uv tool install graphifyy
# Альтернативи:
pipx install graphifyy
pip install graphifyy
```
> **Офіційний пакет:** Пакет PyPI називається `graphifyy`. Єдиний офіційний репозиторій — [safishamsi/graphify](https://github.com/safishamsi/graphify).
**Крок 2 — зареєструвати навичку у вашому ШІ-асистенті:**
## Використання
```
/graphify .
/graphify ./raw --update
/graphify query "що пов'язує Attention з оптимізатором?"
/graphify path "DigestAuth" "Response"
graphify hook install
graphify update ./src
```bash
graphify install
```
## Що ви отримуєте
Це все. Відкрийте асистента і введіть `/graphify .`
**Вузли-боги** — концепції з найвищим ступенем · **Несподівані зв'язки** — відсортовані за оцінкою · **Запропоновані питання** · **«Чому»** — рядки документації та обґрунтування дизайну витягнуті як вузли · **Бенчмарк токенів** — **71,5x** менше токенів на змішаному корпусі.
Щоб встановити навичку в поточний репозиторій замість профілю користувача, додайте `--project`:
```bash
graphify install --project
graphify install --project --platform codex
```
Встановлення на рівні проєкту записуються в поточну директорію, наприклад .claude/skills/graphify/SKILL.md або .agents/skills/graphify/SKILL.md, і виводять підказку git add для файлів, які можна закомітити. Команди для окремих платформ, що підтримують інсталяції на рівні проєкту, приймають той самий прапорець, наприклад graphify claude install --project або graphify codex install --project.
> **Примітка для PowerShell:** Використовуйте `graphify .` замість `/graphify .` — ведучий слеш є роздільником шляху в PowerShell.
> **`graphify: command not found`?** Використовуйте `uv tool install graphifyy` або `pipx install graphifyy` — обидва автоматично додають CLI до PATH. При використанні звичайного `pip` додайте `~/.local/bin` (Linux) або `~/Library/Python/3.x/bin` (Mac) до вашого PATH, або запустіть `python -m graphify`.
### Оберіть платформу
| Платформа | Команда встановлення |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kimi Code | `graphify install --platform kimi` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify install --platform pi` |
| Cursor | `graphify cursor install` |
| Google Antigravity | `graphify antigravity install` |
> Користувачам Codex: також додайте `multi_agent = true` під `[features]` у `~/.codex/config.toml`.
> Codex використовує `$graphify` замість `/graphify`.
### Додаткові пакети (опціонально)
Встановіть лише те, що потрібно:
| Пакет | Що додає | Встановлення |
|---|---|---|
| `pdf` | Вилучення PDF | `pip install "graphifyy[pdf]"` |
| `office` | Підтримка `.docx` та `.xlsx` | `pip install "graphifyy[office]"` |
| `google` | Рендеринг Google Sheets | `pip install "graphifyy[google]"` |
| `video` | Транскрипція відео/аудіо (faster-whisper + yt-dlp) | `pip install "graphifyy[video]"` |
| `mcp` | MCP stdio-сервер | `pip install "graphifyy[mcp]"` |
| `neo4j` | Підтримка надсилання до Neo4j | `pip install "graphifyy[neo4j]"` |
| `svg` | Експорт графу в SVG | `pip install "graphifyy[svg]"` |
| `leiden` | Виявлення спільнот Leiden (лише Python < 3.13) | `pip install "graphifyy[leiden]"` |
| `ollama` | Локальний вивід Ollama | `pip install "graphifyy[ollama]"` |
| `openai` | OpenAI / OpenAI-сумісні API | `pip install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `pip install "graphifyy[gemini]"` |
| `bedrock` | AWS Bedrock (використовує IAM, без API-ключа) | `pip install "graphifyy[bedrock]"` |
| `sql` | Вилучення SQL схем | `pip install "graphifyy[sql]"` |
| `all` | Все вищезазначене | `pip install "graphifyy[all]"` |
---
## Змусьте асистента завжди використовувати граф
Виконайте один раз у своєму проекті після побудови графу:
| Платформа | Команда |
|----------|---------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| GitHub Copilot CLI | `graphify copilot install` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify aider install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Trae CN | `graphify trae-cn install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Hermes | `graphify hermes install` |
| Kimi Code | `graphify install --platform kimi` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify pi install` |
| Google Antigravity | `graphify antigravity install` |
Це записує невеликий конфігураційний файл, який каже асистенту звертатися до графу знань для питань про кодову базу — надаючи перевагу локалізованим запитам на кшталт `graphify query "<питання>"` замість читання повного звіту або пошуку по сирих файлах. На платформах, що підтримують хуки з корисним навантаженням (Claude Code, Gemini CLI), хук спрацьовує автоматично перед пошуковими викликами інструментів і спрямовує асистента до графу. На інших (Codex, OpenCode, Cursor тощо) постійні файли інструкцій (`AGENTS.md`, `.cursor/rules/` тощо) забезпечують таке саме керівництво. `GRAPH_REPORT.md` все ще доступний для загального огляду архітектури.
Щоб видалити graphify з усіх платформ одразу: `graphify uninstall` (додайте `--purge`, щоб також видалити `graphify-out/`). Або скористайтеся командою для конкретної платформи (напр. `graphify claude uninstall`).
---
## Що є у звіті
- **Вузли-боги** — найбільш пов'язані концепції у вашому проекті. Через них проходить все.
- **Несподівані зв'язки** — зв'язки між речами з різних файлів або модулів. Відсортовані за ступенем несподіваності.
- **«Чому»** — рядкові коментарі (`# NOTE:`, `# WHY:`, `# HACK:`), рядки документації та обґрунтування дизайну з документів витягуються як окремі вузли, пов'язані з кодом, який вони пояснюють.
- **Запропоновані питання** — 4–5 питань, на які граф унікально здатний відповісти.
- **Теги впевненості** — кожен виведений зв'язок позначений як `EXTRACTED`, `INFERRED` або `AMBIGUOUS`. Ви завжди знаєте, що знайдено, а що виведено.
---
## Які файли підтримуються
| Тип | Розширення |
|------|-----------|
| Код (31 мова) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json` |
| Документи | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (потрібен `pip install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` (опціонально; потрібна автентифікація `gws` та `--google-workspace`; Sheets потребує `pip install graphifyy[google]`) |
| PDF | `.pdf` |
| Зображення | `.png .jpg .webp .gif` |
| Відео / Аудіо | `.mp4 .mov .mp3 .wav` та інші (потрібен `pip install graphifyy[video]`) |
| YouTube / URL | будь-який URL відео (потрібен `pip install graphifyy[video]`) |
Код витягується локально без API-викликів (AST через tree-sitter). Все інше обробляється через API моделі вашого ШІ-асистента.
Файли `.gdoc`, `.gsheet` та `.gslides` з Google Drive for desktop — це ярлики-посилання, а не вміст документів. Щоб включити нативні Google Docs, Sheets та Slides у безголове витягування, встановіть та автентифікуйте [`gws` CLI](https://github.com/googleworkspace/cli), потім запустіть:
```bash
pip install "graphifyy[google]" # потрібен для рендерингу таблиць Google Sheets
gws auth login -s drive
graphify extract ./docs --google-workspace
```
Також можна встановити `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify експортує ярлики в `graphify-out/converted/` як Markdown-сайдкари, а потім витягує ці файли.
---
## Часті команди
```bash
/graphify . # побудувати граф для поточної папки
/graphify ./docs --update # повторно витягнути лише змінені файли
/graphify . --cluster-only # перезапустити кластеризацію без повторного витягування
/graphify . --cluster-only --resolution 1.5 # більш дрібні спільноти
/graphify . --cluster-only --exclude-hubs 99 # виключити утилітарні суперхаби з рейтингів “god-node” вузлів-богів
/graphify . --no-viz # пропустити HTML, лише звіт + JSON
/graphify . --wiki # побудувати markdown-вікі з графу
graphify export callflow-html # Mermaid архітектура/flow-викликів HTML (автоматично регенерується на кожен git-коміт, якщо встановлений hook)
/graphify query "що пов'язує auth з базою даних?"
/graphify path "UserService" "DatabasePool"
/graphify explain "RateLimiter"
/graphify add https://arxiv.org/abs/1706.03762 # завантажити статтю і додати її
/graphify add <youtube-url> # транскрибувати і додати відео
graphify hook install # автоматичне перебудування при git-коміті
graphify merge-graphs a.json b.json # об'єднати два графи
graphify prs # дашборд PR: стан CI, статус рев’ю, мапінг worktree
graphify prs 42 # детальний огляд PR #42 з впливом на граф
graphify prs --triage # ШІ оцінює вашу чергу рев’ю (використовує будь-який налаштований бекенд)
graphify prs --conflicts # PR-и, що ділять спільні графові спільноти — ризик порядку злиття
```
Дивіться [повний довідник команд](#повний-довідник-команд) нижче.
---
## Ігнорування файлів
Створіть `.graphifyignore` у кореневій директорії проекту — той самий синтаксис, що й `.gitignore`, включно з запереченням `!`:
```
# .graphifyignore
node_modules/
dist/
*.generated.py
# індексувати лише src/, ігнорувати все інше
*
!src/
!src/**
```
---
## Налаштування для команди
`graphify-out/` призначений для коміту в git, щоб кожен у команді починав із картою.
**Рекомендовані доповнення до `.gitignore`:**
```
graphify-out/manifest.json # базується на mtime, ламається після git clone
graphify-out/cost.json # лише локальний
# graphify-out/cache/ # опціонально: комітьте для швидкості, пропустіть для меншого репо
```
**Робочий процес:**
1. Одна людина запускає `/graphify .` і комітить `graphify-out/`.
2. Усі виконують pull — їхній асистент одразу читає граф.
3. Запустіть `graphify hook install` для автоматичного перебудування після кожного коміту (лише AST, без витрат API). Це також налаштовує git merge driver, щоб `graph.json` ніколи не залишався з маркерами конфліктів — два розробники, що комітять одночасно, отримають автоматично об'єднані графи.
4. Коли документи або статті змінюються, запустіть `/graphify --update`, щоб оновити ці вузли.
---
## Використання графу напряму
```bash
# запит до графу з терміналу
graphify query "покажи потік автентифікації"
graphify query "що пов'язує DigestAuth з Response?" --graph graphify-out/graph.json
# відкрити граф як MCP-сервер (для повторного доступу через інструменти)
python -m graphify.serve graphify-out/graph.json
# зареєструвати в Kimi Code:
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
```
MCP-сервер надає асистенту структурований доступ: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
> **Примітка для WSL / Linux:** Ubuntu постачає `python3`, а не `python`. Використовуйте venv, щоб уникнути конфліктів:
> ```bash
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
> ```
---
## Змінні середовища
Потрібні лише для **headless / CI витягування** (`graphify extract`). При запуску через навичку `/graphify` у вашому IDE API моделі надається сесією IDE — додаткових ключів не потрібно.
| Змінна | Використання | Коли потрібна |
|---|---|---|
| `ANTHROPIC_API_KEY` | Backend Claude (Anthropic) | `--backend claude` |
| `ANTHROPIC_BASE_URL` | URL Anthropic-сумісного endpoint (LiteLLM proxy, шлюзи, ...) | `--backend claude` (типово: `https://api.anthropic.com`) |
| `ANTHROPIC_MODEL` | Назва моделі для backend Claude — для власних endpoint використовуйте назву/псевдонім моделі вашого сервера | `--backend claude` (типово: `claude-sonnet-4-6`) |
| `GEMINI_API_KEY` або `GOOGLE_API_KEY` | Backend Google Gemini | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI або OpenAI-сумісні API | `--backend openai` (локальні сервери приймають будь-яке непорожнє значення) |
| `OPENAI_BASE_URL` | URL OpenAI-сумісного сервера (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (типово: `https://api.openai.com/v1`) |
| `OPENAI_MODEL` | Назва моделі для backend OpenAI — для self-hosted серверів використовуйте назву/псевдонім моделі, яку надає ваш сервер (див. його endpoint `/v1/models`), напр. `LFM2.5-8B-A1B-UD-Q4_K_XL` для llama.cpp | `--backend openai` (типово: `gpt-4.1-mini`) |
| `DEEPSEEK_API_KEY` | Backend DeepSeek | `--backend deepseek` |
| `MOONSHOT_API_KEY` | Backend Kimi Code | `--backend kimi` |
| `OLLAMA_BASE_URL` | URL локального виводу Ollama | `--backend ollama` (типово: `http://localhost:11434`) |
| `OLLAMA_MODEL` | Назва моделі Ollama | `--backend ollama` (типово: автовизначення) |
| `GRAPHIFY_OLLAMA_NUM_CTX` | Перевизначити розмір KV-кеш вікна Ollama | опціонально — автоматично за замовчуванням |
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | Хвилини утримання моделі Ollama завантаженою | опціонально — встановіть `0` для вивантаження після кожного шматка |
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — стандартний ланцюг облікових даних | `--backend bedrock` (без API-ключа, використовує IAM) |
| `GRAPHIFY_MAX_WORKERS` | Кількість потоків паралелізму AST | опціонально — також прапор `--max-workers` |
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Підвищити ліміт виводу для щільних корпусів | опціонально — напр. `32768` для великих файлів |
| `GRAPHIFY_API_TIMEOUT` | HTTP тайм-аут у секундах (типово: 600) | опціонально — також прапор `--api-timeout` |
| `GRAPHIFY_FORCE` | Примусове перебудування графу навіть із меншою кількістю вузлів | опціонально — також прапор `--force` |
| `GRAPHIFY_GOOGLE_WORKSPACE` | Автоввімкнення експорту Google Workspace | опціонально — встановіть в `1` |
| `GRAPHIFY_TRIAGE_BACKEND` | Backend для `graphify prs --triage` | опціонально — автовизначення з наявних ключів |
| `GRAPHIFY_TRIAGE_MODEL` | Перевизначення моделі для triage | опціонально — напр. `claude-opus-4-7` |
---
## Конфіденційність
Файли коду обробляються локально через tree-sitter AST. Відео транскрибуються локально за допомогою faster-whisper. Без телеметрії.
- **Файли коду** — обробляються локально через tree-sitter. Нічого не покидає ваш комп'ютер.
- **Відео / аудіо** — транскрибуються локально за допомогою faster-whisper. Нічого не покидає ваш комп'ютер.
- **Документи, PDF, зображення** — надсилаються до вашого ШІ-асистента для семантичного витягування (через навичку `/graphify`, використовуючи модель, що запущена у вашому IDE). Безголове `graphify extract` потребує `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), `DEEPSEEK_API_KEY` (DeepSeek), запущеного екземпляра Ollama (`OLLAMA_BASE_URL`), AWS-облікових даних через стандартний ланцюг провайдерів (Bedrock — без API-ключа, використовує IAM) або бінарного файлу `claude` CLI (Claude Code — без API-ключа, використовує вашу підписку Claude). Прапор `--dedup-llm` використовує той самий ключ.
- Без телеметрії, без відстеження використання, без аналітики.
---
## Вирішення проблем
**`graphify: command not found` після `pip install graphifyy`**
pip встановлює скрипти в директорію bin для користувача, яка може не бути в PATH. Виправлення:
- macOS: додайте `~/Library/Python/3.x/bin` до PATH у `~/.zshrc`
- Linux: додайте `~/.local/bin` до PATH у `~/.bashrc`
- Або використовуйте `uv tool install graphifyy` / `pipx install graphifyy` — обидва автоматично керують PATH.
**`python -m graphify` працює, але команда `graphify` — ні**
PATH вашої оболонки не включає директорію скриптів Python. Використовуйте `uv` або `pipx` замість звичайного `pip`.
**`/graphify .` викликає "path not recognized" в PowerShell**
PowerShell трактує ведучий `/` як роздільник шляху. Використовуйте `graphify .` (без слеша) на Windows.
**Граф має менше вузлів після `--update` або перебудови**
Якщо рефакторинг видалив файли, старі вузли залишаються. Передайте `--force` (або встановіть `GRAPHIFY_FORCE=1`), щоб перезаписати навіть якщо перебудова має менше вузлів.
**Граф має дублікати вузлів для однієї сутності (фантомні дублікати)**
Це трапляється, коли семантичне та AST-витягування не погодилось щодо формату ID вузла. Запустіть повне повторне витягування для очищення:
```bash
graphify extract . --force
```
**Ollama вичерпує VRAM / перевищено вікно контексту**
KV-кеш вікно автоматично розраховується, але може бути завеликим для вашого GPU. Зменшіть його:
```bash
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
```
**HTML графу занадто великий для відкриття в браузері (>5000 вузлів)**
Пропустіть генерацію HTML і використовуйте JSON напряму:
```bash
graphify cluster-only ./my-project --no-viz
graphify query "..."
```
**`graph.json` має маркери конфліктів після одночасного коміту двох розробників**
Запустіть `graphify hook install` — це налаштовує git merge driver, який автоматично об'єднує `graph.json`, щоб конфліктів ніколи не виникало.
**Вилучення повертає порожні вузли/ребра для документів або PDF**
Документи та PDF потребують LLM-виклику. Перевірте, що API-ключ встановлено і backend правильний:
```bash
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
**Попередження про невідповідність версій навички у вашому IDE**
Встановлена версія graphify відрізняється від файлу навички. Оновіть:
```bash
uv tool upgrade graphifyy
graphify install # перезаписує файл навички
```
---
## Повний довідник команд
```
/graphify # запустити в поточному каталозі
/graphify ./raw # запустити у конкретній папці
/graphify ./raw --mode deep # більш агресивне витягування зв'язків
/graphify ./raw --update # повторно витягнути лише змінені файли
/graphify ./raw --directed # зберегти напрямок ребер
/graphify ./raw --cluster-only # повторна кластеризація існуючого графу
/graphify ./raw --no-viz # пропустити HTML-візуалізацію
/graphify ./raw --obsidian # згенерувати сховище Obsidian
/graphify ./raw --wiki # побудувати markdown-вікі для обходу агентами
/graphify ./raw --svg # експортувати graph.svg
/graphify ./raw --graphml # експортувати для Gephi / yEd
/graphify ./raw --neo4j # згенерувати cypher.txt для Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687
/graphify ./raw --watch # автосинхронізація при зміні файлів
/graphify ./raw --mcp # запустити MCP stdio-сервер
/graphify add https://arxiv.org/abs/1706.03762
/graphify add <video-url>
/graphify add https://... --author "Name" --contributor "Name"
/graphify query "що пов'язує attention з optimizer?"
/graphify query "..." --dfs --budget 1500
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
graphify uninstall # видалити з усіх платформ одразу
graphify uninstall --purge # також видалити graphify-out/
graphify uninstall --project --platform codex # видалити лише файли проектного встановлення
graphify hook install # хуки post-commit + post-checkout
graphify hook uninstall
graphify hook status
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
graphify extract ./docs # headless LLM-витягування для CI (без IDE)
graphify extract ./docs --backend gemini # явний backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock або claude-cli
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # локальний Ollama (встановіть OLLAMA_BASE_URL / OLLAMA_MODEL) — без API-ключа для loopback
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # будь-який OpenAI-сумісний сервер (llama.cpp, vLLM, LM Studio)
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # будь-який Anthropic-сумісний endpoint (LiteLLM proxy, шлюзи)
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # перевизначити KV-кеш вікно (автоматично за замовчуванням)
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # вивантажити модель після кожного шматка (економить VRAM на малих GPU)
graphify extract ./docs --backend bedrock # AWS Bedrock через IAM — без API-ключа, використовує ланцюг облікових даних AWS
graphify extract ./docs --backend claude-cli # маршрутизація через Claude Code CLI — без API-ключа, використовує вашу підписку Claude
graphify extract ./docs --max-workers 16 # паралелізм AST (також GRAPHIFY_MAX_WORKERS)
graphify extract ./docs --token-budget 30000 # менші семантичні шматки для локальних/малих моделей
graphify extract ./docs --max-concurrency 2 # менше паралельних LLM-викликів (корисно для локального виводу)
graphify extract ./docs --api-timeout 900 # довший HTTP тайм-аут для повільних локальних моделей (типово 600с)
graphify extract ./docs --google-workspace # експортувати .gdoc/.gsheet/.gslides через gws перед витягуванням
graphify extract ./docs --no-cluster # лише сире витягування, пропустити кластеризацію
graphify extract ./docs --force # перезаписати graph.json навіть якщо новий граф має менше вузлів (використовуйте після рефакторингу або для очищення фантомних дублікатів)
graphify extract ./docs --dedup-llm # LLM-арбітр для неоднозначних пар сутностей (використовує той самий API-ключ)
graphify extract ./docs --global --as myrepo # витягнути і зареєструвати в крос-проектний глобальний граф
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # підвищити ліміт виводу для щільних корпусів
graphify export callflow-html # graphify-out/<project>-callflow.html
graphify export callflow-html --max-sections 8 # обмежити кількість згенерованих секцій архітектури
graphify export callflow-html --output docs/arch.html
graphify export callflow-html ./some-repo/graphify-out
graphify global add graphify-out/graph.json myrepo # зареєструвати граф проекту в ~/.graphify/global.json
graphify global remove myrepo # видалити проект з глобального графу
graphify global list # показати всі зареєстровані репо + кількість вузлів/ребер
graphify global path # вивести шлях до файлу глобального графу
graphify prs # дашборд PR: CI, рев’ю, worktree, вплив на граф
graphify prs 42 # детальний огляд PR #42
graphify prs --triage # AI ранжування пріоритизації (автоматично визначає бекенд з середовища)
graphify prs --worktrees # worktree → гілка → PR зіставлення
graphify prs --conflicts # PR-и, що ділять спільні графові спільноти (ризик порядку злиття)
graphify prs --base main # фільтр PR-ів за цільовою базовою гілкою
graphify prs --repo owner/repo # запустити для іншого GitHub-репо
GRAPHIFY_TRIAGE_BACKEND=kimi graphify prs --triage # використовувати конкретний backend для triage
graphify clone https://github.com/karpathy/nanoGPT
graphify merge-graphs a.json b.json --out merged.json
graphify --version # вивести встановлену версію
graphify watch ./src
graphify check-update ./src
graphify update ./src
graphify update ./src --no-cluster # пропустити рекластеризацію, записати лише сирий AST граф
graphify update ./src --force # перезаписати навіть якщо новий граф має менше вузлів
graphify cluster-only ./my-project
graphify cluster-only ./my-project --graph path/to/graph.json # власне розташування графу
graphify cluster-only ./my-project --resolution 1.5 # більше, менших спільнот
graphify cluster-only ./my-project --exclude-hubs 99 # виключити вузли p99 ступеня з розбиття
```
---
## Дізнатися більше
- [Як це працює](../how-it-works.md) — пайплайн витягування, виявлення спільнот, оцінка впевненості, бенчмарки
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — опис модулів, як додати мову
- [Опціональні інтеграції](../docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
---
## Побудовано на graphify — Penpax
[**Penpax**](https://safishamsi.github.io/penpax.ai) — корпоративний рівень над graphify. **Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://safishamsi.github.io/penpax.ai)
[**Penpax**](https://graphifylabs.ai) — це завжди активний шар поверх graphify, він застосовує той самий графовий підхід до всього робочого життя: зустрічей, історії браузера, email-ів, файлів і коду, постійно оновлюючись у фоновому режимі.
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
Створений для людей, чия робота розкидана по сотнях розмов і документів, які неможливо повністю відтворити. Без хмари, повністю на пристрої.
**Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://graphifylabs.ai)
---
<details>
<summary>Участь у розробці</summary>
### Налаштування розробки
Клонуйте репо і встановіть у редагованому режимі:
```bash
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v8 # гілка активної розробки
# Створіть віртуальне середовище (потрібен Python 3.10+):
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Встановіть у редагованому режимі з усіма опціональними пакетами:
pip install -e ".[all]"
```
Перевірте редаговане встановлення:
```bash
graphify --version
python -c "import graphify; print(graphify.__file__)"
```
### Запуск тестів
```bash
pip install pytest
pytest tests/ -q # запустити весь набір тестів
pytest tests/test_extract.py -q # один модуль
pytest tests/ -q -k "python" # фільтрація за назвою
```
> Примітка для macOS: набір тестів включає обидва файли `sample.f90` та `sample.F90`. Вони конфліктують на файлових системах HFS+ / APFS без урахування регістру. Запускайте на Linux або в Docker-контейнері, якщо потрібно тестувати обидва варіанти Fortran одночасно.
### Робочий процес з git
- Активна розробка відбувається в гілці `v8`.
- Стиль комітів: `fix: <опис>` / `feat: <опис>` / `docs: <опис>`
- Перед відкриттям PR запустіть `pytest tests/ -q` і переконайтесь, що він проходить.
- Додайте файл-фікстуру до `tests/fixtures/` і тести до `tests/test_languages.py` для будь-якого нового екстрактора мови.
### Що варто додати
Найкорисніший внесок — це **опрацьовані приклади**. Запустіть `/graphify` на реальному корпусі, збережіть результат у `worked/{slug}/`, напишіть чесний `review.md` про те, що граф зробив правильно і неправильно, і відкрийте PR.
**Помилки витягування** — відкрийте issue з вхідним файлом, записом кешу (`graphify-out/cache/`) і тим, що було пропущено або неправильно.
Дивіться [ARCHITECTURE.md](../../ARCHITECTURE.md) щодо відповідальностей модулів і того, як додати мову.
</details>
+170
View File
@@ -0,0 +1,170 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**Sun'iy intellektga asoslangan kod yordamchilari uchun ko'nikma.** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro yoki Google Antigravity da `/graphify` deb yozing — u sizning fayllaringizni o'qiydi, bilim grafini quradi va siz bilmagan tuzilmani sizga qaytaradi. Kod bazasini tezroq tushuning. Arxitektura qarorlari ortidagi "nima uchun" savoliga javob toping.
To'liq multimodal. Kod, PDF, markdown, ekran tasvirlari, diagrammalar, doska suratlari, boshqa tillardagi tasvirlar, video va audio fayllarni qo'shing — graphify ularning barchasidan tushuncha va aloqalarni chiqarib, bitta grafga birlashtiradi. Videolar Whisper yordamida mahalliy ravishda transkripsiya qilinadi, sizning korpusingizdan olingan domen-maxsus so'rov bilan. tree-sitter AST orqali 25 ta dasturlash tilini qo'llab-quvvatlaydi (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 Karpati maqolalar, tvitlar, ekran tasvirlari va eslatmalarni saqlaydigan `/raw` papkasini yuritadi. graphify ushbu muammoga javob — xom fayllarni o'qishga nisbatan har bir so'rov uchun **71,5 marta** kamroq token, sessiyalar orasida saqlanadi, topilgan va xulosa qilinganlar haqida halol.
```
/graphify . # istalgan papka bilan ishlaydi — kod, eslatmalar, maqolalar, hammasi
```
```
graphify-out/
├── graph.html interaktiv graf — brauzerda oching, tugunlarni bosing, qidiring, filtrlang
├── GRAPH_REPORT.md god-tugunlar, kutilmagan aloqalar, taklif qilingan savollar
├── graph.json doimiy graf — haftalardan keyin qayta o'qimasdan so'rov qiling
└── cache/ SHA256-kesh — qayta ishga tushirish faqat o'zgargan fayllarni qayta ishlaydi
```
Papkalarni istisno qilish uchun `.graphifyignore` faylini qo'shing:
```
# .graphifyignore
vendor/
node_modules/
dist/
*.generated.py
```
Sintaksisi `.gitignore` ga o'xshash.
## Qanday ishlaydi
graphify uch bosqichda ishlaydi. Birinchi navbatda, deterministik AST bosqichi kod fayllaridan tuzilmani chiqaradi (klasslar, funksiyalar, importlar, chaqiruv graflari, docstring lar, sabab izohlari) — LLM ishtirokisiz. Keyin video va audio fayllar faster-whisper yordamida mahalliy ravishda transkripsiya qilinadi. Nihoyat, Claude subagentlari hujjatlar, maqolalar, tasvirlar va transkriptlar ustida parallel ishlab, tushunchalar, aloqalar va dizayn asoslarini chiqarib oladi. Natijalar NetworkX grafiga birlashtiriladi, Leiden hamjamiyat aniqlash algoritmi bilan klasterlanadi va interaktiv HTML, so'rov qilinadigan JSON hamda tabiiy tildagi audit hisoboti sifatida eksport qilinadi.
**Klasterlash graf topologiyasiga asoslangan — embedding ishlatilmaydi.** Leiden hamjamiyatlarni qirralar zichligi bo'yicha topadi. Claude tomonidan chiqarilgan semantik o'xshashlik qirralari (`semantically_similar_to`, INFERRED deb belgilangan) allaqachon grafda. Graf tuzilmasining o'zi o'xshashlik signali. Alohida embedding bosqichi yoki vektor ma'lumotlar bazasi shart emas.
Har bir aloqa `EXTRACTED` (manbada to'g'ridan-to'g'ri topilgan), `INFERRED` (ishonch bahosi bilan asoslangan xulosa) yoki `AMBIGUOUS` (tekshirish uchun belgilangan) deb teglanadi.
## O'rnatish
**Talablar:** Python 3.10+ va quyidagilardan biri: [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 yoki [Google Antigravity](https://antigravity.google)
```bash
# Tavsiya etiladi — Mac va Linux da PATH ni sozlashsiz ishlaydi
uv tool install graphifyy && graphify install
# yoki pipx bilan
pipx install graphifyy && graphify install
# yoki oddiy pip
pip install graphifyy && graphify install
```
> **Rasmiy paket:** PyPI dagi paket nomi `graphifyy` (`pip install graphifyy` orqali o'rnatiladi). PyPI dagi boshqa `graphify*` nomli paketlar bu loyiha bilan bog'liq emas. Yagona rasmiy repozitoriy — [safishamsi/graphify](https://github.com/safishamsi/graphify).
### Platforma qo'llab-quvvatlash
| Platforma | O'rnatish buyrug'i |
|-----------|--------------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install` (avto-aniqlash) yoki `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kiro IDE/CLI | `graphify kiro install` |
| Cursor | `graphify cursor install` |
| Google Antigravity | `graphify antigravity install` |
Keyin AI yordamchingizni oching va kiriting:
```
/graphify .
```
Eslatma: Codex ko'nikmalar uchun `/` o'rniga `$` ishlatadi, shuning uchun `$graphify .` deb kiriting.
### Yordamchini har doim grafdan foydalanishga majbur qilish (tavsiya etiladi)
Graf qurilgandan so'ng, loyihangizda buni bir marta bajaring:
| Platforma | Buyruq |
|-----------|--------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Google Antigravity | `graphify antigravity install` |
## Foydalanish
```
/graphify # joriy katalog
/graphify ./raw # ma'lum bir papka
/graphify ./raw --mode deep # INFERRED qirralarini agressivroq chiqarish
/graphify ./raw --update # faqat o'zgargan fayllarni qayta chiqarish
/graphify ./raw --directed # yo'naltirilgan graf
/graphify ./raw --cluster-only # mavjud grafda klasterlashni qayta ishga tushirish
/graphify ./raw --no-viz # HTML siz, faqat hisobot + JSON
/graphify ./raw --obsidian # Obsidian vault yaratish (opsional)
/graphify add https://arxiv.org/abs/1706.03762 # maqolani olish
/graphify add <video-url> # audio yuklab olish, transkripsiya qilish va qo'shish
/graphify query "Attention ni optimallashtiruvchi bilan nima bog'laydi?"
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
graphify hook install # Git ilgaklarini o'rnatish
graphify update ./src # kod fayllarini qayta chiqarish, LLM siz
graphify watch ./src # grafni avtomatik yangilash
```
## Nima olasiz
**God-tugunlar** — eng yuqori darajadagi tushunchalar (hamma narsa ular orqali o'tadi)
**Kutilmagan aloqalar** — qo'shma ball bo'yicha tartiblangan. Kod-maqola qirralari yuqoriroq baholanadi. Har bir natijada tabiiy tildagi "nima uchun" tushuntirishi bor.
**Taklif qilingan savollar** — graf alohida javob bera oladigan 4-5 ta savol
**"Nima uchun"** — docstring lar, ichki izohlar (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`) va hujjatlardagi dizayn asoslari `rationale_for` tugunlari sifatida chiqariladi.
**Ishonch ballari** — har bir INFERRED qirrasida `confidence_score` (0,0-1,0) mavjud.
**Token benchmark** — har bir ishga tushirishdan keyin avtomatik chiqariladi. Aralash korpusda: so'rov uchun **71,5 marta** kamroq token, xom fayllarga nisbatan.
**Avto-sinxronlash** (`--watch`) — kod o'zgarganida grafni avtomatik yangilaydi.
**Git ilgaklari** (`graphify hook install`) — post-commit va post-checkout ilgaklarini o'rnatadi.
## Maxfiylik
graphify hujjatlar, maqolalar va tasvirlardan semantik chiqarish uchun fayl mazmunini AI yordamchingizning model API siga yuboradi. Kod fayllari tree-sitter AST orqali mahalliy ravishda qayta ishlanadi. Video va audio fayllar faster-whisper bilan mahalliy ravishda transkripsiya qilinadi. Hech qanday telemetriya, foydalanishni kuzatish yo'q.
## Texnologiyalar to'plami
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantik chiqarish Claude, GPT-4 yoki sizning platformangiz modeli orqali. Video transkripsiyasi faster-whisper + yt-dlp orqali (opsional).
## graphify ustida qurilgan — Penpax
[**Penpax**](https://safishamsi.github.io/penpax.ai) — graphify ustidagi korporativ qatlam. graphify fayllar papkasini bilim grafiga aylantirganidek, Penpax o'sha yondashuvni butun ish hayotingizga uzluksiz qo'llaydi.
**Tez orada bepul sinov muddati.** [Kutish ro'yxatiga qo'shiling →](https://safishamsi.github.io/penpax.ai)
## Yulduzlar tarixi
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+8 -4
View File
@@ -1,11 +1,11 @@
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
**一个面向 AI 编码助手的技能。** 在 Claude Code、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
**一个面向 AI 编码助手的技能。** 在 Claude Code、CodeBuddy、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
@@ -33,7 +33,7 @@ graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件
## 安装
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[OpenClaw](https://openclaw.ai)、[Factory Droid](https://factory.ai) 或 [Trae](https://trae.ai)
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[CodeBuddy](https://codebuddy.ai)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[OpenClaw](https://openclaw.ai)、[Factory Droid](https://factory.ai) 或 [Trae](https://trae.ai)
```bash
pip install graphifyy && graphify install
@@ -46,6 +46,7 @@ pip install graphifyy && graphify install
| 平台 | 安装命令 |
|------|----------|
| Claude Code | `graphify install` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| OpenClaw | `graphify install --platform claw` |
@@ -53,7 +54,7 @@ pip install graphifyy && graphify install
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。CodeBuddy 使用与 Claude Code 相同的 Agent 工具和 PreToolUse hook 机制。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
然后打开你的 AI 编码助手,输入:
@@ -68,6 +69,7 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
| 平台 | 命令 |
|------|------|
| Claude Code | `graphify claude install` |
| CodeBuddy | `graphify codebuddy install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| OpenClaw | `graphify claw install` |
@@ -81,6 +83,8 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
**CodeBuddy** 与 Claude Code 相同,也会做两件事:在 `CODEBUDDY.md` 中写入规则,并安装 **PreToolUse hook**(写入 `.codebuddy/settings.json`),在每次 `Glob` 和 `Grep` 前触发。
**Codex、OpenCode、OpenClaw、Factory Droid、Trae** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
+1 -1
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
</p>
<p align="center">
+2430 -462
View File
File diff suppressed because it is too large. Load diff
+107
View File
@@ -0,0 +1,107 @@
"""MinHash + band-LSH — datasketch-compatible drop-in (no scipy).
datasketch.lsh has `from scipy.integrate import quad` at module level.
scipy's array_api_compat layer then lazily loads numpy.testing, which calls
platform.machine() at import time to set test-skip decorator constants — and
that in turn spawns cmd.exe via subprocess, hanging for minutes under EDR
software in corporate Windows environments.
Covers the exact MinHash/MinHashLSH API surface used by dedup.py.
Hash family (Mersenne-prime permutations) and LSH band structure are
equivalent to datasketch so dedup quality is unchanged.
"""
from __future__ import annotations
import hashlib
import struct
import numpy as np
_MP = np.uint64((1 << 61) - 1) # Mersenne prime for the hash family
_MH = np.uint64(0xFFFF_FFFF) # mask to 32-bit values
# One (a, b) coefficient array per num_perm, shared across all instances.
_MH_COEFFS: dict[int, tuple[np.ndarray, np.ndarray]] = {}
def _mh_coeffs(num_perm: int) -> tuple[np.ndarray, np.ndarray]:
if num_perm not in _MH_COEFFS:
rng = np.random.RandomState(1)
a = rng.randint(1, int(_MP), num_perm, dtype=np.uint64)
b = rng.randint(0, int(_MP), num_perm, dtype=np.uint64)
_MH_COEFFS[num_perm] = (a, b)
return _MH_COEFFS[num_perm]
class MinHash:
"""MinHash sketch — same API as datasketch.MinHash for the subset used here."""
__slots__ = ("num_perm", "hashvalues", "_a", "_b")
def __init__(self, num_perm: int = 128) -> None:
self.num_perm = num_perm
self.hashvalues = np.full(num_perm, int(_MH), dtype=np.uint64)
self._a, self._b = _mh_coeffs(num_perm)
def update(self, v: bytes) -> None:
hv = np.uint64(struct.unpack("<I", hashlib.sha1(v).digest()[:4])[0])
phv = np.bitwise_and((self._a * hv + self._b) % _MP, _MH)
self.hashvalues = np.minimum(self.hashvalues, phv)
def _lsh_integrate(f, lo: float, hi: float, n: int = 128) -> float:
"""Numerical integration — replaces scipy.integrate.quad for LSH param search."""
h = (hi - lo) / n
return h * sum(f(lo + i * h) for i in range(n))
_LSH_PARAMS_CACHE: dict[tuple[float, int], tuple[int, int]] = {}
def _optimal_lsh_params(threshold: float, num_perm: int) -> tuple[int, int]:
"""Find (bands, rows) that minimise weighted FP+FN error, without scipy."""
key = (threshold, num_perm)
if key in _LSH_PARAMS_CACHE:
return _LSH_PARAMS_CACHE[key]
best_err, best = float("inf"), (1, 1)
for b in range(1, num_perm + 1):
for r in range(1, num_perm // b + 1):
fp = _lsh_integrate(
lambda s, _b=float(b), _r=float(r): 1 - (1 - s ** _r) ** _b,
0.0, threshold,
)
fn = _lsh_integrate(
lambda s, _b=float(b), _r=float(r): 1 - (1 - (1 - s ** _r) ** _b),
threshold, 1.0,
)
err = 0.5 * fp + 0.5 * fn
if err < best_err:
best_err, best = err, (b, r)
_LSH_PARAMS_CACHE[key] = best
return best
class MinHashLSH:
"""Band-hashing LSH — same API as datasketch.MinHashLSH for the subset used here."""
def __init__(self, threshold: float = 0.5, num_perm: int = 128) -> None:
self.b, self.r = _optimal_lsh_params(threshold, num_perm)
self._tables: list[dict[bytes, list[str]]] = [{} for _ in range(self.b)]
self._keys: set[str] = set()
def insert(self, key: str, minhash: MinHash) -> None:
if key in self._keys:
raise ValueError(f"Key {key!r} already exists in MinHashLSH")
self._keys.add(key)
hv = minhash.hashvalues
for i, table in enumerate(self._tables):
band = hv[i * self.r : (i + 1) * self.r].tobytes()
table.setdefault(band, []).append(key)
def query(self, minhash: MinHash) -> list[str]:
hv = minhash.hashvalues
candidates: set[str] = set()
for i, table in enumerate(self._tables):
band = hv[i * self.r : (i + 1) * self.r].tobytes()
candidates.update(table.get(band, []))
return list(candidates)
+182
View File
@@ -0,0 +1,182 @@
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import unicodedata
import networkx as nx
DEFAULT_AFFECTED_RELATIONS = (
"calls",
"references",
"imports",
"imports_from",
"re_exports",
"inherits",
"extends",
"implements",
"uses",
"mixes_in",
"embeds",
)
@dataclass(frozen=True)
class AffectedHit:
node_id: str
depth: int
via_relation: str
def _node_label(graph: nx.Graph, node_id: str) -> str:
data = graph.nodes[node_id]
return str(data.get("label") or node_id)
def _format_location(data: dict) -> str:
source_file = data.get("source_file") or "-"
source_location = data.get("source_location")
if source_location:
return f"{source_file}:{source_location}"
return str(source_file)
def _bare_name(label: str) -> str:
"""Lowercased label with the callable decoration (trailing "()") removed."""
label = _normalize_label(label)
return label[:-2] if label.endswith("()") else label
def _normalize_label(label: str) -> str:
return unicodedata.normalize("NFC", label).casefold()
def resolve_seed(graph: nx.Graph, query: str) -> str | None:
if query in graph:
return query
query_lower = _normalize_label(query)
exact_label_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if _normalize_label(str(data.get("label", ""))) == query_lower
]
if len(exact_label_matches) == 1:
return exact_label_matches[0]
# Callable labels are decorated ("name()"), so a bare "name" query falls
# through exact matching and then ties with any "name*" sibling in the
# contains pass. Match on the undecorated name before giving up.
query_bare = _bare_name(query_lower)
bare_name_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if _bare_name(str(data.get("label", ""))) == query_bare
]
if len(bare_name_matches) == 1:
return bare_name_matches[0]
exact_source_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if _normalize_label(str(data.get("source_file", ""))) == query_lower
]
if len(exact_source_matches) == 1:
return exact_source_matches[0]
contains_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if query_lower in _normalize_label(str(data.get("label", "")))
]
if len(contains_matches) == 1:
return contains_matches[0]
return None
def affected_nodes(
graph: nx.Graph,
seed: str,
*,
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
depth: int = 2,
) -> list[AffectedHit]:
relation_set = set(relations)
seen = {seed}
queue: deque[tuple[str, int]] = deque([(seed, 0)])
hits: list[AffectedHit] = []
while queue:
current, current_depth = queue.popleft()
if current_depth >= depth:
continue
if hasattr(graph, "in_edges"):
incoming = graph.in_edges(current, data=True)
else:
incoming = (
(source, target, data)
for source, target, data in graph.edges(data=True)
if target == current
)
for source, _target, data in incoming:
relation = str(data.get("relation", ""))
if relation not in relation_set:
continue
source = str(source)
if source in seen:
continue
seen.add(source)
hit = AffectedHit(source, current_depth + 1, relation)
hits.append(hit)
queue.append((source, current_depth + 1))
return hits
def format_affected(
graph: nx.Graph,
query: str,
*,
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
depth: int = 2,
) -> str:
relation_list = tuple(relations)
seed = resolve_seed(graph, query)
if seed is None:
return f"No unique node match for {query}"
hits = affected_nodes(graph, seed, relations=relation_list, depth=depth)
lines = [
f"Affected nodes for {_node_label(graph, seed)}",
f"Relations: {', '.join(relation_list)}",
f"Depth: {depth}",
]
if not hits:
lines.append("No affected nodes found.")
return "\n".join(lines)
for hit in hits:
data = graph.nodes[hit.node_id]
lines.append(
f"- {_node_label(graph, hit.node_id)} [{hit.via_relation}] {_format_location(data)}"
)
return "\n".join(lines)
def load_graph(path: Path) -> nx.Graph:
import json
from networkx.readwrite import json_graph
raw = json.loads(path.read_text(encoding="utf-8"))
# Force directed so stored caller→callee direction survives the round-trip;
# mirrors serve.py and __main__.py (#1174).
raw = {**raw, "directed": True}
# Normalize the edge key: graphify's `extract` output uses "edges" while
# networkx's node_link_data default is "links". Without this, an edges-keyed
# graph.json raises an uncaught KeyError: 'links' here — every other loader
# (__main__.py) already normalizes this (#738; same class as #1198).
if "links" not in raw and "edges" in raw:
raw = dict(raw, links=raw["edges"])
try:
return json_graph.node_link_graph(raw, edges="links")
except TypeError:
return json_graph.node_link_graph(raw)
+12
View File
@@ -0,0 +1,12 @@
## graphify
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
When the user types `/graphify`, invoke the `skill` tool with `skill: "graphify"` before doing anything else.
Rules:
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
- Dirty graphify-out/ files are expected after hooks or incremental updates; dirty graph files are not a reason to skip graphify. Only skip graphify if the task is about stale or incorrect graph output, or the user explicitly says not to use it.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
+14
View File
@@ -0,0 +1,14 @@
---
trigger: always_on
description: Consult the graphify knowledge graph at graphify-out/ for codebase and architecture questions.
---
## graphify
This project has a graphify knowledge graph at graphify-out/.
Rules:
- For codebase or architecture questions, when `graphify-out/graph.json` exists, first run `graphify query "<question>"` (CLI) or `query_graph` (MCP). Use `graphify path "<A>" "<B>"` / `shortest_path` for relationships and `graphify explain "<concept>"` / `get_node` for focused concepts. These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output.
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
+9
View File
@@ -0,0 +1,9 @@
## graphify
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
Rules:
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
+9
View File
@@ -0,0 +1,9 @@
## graphify
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
Rules:
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
+5
View File
@@ -0,0 +1,5 @@
---
inclusion: always
---
graphify: A knowledge graph of this project lives in `graphify-out/`. For codebase, architecture, or dependency questions, when `graphify-out/graph.json` exists, first run `graphify query "<question>"` (or `graphify path "<A>" "<B>"` / `graphify explain "<concept>"`). These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output. Read `GRAPH_REPORT.md` only for broad architecture review or when those commands do not surface enough context.
+17
View File
@@ -0,0 +1,17 @@
## graphify
For any question about this repo's architecture, structure, components, or how to add/modify/find
code, your first action should be `graphify query "<question>"` when `graphify-out/graph.json`
exists. Use `graphify path "<A>" "<B>"` for relationship questions and `graphify explain "<concept>"`
for focused-concept questions. These return a scoped subgraph, usually much smaller than the full
report or raw grep output.
Triggers: "how do I…", "where is…", "what does … do", "add/modify a <component>",
"explain the architecture", or anything that depends on how files or classes relate.
If `graphify-out/wiki/index.md` exists, use it for broad navigation. Read `graphify-out/GRAPH_REPORT.md`
only for broad architecture review or when query/path/explain do not surface enough context. Only read
source files when (a) modifying/debugging specific code, (b) the graph lacks the needed detail, or
(c) the graph is missing or stale.
Type `/graphify` in Copilot Chat to build or update the graph.
+169 -12
View File
@@ -5,6 +5,21 @@ import networkx as nx
from graphify.build import edge_data
# Builtin/mock names that can appear as annotation-derived nodes in pre-existing
# graphs. Excluded from god-node ranking so they don't displace real abstractions
# even if they weren't filtered at extraction time (#1147).
_BUILTIN_NOISE_LABELS = frozenset({
"str", "int", "float", "bool", "bytes", "bytearray", "complex", "object",
"True", "False",
"MagicMock", "Mock", "AsyncMock", "NonCallableMock",
"NonCallableMagicMock", "PropertyMock", "patch", "sentinel",
# Python stdlib types commonly confused for project symbols
"Path", "Any", "Optional", "List", "Dict", "Set", "Tuple", "Union",
"Callable", "Type", "ClassVar", "Final", "Literal", "Protocol",
"Counter", "defaultdict", "OrderedDict", "datetime", "Enum",
"os", "sys", "re", "json", "io", "abc", "typing",
})
# Language families — extensions sharing a runtime can legitimately call each other
_LANG_FAMILY: dict[str, str] = {
**{e: "python" for e in (".py", ".pyw")},
@@ -65,6 +80,23 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
return False
_JSON_NOISE_LABELS: frozenset[str] = frozenset({
"start", "end", "name", "id", "type", "properties",
"value", "key", "data", "items", "title", "description", "version",
"dependencies", "devdependencies", "peerdependencies",
"optionaldependencies", "bundleddependencies", "bundledependencies",
})
def _is_json_key_node(G: nx.Graph, node_id: str) -> bool:
attrs = G.nodes[node_id]
src = (attrs.get("source_file") or "").lower()
if not src.endswith(".json"):
return False
label = (attrs.get("label") or "").strip().lower()
return label in _JSON_NOISE_LABELS
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
"""Return the top_n most-connected real entities - the core abstractions.
@@ -75,7 +107,9 @@ def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
sorted_nodes = sorted(degree.items(), key=lambda x: x[1], reverse=True)
result = []
for node_id, deg in sorted_nodes:
if _is_file_node(G, node_id) or _is_concept_node(G, node_id):
if _is_file_node(G, node_id) or _is_concept_node(G, node_id) or _is_json_key_node(G, node_id):
continue
if G.nodes[node_id].get("label", "") in _BUILTIN_NOISE_LABELS:
continue
result.append({
"id": node_id,
@@ -165,6 +199,7 @@ def _surprise_score(
node_community: dict[str, int],
u_source: str,
v_source: str,
degrees: dict[str, int] | None = None,
) -> tuple[int, list[str]]:
"""Score how surprising a cross-file edge is. Returns (score, reasons)."""
score = 0
@@ -175,30 +210,41 @@ def _surprise_score(
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
cat_u = _file_category(u_source)
cat_v = _file_category(v_source)
# Suppress all structural bonuses for INFERRED calls/uses that cross language
# boundaries or connect code to a doc file. Both cases are resolver pollution:
# label-matching fires across language families in monorepos, and code→doc
# "calls" edges are extraction artefacts, not real architecture.
# Excludes `semantically_similar_to` (genuine cross-boundary insight) and all
# AMBIGUOUS/EXTRACTED edges (not from the resolver path).
_suppress_structural = (
conf == "INFERRED"
and relation in ("calls", "uses")
and (_cross_language(u_source, v_source) or {cat_u, cat_v} == {"code", "doc"})
)
if _suppress_structural:
conf_bonus = 0
score += conf_bonus
if conf in ("AMBIGUOUS", "INFERRED"):
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
# 2. Cross file-type bonus - code↔paper or code↔image is non-obvious
cat_u = _file_category(u_source)
cat_v = _file_category(v_source)
if cat_u != cat_v:
if cat_u != cat_v and not _suppress_structural:
score += 2
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
# 3. Cross-repo bonus - different top-level directory
if _top_level_dir(u_source) != _top_level_dir(v_source):
if _top_level_dir(u_source) != _top_level_dir(v_source) and not _suppress_structural:
score += 2
reasons.append("connects across different repos/directories")
# 4. Cross-community bonus - Leiden says these are structurally distant
cid_u = node_community.get(u)
cid_v = node_community.get(v)
if cid_u is not None and cid_v is not None and cid_u != cid_v:
if cid_u is not None and cid_v is not None and cid_u != cid_v and not _suppress_structural:
score += 1
reasons.append("bridges separate communities")
@@ -208,8 +254,8 @@ def _surprise_score(
reasons.append("semantically similar concepts with no structural link")
# 5. Peripheral→hub: a low-degree node connecting to a high-degree one
deg_u = G.degree(u)
deg_v = G.degree(v)
deg_u = degrees[u] if degrees is not None else G.degree(u)
deg_v = degrees[v] if degrees is not None else G.degree(v)
if min(deg_u, deg_v) <= 2 and max(deg_u, deg_v) >= 5:
score += 1
peripheral = G.nodes[u].get("label", u) if deg_u <= 2 else G.nodes[v].get("label", v)
@@ -234,6 +280,7 @@ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n:
Each result includes a 'why' field explaining what makes it non-obvious.
"""
node_community = _node_community_map(communities)
degrees = dict(G.degree())
candidates = []
for u, v, data in G.edges(data=True):
@@ -251,7 +298,7 @@ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n:
if not u_source or not v_source or u_source == v_source:
continue
score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source)
score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source, degrees)
src_id = data.get("_src", u)
if src_id not in G.nodes:
src_id = u
@@ -380,6 +427,9 @@ def suggest_questions(
Based on: AMBIGUOUS edges, bridge nodes, underexplored god nodes, isolated nodes.
Each question has a 'type', 'question', and 'why' field.
"""
if community_labels:
community_labels = {int(k) if isinstance(k, str) else k: v for k, v in community_labels.items()}
questions = []
node_community = _node_community_map(communities)
@@ -573,3 +623,110 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
"removed_edges": removed_edges_list,
"summary": summary,
}
def find_import_cycles(
G: nx.Graph,
max_cycle_length: int = 5,
top_n: int = 20,
) -> list[dict]:
"""Detect circular import dependencies at the file level.
Collapses symbol-level nodes to their parent file (using source_file attr
or 'contains' edges), builds a directed file-level graph from imports_from
edges, then finds simple cycles.
Args:
G: The full knowledge graph (may be undirected or directed).
max_cycle_length: Only report cycles with at most this many files.
top_n: Maximum number of cycles to return (shortest first).
Returns:
List of cycle records with stable structure:
{
"cycle": ["a.ts", "b.ts"],
"length": 2,
"why": "circular dependency"
}
"""
def _endpoint_source_file(node_id: str) -> str:
attrs = G.nodes.get(node_id, {})
src_file = attrs.get("source_file", "")
return src_file if isinstance(src_file, str) else ""
# Step 1: Build a directed file-level graph from import/re-export edges.
# IMPORTANT: resolve endpoints using source_file only; never infer from label/id.
file_graph = nx.DiGraph()
for u, v, data in G.edges(data=True):
rel = data.get("relation", "")
if rel not in ("imports_from", "re_exports"):
continue
src_file_attr = data.get("source_file", "")
if not isinstance(src_file_attr, str) or not src_file_attr:
continue
u_file = _endpoint_source_file(u)
v_file = _endpoint_source_file(v)
# Works for both DiGraph and Graph inputs:
# orient edge from edge.source_file endpoint to the opposite endpoint.
if u_file == src_file_attr:
tgt_file = v_file
elif v_file == src_file_attr:
tgt_file = u_file
else:
# Fallback: if source endpoint cannot be matched exactly,
# still treat edge.source_file as source and pick the opposite endpoint
# only if one endpoint has a real source_file.
tgt_file = v_file if v_file and v_file != src_file_attr else u_file
if not tgt_file:
continue
file_graph.add_edge(src_file_attr, tgt_file)
if not file_graph.edges():
return []
# Step 2: Find simple cycles, bounded by length.
# Pass length_bound so networkx prunes during enumeration rather than
# enumerating all elementary cycles and post-filtering — avoids exponential
# blowup on dense graphs with many long cycles (#1196).
cycles: list[list[str]] = []
for cycle in nx.simple_cycles(file_graph, length_bound=max_cycle_length):
if len(cycle) <= max_cycle_length:
cycles.append(cycle)
if len(cycles) >= top_n * 10:
# Stop early to avoid combinatorial explosion
break
# Step 3: Sort by length (shortest = tightest coupling), then deduplicate.
cycles.sort(key=len)
# Deduplicate rotations: normalize each cycle by starting from the
# lexicographically smallest element.
seen: set[tuple[str, ...]] = set()
unique_cycles: list[list[str]] = []
for cycle in cycles:
core = list(cycle)
if not core:
continue
min_idx = core.index(min(core))
normalized = tuple(core[min_idx:] + core[:min_idx])
if normalized not in seen:
seen.add(normalized)
unique_cycles.append(list(normalized))
if len(unique_cycles) >= top_n:
break
result: list[dict] = []
for cycle in unique_cycles:
result.append({
"cycle": cycle,
"length": len(cycle),
"why": "circular dependency",
})
return result
+4 -1
View File
@@ -7,6 +7,7 @@ import networkx as nx
from networkx.readwrite import json_graph
from graphify.build import edge_data
from graphify.serve import _query_terms
_CHARS_PER_TOKEN = 4 # standard approximation
@@ -37,7 +38,7 @@ def _estimate_tokens(text: str) -> int:
def _query_subgraph_tokens(G: nx.Graph, question: str, depth: int = 3) -> int:
"""Run BFS from best-matching nodes and return estimated tokens in the subgraph context."""
terms = [t.lower() for t in question.split() if len(t) > 2]
terms = _query_terms(question)
scored = []
for nid, data in G.nodes(data=True):
label = data.get("label", "").lower()
@@ -97,6 +98,8 @@ def run_benchmark(
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
"""
from graphify.security import check_graph_file_size_cap
check_graph_file_size_cap(Path(graph_path))
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
try:
G = json_graph.node_link_graph(data, edges="links")
+264 -33
View File
@@ -22,11 +22,13 @@
#
from __future__ import annotations
import json
import os
import re
import sys
import unicodedata
from pathlib import Path
import networkx as nx
from .ids import normalize_id as _normalize_id
from .validate import validate_extraction
@@ -50,24 +52,22 @@ _FILE_TYPE_SYNONYMS = {
}
def _normalize_id(s: str) -> str:
r"""Normalize an ID string the same way extract._make_id does.
def _norm_source_file(p: str | None, root: str | None = None) -> str | None:
"""Normalize path separators and relativize absolute paths.
Used to reconcile edge endpoints when the LLM generates IDs with slightly
different punctuation or casing than the AST extractor. Must stay in sync
with extract._make_id — NFKC normalization, \w with re.UNICODE, underscore
collapse, and casefold must all match (#811).
Converts backslashes to forward slashes (Windows compatibility) and, when
root is provided, strips the absolute prefix from paths produced by semantic
subagents so source_file is always repo-relative (fixes #932).
"""
s = unicodedata.normalize("NFKC", s)
cleaned = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
cleaned = re.sub(r"_+", "_", cleaned)
return cleaned.strip("_").casefold()
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
if not p:
return p
p = p.replace("\\", "/")
if root and os.path.isabs(p):
try:
p = Path(p).relative_to(root).as_posix()
except ValueError:
pass
return p
def edge_data(G: nx.Graph, u: str, v: str) -> dict:
@@ -91,12 +91,57 @@ def edge_datas(G: nx.Graph, u: str, v: str) -> list[dict]:
return [raw]
def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
def dedupe_nodes(nodes: list[dict]) -> list[dict]:
"""Collapse nodes sharing an ``id``, last-writer-wins on attributes.
Mirrors what ``build_from_json``'s ``G.add_node`` does implicitly (idempotent;
a later node overwrites an earlier one's attributes). The ``--no-cluster``
write path dumps the raw node list without building a graph, so same-id nodes
— e.g. a Swift ``type=module`` anchor emitted once per importing file (#1327)
— would otherwise appear as duplicates. Insertion order follows each id's
first appearance; the retained dict is the last one seen.
"""
by_id: dict = {}
for n in nodes:
nid = n.get("id")
if nid is None:
continue
by_id[nid] = n
return list(by_id.values())
def dedupe_edges(edges: list[dict]) -> list[dict]:
"""Collapse exact parallel edges by ``(source, target, relation)``, keeping the
first occurrence.
The clustered build path runs edges through a NetworkX ``DiGraph``, which
collapses parallel edges automatically. The ``--no-cluster`` and incremental
``update`` write paths bypass NetworkX and concatenate edge lists raw, so
duplicates accumulate and edge counts become non-deterministic across build
modes / repeated updates (#1317). Deduping on the connectivity identity is
zero-signal-loss and restores idempotency. Callers that intentionally keep
parallel edges (multigraph output) must not use this.
"""
seen: set[tuple] = set()
out: list[dict] = []
for e in edges:
key = (e.get("source"), e.get("target"), e.get("relation"))
if key in seen:
continue
seen.add(key)
out.append(e)
return out
def build_from_json(extraction: dict, *, directed: bool = False, root: str | Path | None = None) -> nx.Graph:
"""Build a NetworkX graph from an extraction dict.
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
root: if given, absolute source_file paths from semantic subagents are made
relative to root so all nodes share a consistent path key (#932).
"""
_root = str(Path(root).resolve()) if root else None
# NetworkX <= 3.1 serialised edges as "links"; remap to "edges" for compatibility.
if "edges" not in extraction and "links" in extraction:
extraction = dict(extraction, edges=extraction["links"])
@@ -137,14 +182,92 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
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"])
node["source_file"] = _norm_source_file(node["source_file"], _root)
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
node_set = set(G.nodes())
# #1145 (extended): merge LLM ghost-duplicate nodes into AST canonical nodes.
# Original bug: AST uses parent-qualified IDs (mingpt_bpe_get_pairs) while LLM
# uses bare-stem IDs (bpe_get_pairs) — different IDs, same symbol.
# Original fix only caught LLM nodes with source_location=None; LLM now
# populates source_location, so those ghosts survived. Extended fix: use
# _origin=="ast" as the canonical signal. AST nodes always win; any non-AST
# node sharing (basename, label) with an AST node is a ghost.
_loc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> canonical node id
_loc_collisions: set[tuple[str, str]] = set() # keys shared by 2+ AST nodes
_noloc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> ghost node id
# Pass 1: collect canonical nodes — AST-origin nodes take precedence over LLM nodes.
# When 2+ AST nodes share a key (same-named symbols in same-named files across
# directories, e.g. render in two index.ts), the key is ambiguous: merging a
# ghost would pick an arbitrary winner via set-iteration order (#1257). Track
# those keys so Pass 2 skips them — same conservatism as
# _rewire_unique_stub_nodes, which only merges when exactly one real def exists.
for nid in node_set:
attrs = G.nodes[nid]
label = str(attrs.get("label", "")).strip()
sf = str(attrs.get("source_file", ""))
basename = Path(sf).name if sf else ""
if not label or not basename:
continue
is_ast = attrs.get("_origin") == "ast"
if attrs.get("source_location") or is_ast:
key = (basename, label)
if is_ast:
# Two AST nodes on the same key is an ambiguous collision.
if key in _loc_nodes and G.nodes[_loc_nodes[key]].get("_origin") == "ast":
_loc_collisions.add(key)
# AST-origin nodes always overwrite a prior non-AST entry.
_loc_nodes[key] = nid
elif key not in _loc_nodes:
_loc_nodes[key] = nid
# Pass 2: find ghosts — non-AST nodes that have an AST canonical twin.
for nid in node_set:
attrs = G.nodes[nid]
if attrs.get("_origin") == "ast":
continue # AST nodes are never ghosts
label = str(attrs.get("label", "")).strip()
sf = str(attrs.get("source_file", ""))
basename = Path(sf).name if sf else ""
if not label or not basename:
continue
key = (basename, label)
if key in _loc_collisions:
continue # ambiguous key: no safe canonical winner, leave ghost intact
if key in _loc_nodes and _loc_nodes[key] != nid:
_noloc_nodes[key] = nid
# For every ghost that has an AST counterpart, record a remap.
_ghost_remap: dict[str, str] = {} # ghost_id -> canonical_id
for key, sem_id in _noloc_nodes.items():
ast_id = _loc_nodes.get(key)
if ast_id is not None:
_ghost_remap[sem_id] = ast_id
# Remove ghost nodes from the graph; edges will be re-pointed via norm_to_id.
for ghost_id in _ghost_remap:
G.remove_node(ghost_id)
node_set.discard(ghost_id)
# Normalized ID map: lets edges survive when the LLM generates IDs with
# slightly different casing or punctuation than the AST extractor.
# e.g. "Session_ValidateToken" maps to "session_validatetoken".
norm_to_id: dict[str, str] = {_normalize_id(nid): nid for nid in node_set}
for edge in extraction.get("edges", []):
# Also map ghost IDs to their canonical AST replacements.
for ghost_id, canonical_id in _ghost_remap.items():
norm_to_id[_normalize_id(ghost_id)] = canonical_id
norm_to_id[ghost_id] = canonical_id
# Iterate edges in a deterministic order. The graph is undirected and stores
# direction in _src/_tgt; when two edges collapse onto the same node pair the
# last write wins, so an unstable iteration order flips _src/_tgt run-to-run
# and makes the serialized graph churn. Sorting fixes the last-write outcome.
for edge in sorted(
extraction.get("edges", []),
key=lambda e: (
str(e.get("source", e.get("from", ""))),
str(e.get("target", e.get("to", ""))),
str(e.get("relation", "")),
),
):
if "source" not in edge and "from" in edge:
edge["source"] = edge["from"]
if "target" not in edge and "to" in edge:
@@ -160,12 +283,51 @@ 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")}
# Backfill source_file from the endpoint nodes (every node carries one).
# Semantic/LLM edges occasionally omit it, which downstream validation
# flags and leaves query results with no file reference (#1279).
if not attrs.get("source_file"):
attrs["source_file"] = (
G.nodes[src].get("source_file")
or G.nodes[tgt].get("source_file")
or ""
)
if "source_file" in attrs:
attrs["source_file"] = _norm_source_file(attrs["source_file"])
attrs["source_file"] = _norm_source_file(attrs["source_file"], _root)
# Drop cross-language INFERRED `calls` edges — same short names (render,
# parse, etc.) appear across language boundaries in multi-language chunks,
# producing phantom edges that don't represent real call relationships.
if attrs.get("relation") == "calls" and attrs.get("confidence") == "INFERRED":
_LANG_FAMILY: dict[str, str] = {
".py": "py", ".pyi": "py",
".js": "js", ".mjs": "js", ".cjs": "js", ".jsx": "js",
".ts": "js", ".tsx": "js",
".go": "go", ".rs": "rs",
".java": "jvm", ".kt": "jvm", ".scala": "jvm", ".groovy": "jvm",
".c": "c", ".h": "c", ".cc": "cpp", ".cpp": "cpp", ".hpp": "cpp",
".rb": "rb", ".php": "php", ".cs": "cs", ".swift": "swift", ".lua": "lua",
}
src_ext = Path(G.nodes[src].get("source_file") or "").suffix.lower()
tgt_ext = Path(G.nodes[tgt].get("source_file") or "").suffix.lower()
if src_ext and tgt_ext and _LANG_FAMILY.get(src_ext) != _LANG_FAMILY.get(tgt_ext):
continue
# Preserve original edge direction - undirected graphs lose it otherwise,
# causing display functions to show edges backwards.
attrs["_src"] = src
attrs["_tgt"] = tgt
# When the graph is undirected and the same node pair appears twice with
# the same relation but opposite directions (e.g. a `calls` b and b `calls` a),
# nx.Graph collapses them into one edge. The deterministic sort above means
# the lexicographically-later direction would systematically overwrite the
# earlier one's _src/_tgt, silently flipping the surviving edge's caller
# and callee. First-seen direction wins instead — drop the redundant
# reverse-direction duplicate so the original direction is preserved (#1061).
if not G.is_directed() and G.has_edge(src, tgt):
existing = edge_data(G, src, tgt)
if existing.get("relation") == attrs.get("relation") and (
existing.get("_src") == tgt and existing.get("_tgt") == src
):
continue
G.add_edge(src, tgt, **attrs)
hyperedges = extraction.get("hyperedges", [])
if hyperedges:
@@ -179,6 +341,7 @@ def build(
directed: bool = False,
dedup: bool = True,
dedup_llm_backend: str | None = None,
root: str | Path | None = None,
) -> nx.Graph:
"""Merge multiple extraction results into one graph.
@@ -187,6 +350,7 @@ def build(
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.
root: if given, absolute source_file paths are made relative to root (#932).
Extractions are merged in order. For nodes with the same ID, the last
extraction's attributes win (NetworkX add_node overwrites). Pass AST
@@ -206,12 +370,15 @@ def build(
combined["nodes"], combined["edges"], communities={},
dedup_llm_backend=dedup_llm_backend,
)
return build_from_json(combined, directed=directed)
return build_from_json(combined, directed=directed, root=root)
def _norm_label(label: str) -> str:
"""Canonical dedup key — lowercase, alphanumeric only."""
return re.sub(r"[^a-z0-9 ]", "", label.lower()).strip()
def _norm_label(label: str | None) -> str:
"""Canonical dedup key — Unicode-aware, preserves CJK/word characters."""
if not isinstance(label, str):
label = "" if label is None else str(label)
label = unicodedata.normalize("NFKC", label)
return re.sub(r"[\W_ ]+", " ", label.casefold(), flags=re.UNICODE).strip()
def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dict], list[dict]]:
@@ -268,11 +435,16 @@ def build_merge(
directed: bool = False,
dedup: bool = True,
dedup_llm_backend: str | None = None,
root: str | Path | 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.
Re-extracted files REPLACE their prior contribution: any source_file present
in new_chunks is dropped from the loaded graph before merging, so a changed
file's stale nodes/edges don't accumulate. Files absent from new_chunks are
preserved unchanged; deleted files are removed via prune_sources.
Safe to call repeatedly.
root: if given, absolute source_file paths in new_chunks are made relative (#932).
"""
graph_path = Path(graph_path)
if graph_path.exists():
@@ -283,23 +455,70 @@ def build_merge(
# was inserted before the caller. The _src/_tgt direction-preserving
# attrs are popped before saving in export.py, so going through the
# NetworkX round-trip loses direction permanently (#760).
from graphify.security import check_graph_file_size_cap
check_graph_file_size_cap(graph_path)
data = json.loads(graph_path.read_text(encoding="utf-8"))
links_key = "links" if "links" in data else "edges"
existing_nodes = list(data.get("nodes", []))
existing_edges = list(data.get(links_key, []))
base = [{"nodes": existing_nodes, "edges": existing_edges}]
had_graph = True
else:
existing_nodes = []
base = []
existing_edges = []
had_graph = False
# Re-extracted files REPLACE their prior contribution. Every source_file
# present in new_chunks is dropped from the loaded base before merging, so a
# CHANGED file's stale nodes/edges don't accumulate across incremental
# updates. Without this, build() merges old+new for the same file and only
# exact-duplicate edges collapse — edges/nodes that disappeared from the new
# version survive forever. Brand-new files aren't in base, so this is a no-op
# for them; genuinely deleted files are still handled via prune_sources.
# Matched in both raw and _norm_source_file form because new_chunks may carry
# absolute win32 paths while the stored graph keeps relative posix (#1007).
_replace_root = str(Path(root).resolve()) if root is not None else None
new_sources: set[str] = set()
for ch in new_chunks:
for n in ch.get("nodes", []):
sf = n.get("source_file")
if not sf:
continue
new_sources.add(sf)
norm = _norm_source_file(sf, _replace_root)
if norm:
new_sources.add(norm)
if new_sources:
def _kept(item: dict) -> bool:
sf = item.get("source_file")
return sf not in new_sources and _norm_source_file(sf, _replace_root) not in new_sources
existing_nodes = [n for n in existing_nodes if _kept(n)]
existing_edges = [e for e in existing_edges if _kept(e)]
base = [{"nodes": existing_nodes, "edges": existing_edges}] if had_graph else []
all_chunks = base + list(new_chunks)
G = build(all_chunks, directed=directed, dedup=dedup, dedup_llm_backend=dedup_llm_backend)
G = build(all_chunks, directed=directed, dedup=dedup, dedup_llm_backend=dedup_llm_backend, root=root)
# Prune nodes from deleted source files
# Prune nodes and edges from deleted source files
if prune_sources:
# Build a set containing both the raw form (matches nodes that kept
# absolute source_file) and the normalised relative form (matches nodes
# that were relativised by _norm_source_file at build time).
# .resolve() handles symlinked roots and redundant ".." / "./" segments
# so Path.relative_to() succeeds even when the scan root is a symlink.
# (#1007: manifest absolute paths vs graph relative source_file mismatch)
_root_str = str(Path(root).resolve()) if root is not None else None
prune_set: set[str] = set()
for p in prune_sources:
if not p:
continue
prune_set.add(p)
norm = _norm_source_file(p, _root_str)
if norm:
prune_set.add(norm)
to_remove = [
n for n, d in G.nodes(data=True)
if d.get("source_file") in prune_sources
if d.get("source_file") in prune_set
]
G.remove_nodes_from(to_remove)
n_files = len(prune_sources)
@@ -309,10 +528,22 @@ def build_merge(
f"[graphify] Pruned {n_nodes} node(s) from {n_files} deleted source file(s).",
file=sys.stderr,
)
else:
edges_to_remove = [
(u, v) for u, v, d in G.edges(data=True)
if d.get("source_file") in prune_set
]
if edges_to_remove:
G.remove_edges_from(edges_to_remove)
print(
f"[graphify] Pruned {len(edges_to_remove)} edge(s) from deleted source file(s).",
file=sys.stderr,
)
if not n_nodes and not edges_to_remove:
print(
f"[graphify] {n_files} source file(s) deleted since last run — "
f"no matching nodes in graph, already clean.",
f"no matching nodes or edges in graph, already clean.",
file=sys.stderr,
)
+257 -26
View File
@@ -1,9 +1,11 @@
# per-file extraction cache - skip unchanged files on re-run
from __future__ import annotations
import atexit
import hashlib
import json
import os
import re
import tempfile
from pathlib import Path
@@ -12,15 +14,131 @@ from pathlib import Path
# absolute path ("/shared/graphify-out").
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
# AST cache entries are the output of graphify's own extractor code, so they
# are only valid for the version that wrote them: keying purely on file
# content means extractor fixes shipped in a new release keep serving stale
# pre-fix results. The AST cache is therefore namespaced by package version
# (cache/ast/v{version}/), with entries from other versions removed on first
# use. The semantic cache is deliberately NOT versioned — its entries are
# produced by the LLM from file contents, and invalidating them on every
# release would re-bill extraction for unchanged files.
try:
from importlib.metadata import version as _pkg_version
_EXTRACTOR_VERSION = _pkg_version("graphifyy")
except Exception:
_EXTRACTOR_VERSION = "unknown"
# Version dirs already swept this process — cleanup runs once per (base, version).
_cleaned_ast_dirs: set[str] = set()
def _cleanup_stale_ast_entries(ast_base: Path, current_dir: Path) -> None:
"""Remove AST cache entries left behind by other graphify versions.
Sweeps sibling ``v*/`` directories and unversioned ``*.json`` entries
(the pre-versioning layout) under ``cache/ast/``. Best-effort: failures
are ignored, stragglers are retried on the next run.
"""
key = str(current_dir)
if key in _cleaned_ast_dirs:
return
_cleaned_ast_dirs.add(key)
if not ast_base.is_dir():
return
import shutil
for child in ast_base.iterdir():
if child == current_dir:
continue
try:
if child.is_dir() and child.name.startswith("v"):
shutil.rmtree(child, ignore_errors=True)
elif child.suffix == ".json":
child.unlink()
except OSError:
pass
# A frontmatter delimiter is a whole line of exactly three dashes (optional
# trailing whitespace). Substring checks like startswith("---") /
# find("\n---") also match `----` thematic breaks and `--- text` prose,
# silently dropping everything above them from the hash (#1259).
_FRONTMATTER_DELIM = re.compile(r"^---[ \t]*\r?$", re.MULTILINE)
def _body_content(content: bytes) -> bytes:
"""Strip YAML frontmatter from Markdown content, returning only the body."""
text = content.decode(errors="replace")
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
return text[end + 4:].encode()
return content
opener = _FRONTMATTER_DELIM.match(text)
if opener is None:
return content
closer = _FRONTMATTER_DELIM.search(text, opener.end())
if closer is None:
return content
# Slice right after the closing `---` (not after its line) so the output
# stays byte-identical with the historical implementation for well-formed
# frontmatter -- existing semantic-cache hashes must not churn.
return text[closer.start() + 3:].encode()
# Stat-based index: maps absolute path → {size, mtime_ns, hash}.
# Loaded once per process, flushed via atexit. Skips full file reads when
# size+mtime_ns are unchanged — same trade-off as make(1).
# Correctness risks: `touch` causes a harmless extra re-hash; same-size edits
# within NFS second-resolution mtime have a 1-second window (same as make).
# Use `graphify extract --force` to bypass when needed.
_stat_index: dict[str, dict] = {}
_stat_index_root: Path | None = None
_stat_index_dirty: bool = False
def _stat_index_file(root: Path) -> Path:
_out = Path(_GRAPHIFY_OUT)
base = _out if _out.is_absolute() else Path(root).resolve() / _out
return base / "cache" / "stat-index.json"
def _ensure_stat_index(root: Path) -> None:
global _stat_index, _stat_index_root, _stat_index_dirty
if _stat_index_root is not None:
return
_stat_index_root = Path(root).resolve()
p = _stat_index_file(_stat_index_root)
if p.exists():
try:
_stat_index = json.loads(p.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
_stat_index = {}
else:
_stat_index = {}
atexit.register(_flush_stat_index)
def _flush_stat_index() -> None:
global _stat_index_dirty, _stat_index_root
if not _stat_index_dirty or _stat_index_root is None:
return
p = _stat_index_file(_stat_index_root)
try:
p.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=p.parent, prefix="stat-index.", suffix=".tmp")
try:
os.write(fd, json.dumps(_stat_index, separators=(",", ":")).encode())
os.close(fd)
os.replace(tmp, p)
except Exception:
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(tmp)
except OSError:
pass
except OSError:
pass
_stat_index_dirty = False
def _normalize_path(path: Path) -> Path:
@@ -37,6 +155,10 @@ def _normalize_path(path: Path) -> Path:
def file_hash(path: Path, root: Path = Path(".")) -> str:
"""SHA256 of file contents + path relative to root.
Uses a stat-based fastpath (size + mtime_ns) to skip full reads when the
file hasn't changed. Falls through to full SHA256 on first encounter or
when stat changes. Index is flushed atomically at process exit.
Using a relative path (not absolute) makes cache entries portable across
machines and checkout directories, so shared caches and CI work correctly.
Falls back to the resolved absolute path if the file is outside root.
@@ -44,10 +166,25 @@ 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.
"""
global _stat_index_dirty
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}")
_ensure_stat_index(root)
abs_key = str(p.resolve())
st: "os.stat_result | None" = None
try:
st = p.stat()
entry = _stat_index.get(abs_key)
if (entry
and entry.get("size") == st.st_size
and entry.get("mtime_ns") == st.st_mtime_ns):
return entry["hash"]
except OSError:
pass
raw = p.read_bytes()
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
h = hashlib.sha256()
@@ -58,18 +195,96 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
h.update(rel.as_posix().lower().encode())
except ValueError:
h.update(p.resolve().as_posix().lower().encode())
return h.hexdigest()
digest = h.hexdigest()
if st is not None:
_stat_index[abs_key] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns, "hash": digest}
_stat_index_dirty = True
return digest
def _relativize_source_files_in(payload: dict, root: Path) -> None:
"""Mutate ``payload`` to rewrite absolute ``source_file`` fields as
forward-slash relative paths from ``root``.
Mirror of :func:`graphify.watch._relativize_source_files` so cached
extraction fragments persist in portable form (#777). Already-relative
fields and out-of-root paths pass through unchanged.
Only ``root`` is resolved — ``source_file`` itself is relativized
symbolically so in-root symlinks keep their original name rather than
pointing at the resolved target. Same reasoning as
:func:`graphify.detect._to_relative_for_storage`.
"""
try:
root_resolved = Path(root).resolve()
except OSError:
return
for bucket in ("nodes", "edges", "hyperedges"):
for item in payload.get(bucket, []):
if not isinstance(item, dict):
continue
source = item.get("source_file")
if not source:
continue
sp = Path(source)
if not sp.is_absolute():
continue
try:
rel = os.path.relpath(sp, root_resolved)
except (ValueError, OSError):
continue # out-of-root (e.g. Windows cross-drive)
if rel == ".." or rel.startswith(".." + os.sep) or rel.startswith("../"):
continue # escaped root — keep absolute
item["source_file"] = rel.replace(os.sep, "/")
def _absolutize_source_files_in(payload: dict, root: Path) -> None:
"""Inverse of :func:`_relativize_source_files_in`.
Re-anchor relative ``source_file`` fields against ``root`` so callers
that load a cached fragment see the same absolute-path shape that a
fresh in-process extraction would produce. Legacy cache entries with
absolute ``source_file`` values pass through unchanged.
"""
try:
root_resolved = Path(root).resolve()
except OSError:
return
for bucket in ("nodes", "edges", "hyperedges"):
for item in payload.get(bucket, []):
if not isinstance(item, dict):
continue
source = item.get("source_file")
if not source:
continue
sp = Path(source)
if sp.is_absolute():
continue
try:
item["source_file"] = str(root_resolved / sp)
except (TypeError, OSError):
continue
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
"""Returns the cache directory for ``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).
AST entries live in graphify-out/cache/ast/v{version}/ — namespaced by
graphify version because they depend on extractor code, not just file
contents. Semantic entries live unversioned in graphify-out/cache/semantic/
(re-extraction costs LLM calls).
"""
_out = Path(_GRAPHIFY_OUT)
base = _out if _out.is_absolute() else Path(root).resolve() / _out
d = base / "cache" / kind
if kind == "ast":
d = d / f"v{_EXTRACTOR_VERSION}"
_cleanup_stale_ast_entries(d.parent, d)
d.mkdir(parents=True, exist_ok=True)
return d
@@ -78,10 +293,13 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict |
"""Return cached extraction for this file if hash matches, else None.
Cache key: SHA256 of file contents.
Cache value: stored as graphify-out/cache/{kind}/{hash}.json
Cache value: stored as graphify-out/cache/{kind}/{hash}.json (AST entries
under the per-version subdirectory, see :func:`cache_dir`).
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.
AST entries written by other graphify versions — including the legacy
flat cache/ layout (pre-0.5.3) and the unversioned cache/ast/ layout —
are deliberately not consulted: they were produced by a different
extractor and may be stale.
Returns None if no cache entry or file has changed.
"""
try:
@@ -91,17 +309,15 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict |
entry = cache_dir(root, kind) / f"{h}.json"
if entry.exists():
try:
return json.loads(entry.read_text(encoding="utf-8"))
result = 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
# Re-anchor relative source_file fields so callers see the same
# absolute-path shape that a fresh in-process extraction produces
# (#777). Legacy entries with absolute source_file pass through.
if isinstance(result, dict):
_absolutize_source_files_in(result, root)
return result
return None
@@ -118,12 +334,27 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
p = Path(path)
if not p.is_file():
return
# Relativize source_file fields against ``root`` before write so the
# cache file on disk is portable across machines and checkout
# directories (#777). The cache key is content-hashed so lookup is
# already path-independent; this fixes the embedded path leak.
#
# Serialize a relativized copy rather than mutating the caller's dict —
# downstream pipeline steps (notably extract.py's AST prefix remap, which
# looks up Path(source_file).resolve() in a prefix table) depend on the
# source_file field's original absolute form. Mutating the input here would
# silently break those remaps on the first extraction pass.
on_disk = result
if isinstance(result, dict) and any(result.get(k) for k in ("nodes", "edges", "hyperedges")):
import copy as _copy
on_disk = _copy.deepcopy(result)
_relativize_source_files_in(on_disk, root)
h = file_hash(p, root)
target_dir = cache_dir(root, kind)
entry = target_dir / f"{h}.json"
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
try:
os.write(fd, json.dumps(result).encode())
os.write(fd, json.dumps(on_disk).encode())
os.close(fd)
try:
os.replace(tmp_path, entry)
@@ -152,11 +383,11 @@ def cached_files(root: Path = Path(".")) -> set[str]:
# Legacy flat entries
if base.is_dir():
hashes.update(p.stem for p in base.glob("*.json"))
# Namespaced entries
for kind in ("ast", "semantic"):
# Namespaced entries (ast/ recursively, covering per-version subdirs)
for kind, pattern in (("ast", "**/*.json"), ("semantic", "*.json")):
d = base / kind
if d.is_dir():
hashes.update(p.stem for p in d.glob("*.json"))
hashes.update(p.stem for p in d.glob(pattern))
return hashes
@@ -167,11 +398,11 @@ def clear_cache(root: Path = Path(".")) -> None:
if base.is_dir():
for f in base.glob("*.json"):
f.unlink()
# Namespaced entries
for kind in ("ast", "semantic"):
# Namespaced entries (ast/ recursively, covering per-version subdirs)
for kind, pattern in (("ast", "**/*.json"), ("semantic", "*.json")):
d = base / kind
if d.is_dir():
for f in d.glob("*.json"):
for f in d.glob(pattern):
f.unlink()
+8 -2
View File
@@ -252,6 +252,12 @@ def _node_link_payload(data: dict) -> tuple[list, list] | None:
def load_graph(path: str | Path) -> tuple:
"""Load graph.json. Returns normalized (nodes, edges, hyperedges, metadata)."""
if path:
from graphify.security import check_graph_file_size_cap
try:
check_graph_file_size_cap(Path(path))
except ValueError as exc:
raise SystemExit(f"ERROR: {exc}") from exc
data = read_json(path)
if not isinstance(data, dict):
raise SystemExit(f"ERROR: graph file must contain a JSON object: {path}")
@@ -355,7 +361,7 @@ def html_comment_text(text: str) -> str:
def stable_ascii_id(raw: str, prefix: str = "node", limit: int = 48) -> str:
"""Build a Mermaid-safe ASCII identifier with a hash suffix to avoid collisions."""
raw = str(raw or "")
digest = hashlib.sha1(raw.encode("utf-8")).hexdigest()[:8]
digest = hashlib.sha1(raw.encode("utf-8"), usedforsecurity=False).hexdigest()[:8]
slug = re.sub(r"[^A-Za-z0-9_]+", "_", raw)
slug = re.sub(r"_+", "_", slug).strip("_")
if not slug:
@@ -646,7 +652,7 @@ def html_anchor_id(raw: str, fallback: str, used: set) -> str:
base = base[:48].strip("-") or "section"
candidate = base
if candidate in used:
candidate = f"{base}-{hashlib.sha1(raw.encode('utf-8')).hexdigest()[:6]}"
candidate = f"{base}-{hashlib.sha1(raw.encode('utf-8'), usedforsecurity=False).hexdigest()[:6]}"
suffix = 2
while candidate in used:
candidate = f"{base}-{suffix}"
+98
View File
@@ -0,0 +1,98 @@
"""Cargo manifest introspection for workspace-internal crate dependencies."""
from __future__ import annotations
from pathlib import Path
from typing import Any
_CONFIDENCE_EXTRACTED = "EXTRACTED"
def _load_toml(path: Path) -> dict[str, Any]:
try:
import tomllib # type: ignore[import-not-found]
except ModuleNotFoundError:
try:
import tomli as tomllib # type: ignore[import-not-found,no-redef]
except ModuleNotFoundError:
raise ImportError(
"--cargo on Python 3.10 needs tomli. Install with: pip install tomli"
) from None
with path.open("rb") as manifest:
return tomllib.load(manifest)
def _member_manifest_paths(root: Path, root_data: dict[str, Any]) -> list[Path]:
paths: list[Path] = []
if isinstance(root_data.get("package"), dict):
paths.append(root / "Cargo.toml")
workspace = root_data.get("workspace")
members = workspace.get("members", []) if isinstance(workspace, dict) else []
if not isinstance(members, list):
return paths
for pattern in members:
if not isinstance(pattern, str):
continue
for member in sorted(root.glob(pattern)):
manifest = member / "Cargo.toml"
if manifest.is_file() and manifest not in paths:
paths.append(manifest)
return paths
def introspect_cargo(root: str | Path) -> dict[str, Any]:
"""Return crate nodes and internal dependency edges from Cargo manifests."""
root_path = Path(root).resolve()
root_manifest = root_path / "Cargo.toml"
root_data = _load_toml(root_manifest)
manifests = _member_manifest_paths(root_path, root_data)
crates: dict[str, tuple[str, Path, dict[str, Any]]] = {}
for manifest in manifests:
data = root_data if manifest == root_manifest else _load_toml(manifest)
package = data.get("package")
if not isinstance(package, dict):
continue
name = package.get("name")
if isinstance(name, str):
crates[name] = (f"crate:{name}", manifest, data)
nodes = [
{
"id": crate_id,
"label": name,
"source_file": manifest.relative_to(root_path).as_posix(),
"source_location": "L1",
}
for name, (crate_id, manifest, _data) in sorted(crates.items())
]
edges: list[dict[str, Any]] = []
for source_name, (source_id, manifest, data) in sorted(crates.items()):
dependencies = data.get("dependencies", {})
if not isinstance(dependencies, dict):
continue
source_file = manifest.relative_to(root_path).as_posix()
for dependency_name in sorted(dependencies):
target = crates.get(dependency_name)
if target is None:
continue
edges.append(
{
"source": source_id,
"target": target[0],
"relation": "crate_depends_on",
"context": "cargo_dependency",
"weight": 1.0,
"confidence": _CONFIDENCE_EXTRACTED,
"source_file": source_file,
"source_location": "L1",
}
)
return {"nodes": nodes, "edges": edges}
+60 -9
View File
@@ -19,12 +19,15 @@ def _suppress_output():
return contextlib.redirect_stdout(io.StringIO())
def _partition(G: nx.Graph) -> dict[str, int]:
def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
"""Run community detection. Returns {node_id: community_id}.
Tries Leiden (graspologic) first — best quality.
Falls back to Louvain (built into networkx) if graspologic is not installed.
resolution > 1.0 → more, smaller communities.
resolution < 1.0 → fewer, larger communities.
Output from graspologic is suppressed to prevent ANSI escape codes
from corrupting terminal scroll buffers on Windows PowerShell 5.1.
"""
@@ -49,6 +52,8 @@ def _partition(G: nx.Graph) -> dict[str, int]:
kwargs["random_seed"] = 42
if "trials" in lsig:
kwargs["trials"] = 1
if "resolution" in lsig:
kwargs["resolution"] = resolution
# Suppress graspologic output to prevent ANSI escape codes from
# corrupting PowerShell 5.1 scroll buffer (issue #19)
old_stderr = sys.stderr
@@ -65,7 +70,7 @@ def _partition(G: nx.Graph) -> dict[str, int]:
# Fallback: networkx louvain (available since networkx 2.7).
# Inspect kwargs to stay compatible across NetworkX versions — max_level
# was added in a later release and prevents hangs on large sparse graphs.
kwargs: dict = {"seed": 42, "threshold": 1e-4}
kwargs: dict = {"seed": 42, "threshold": 1e-4, "resolution": resolution}
if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:
kwargs["max_level"] = 10
communities = nx.community.louvain_communities(stable, **kwargs)
@@ -78,7 +83,11 @@ _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]]:
def cluster(
G: nx.Graph,
resolution: float = 1.0,
exclude_hubs_percentile: float | None = None,
) -> dict[int, list[str]]:
"""Run Leiden community detection. Returns {community_id: [node_ids]}.
Community IDs are stable across runs: 0 = largest community after splitting.
@@ -87,6 +96,13 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
Accepts directed or undirected graphs. DiGraphs are converted to undirected
internally since Louvain/Leiden require undirected input.
resolution: passed to Leiden/Louvain. >1.0 = more smaller communities,
<1.0 = fewer larger communities. Default 1.0.
exclude_hubs_percentile: if set (0-100), nodes whose degree exceeds this
percentile are excluded from partitioning and reattached to their
majority-vote neighbour community afterwards. Useful for staging/utility
super-hubs that inflate god-node rankings (#919).
"""
if G.number_of_nodes() == 0:
return {}
@@ -95,14 +111,26 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
if G.number_of_edges() == 0:
return {i: [n] for i, n in enumerate(sorted(G.nodes))}
# Compute hub exclusion set before removing anything so degree is based on full graph
hub_nodes: set[str] = set()
if exclude_hubs_percentile is not None:
degrees = sorted(d for _, d in G.degree())
if degrees:
idx = max(0, int(len(degrees) * exclude_hubs_percentile / 100) - 1)
threshold = degrees[idx]
hub_nodes = {n for n, d in G.degree() if d > threshold}
# Leiden warns and drops isolates - handle them separately
isolates = [n for n in G.nodes() if G.degree(n) == 0]
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0]
# Also exclude hub nodes from partitioning so they don't pull unrelated
# subsystems into the same community
excluded = hub_nodes
isolates = [n for n in G.nodes() if G.degree(n) == 0 and n not in excluded]
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0 and n not in excluded]
connected = G.subgraph(connected_nodes)
raw: dict[int, list[str]] = {}
if connected.number_of_nodes() > 0:
partition = _partition(connected)
partition = _partition(connected, resolution=resolution)
for node, cid in partition.items():
raw.setdefault(cid, []).append(node)
@@ -112,6 +140,24 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
raw[next_cid] = [node]
next_cid += 1
# Reattach excluded hubs by majority-vote neighbour community
if hub_nodes:
node_community: dict[str, int] = {n: cid for cid, nodes in raw.items() for n in nodes}
for hub in sorted(hub_nodes):
votes: dict[int, int] = {}
for nb in G.neighbors(hub):
cid = node_community.get(nb)
if cid is not None:
votes[cid] = votes.get(cid, 0) + 1
if votes:
best = min(votes, key=lambda c: (-votes[c], c))
raw.setdefault(best, []).append(hub)
node_community[hub] = best
else:
raw[next_cid] = [hub]
node_community[hub] = next_cid
next_cid += 1
# Split oversized communities
max_size = max(_MIN_SPLIT_SIZE, int(G.number_of_nodes() * _MAX_COMMUNITY_FRACTION))
final_communities: list[list[str]] = []
@@ -132,8 +178,13 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
second_pass.append(nodes)
final_communities = second_pass
# Re-index by size descending for deterministic ordering
final_communities.sort(key=len, reverse=True)
# Re-index by size descending. The tuple(sorted(nodes)) tiebreak makes this a
# TOTAL order, so an identical grouping always gets identical community IDs.
# Without it, the hundreds of equal-sized small communities are ordered by the
# partitioner's (not seed-stable) enumeration order, so their integer IDs
# permute run-to-run - which reads as massive "community churn" in a per-node
# cid diff even though the actual grouping is reproducible (#1090 follow-up).
final_communities.sort(key=lambda nodes: (-len(nodes), tuple(sorted(map(str, nodes)))))
return {i: sorted(nodes) for i, nodes in enumerate(final_communities)}
@@ -163,7 +214,7 @@ def cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
subgraph = G.subgraph(community_nodes)
actual = subgraph.number_of_edges()
possible = n * (n - 1) / 2
return round(actual / possible, 2) if possible > 0 else 0.0
return actual / possible if possible > 0 else 0.0
def score_all(G: nx.Graph, communities: dict[int, list[str]]) -> dict[int, float]:
+15
View File
@@ -0,0 +1,15 @@
---
description: Build or query a graphify knowledge graph
---
Invoke the `graphify` skill immediately.
Pass the full `/graphify` argument string through unchanged.
If no arguments were supplied, treat the target path as `.`.
Examples:
- `/graphify`
- `/graphify src --update`
- `/graphify query "what connects auth to billing?"`
Do not answer from raw files before handing off to the `graphify` skill.
+220 -25
View File
@@ -6,17 +6,21 @@ Jaro-Winkler verification → same-community boost → union-find merge.
from __future__ import annotations
import math
import re
import unicodedata
from collections import defaultdict
from datasketch import MinHash, MinHashLSH
from rapidfuzz.distance import JaroWinkler
from graphify._minhash import MinHash, MinHashLSH
from rapidfuzz.distance import Jaro, 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 _norm(label: str | None) -> str:
"""Lowercase + collapse non-alphanumeric runs to space (Unicode-aware)."""
if not isinstance(label, str):
label = "" if label is None else str(label)
label = unicodedata.normalize("NFKC", label)
return re.sub(r"[\W_]+", " ", label.casefold(), flags=re.UNICODE).strip()
def _entropy(label: str) -> float:
@@ -46,6 +50,91 @@ def _make_minhash(text: str, num_perm: int = 128) -> MinHash:
return m
# Matches labels whose trailing token is a version/variant suffix:
# digits optionally followed by letters (chip SKUs: ASR1603, M1, Cortex-A55)
# or 2+ letters (codename revisions: cranelr vs cranel).
# Requires the stem to end in a letter so plain words don't accidentally match.
_VARIANT_SUFFIX = re.compile(r"^(.*[a-z])([0-9]+[a-z]*|[a-z]{2,})$")
def _is_variant_pair(a: str, b: str) -> bool:
"""True if a and b are sibling model/SKU variants (same stem, different suffix).
Only applied to short labels (< 12 chars); long labels go through JW normally.
"""
if a == b:
return False
if max(len(a), len(b)) >= 12:
return False
ma, mb = _VARIANT_SUFFIX.match(a), _VARIANT_SUFFIX.match(b)
if not (ma and mb):
return False
return ma.group(1) == mb.group(1) and ma.group(2) != mb.group(2)
def _short_label_blocked(a: str, b: str, jw_score: float) -> bool:
"""Block fuzzy merge for short labels unless it's a same-length single-char substitution.
Insertions/deletions on short strings (cranel/cranelr, M1/M1 Pro) produce
high Jaro-Winkler scores due to the prefix bonus but are almost never true
duplicates — they're abbreviations or variants.
"""
if max(len(a), len(b)) >= 12:
return False
from rapidfuzz.distance import DamerauLevenshtein
# Allow only same-length single-char substitutions (true typos like "Extractor"/"Extractar").
# Block length-differing pairs regardless of score.
if jw_score >= 97.0 and len(a) == len(b) and DamerauLevenshtein.distance(a, b) <= 1:
return False
return True
_DIGIT_RUN = re.compile(r"\d+")
def _numeric_tokens_differ(a: str, b: str) -> bool:
"""True when two labels carry different embedded numbers (#1284).
Long labels that differ only in their digit runs ("ADR 0011 §D5" vs
"ADR 0013 D4", "3.1 Product Goals" vs "1.1 Product Goals", "block3" vs
"block13", "40%+ retention" vs "<20% retention") are numbered/versioned
siblings, not duplicates -- but the long shared boilerplate keeps
Jaro-Winkler above _MERGE_THRESHOLD, and _is_variant_pair only covers
short trailing suffixes. Digit runs are compared as multisets with
leading zeros stripped, so zero-padding ("09" vs "9") does not count as
a difference. (String comparison, not int(): a pathological label with a
>4300-digit run would crash int() on Python's conversion limit.) Labels
with identical numbers, or none at all, are unaffected.
"""
if a == b:
return False
return sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(a)) != \
sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(b))
# file_type values whose identity is anchored to their source location, not
# their label text. Like code (#1205), these must not be label-merged across
# files: rationale = module/class docstrings, document = headings/positional
# content. `concept` is intentionally excluded -- it is the type meant to unify
# across files (protected from over-merge by the numeric/Jaro guards instead).
_FILE_ANCHORED_NONCODE = frozenset({"rationale", "document"})
def _crossfile_fileanchored_blocked(node: dict, neighbor: dict) -> bool:
"""Block label-based merging of file-anchored non-code nodes across files (#1284).
rationale/document nodes are docstring- and heading-derived and as
file-anchored as the code they describe (#1205's reasoning, one layer up):
parallel modules carry near-identical boilerplate ("Django app config for
apps.<name>. No business logic here...") that differs by one word and sails
past the JW threshold. Same-file duplicates of these types may still merge.
"""
if (node.get("file_type") not in _FILE_ANCHORED_NONCODE
and neighbor.get("file_type") not in _FILE_ANCHORED_NONCODE):
return False
return (node.get("source_file") or "") != (neighbor.get("source_file") or "")
# ── union-find ────────────────────────────────────────────────────────────────
class _UF:
@@ -83,6 +172,20 @@ _NUM_PERM = 128
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
def _is_code(node: dict) -> bool:
"""True for AST-extracted code symbols.
Code-node identity is the node ID (which already encodes the fully
qualified path: module/class/symbol). The label is only a display name
(e.g. a bare ``.draw()`` method name, or a function name shared by two
parallel backends), so label-based merging conflates distinct symbols
(#1205). Genuine duplicates — the same symbol re-extracted — share an ID
and are already collapsed by the exact-ID ``seen_ids`` pre-dedup above,
so code never needs label-based merging.
"""
return node.get("file_type") == "code"
# ── main entry point ──────────────────────────────────────────────────────────
def deduplicate_entities(
@@ -130,23 +233,46 @@ def deduplicate_entities(
# ── pass 1: exact normalization ───────────────────────────────────────────
norm_to_nodes: dict[str, list[dict]] = defaultdict(list)
for node in unique_nodes:
# Code symbols are keyed by ID, never by label — skip them entirely so
# distinct same-named symbols are never merged by string similarity (#1205).
if _is_code(node):
continue
key = _norm(node.get("label", node.get("id", "")))
if key:
norm_to_nodes[key].append(node)
uf = _UF()
exact_merges = 0
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)
if len(group) <= 1:
continue
# Partition by source_file — only merge within the same file in Pass 1.
# Cross-file matches fall through to Pass 2 fuzzy matching.
by_file: dict[str, list[dict]] = defaultdict(list)
for node in group:
sf = node.get("source_file") or ""
by_file[sf].append(node)
for sf, file_group in by_file.items():
if not sf:
# No source_file — cannot prove same symbol; skip to avoid
# collapsing distinct nodes that happen to share a label (#1178).
continue
if len(file_group) > 1:
winner = _pick_winner(file_group)
for node in file_group:
uf.union(winner["id"], node["id"])
exact_merges += len(file_group) - 1
# ── pass 2: MinHash/LSH + Jaro-Winkler (high-entropy nodes only) ─────────
candidates: list[dict] = []
seen_norms: set[str] = set()
for node in unique_nodes:
# Code symbols are excluded from fuzzy matching too: two functions with
# similar long names in different files (parallel backends, sibling
# classes) must not be fuzzy-merged, and a code↔concept fuzzy match must
# not transitively union two distinct code symbols via a concept (#1205).
if _is_code(node):
continue
key = _norm(node.get("label", node.get("id", "")))
if key and key not in seen_norms:
seen_norms.add(key)
@@ -157,19 +283,26 @@ def deduplicate_entities(
if len(candidates) >= 2:
lsh = MinHashLSH(threshold=_LSH_THRESHOLD, num_perm=_NUM_PERM)
minhashes: dict[str, MinHash] = {}
# Pre-build O(1) lookup structures so the query loop below doesn't scan
# the candidates list linearly for every LSH neighbor (was O(n²×B)).
candidates_by_id: dict[str, dict] = {}
norm_cache: dict[str, str] = {}
for node in candidates:
norm_label = _norm(node.get("label", node.get("id", "")))
m = _make_minhash(norm_label)
minhashes[node["id"]] = m
node_id = node["id"]
candidates_by_id[node_id] = node
nl = _norm(node.get("label", node.get("id", "")))
norm_cache[node_id] = nl
m = _make_minhash(nl)
minhashes[node_id] = m
try:
lsh.insert(node["id"], m)
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", "")))
norm_label = norm_cache[node_id]
neighbors = lsh.query(minhashes[node_id])
for neighbor_id in neighbors:
@@ -178,22 +311,66 @@ def deduplicate_entities(
if uf.find(node_id) == uf.find(neighbor_id):
continue
neighbor = next((n for n in candidates if n["id"] == neighbor_id), None)
neighbor = candidates_by_id.get(neighbor_id)
if neighbor is None:
continue
neighbor_norm = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
neighbor_norm = norm_cache.get(neighbor_id) or _norm(neighbor.get("label", neighbor.get("id", "")))
# Cross-file long labels score on plain Jaro (no prefix bonus).
# Jaro-Winkler's leading-prefix bonus lifts pairs that share a
# prefix but diverge in a distinguishing token ("testing-library
# jest-native" vs "react-native") past threshold, fabricating
# destructive cross-file merges; on Jaro alone they fall short
# while true cross-file duplicates still clear it (#1243). Same-file
# near-duplicates keep Jaro-Winkler (low-risk, and a mid-string
# stopword insertion needs the prefix bonus to merge); short labels
# keep Jaro-Winkler too (gated by _short_label_blocked).
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
if _xfile and max(len(norm_label), len(neighbor_norm)) >= 12:
score = Jaro.normalized_similarity(norm_label, neighbor_norm) * 100
else:
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
if _is_variant_pair(norm_label, neighbor_norm):
continue
if _short_label_blocked(norm_label, neighbor_norm, score):
continue
# Prefix-extension pairs (getActiveSession / getActiveSessions,
# parseConfig / parseConfigFile) are almost never duplicates —
# one is a strict suffix-extension of the other. Block the merge
# regardless of JW score (#1201).
_lo, _hi = sorted((norm_label, neighbor_norm), key=len)
if _hi.startswith(_lo) and _hi != _lo:
continue
# Numbered/versioned siblings and cross-file file-anchored
# boilerplate (rationale/document) are decisively distinct
# regardless of score (#1284).
if _numeric_tokens_differ(norm_label, neighbor_norm):
continue
if _crossfile_fileanchored_blocked(node, neighbor):
continue
c1 = communities.get(node_id)
c2 = communities.get(neighbor_id)
if c1 is not None and c2 is not None and c1 == c2:
if (c1 is not None and c2 is not None and c1 == c2
and min(len(norm_label), len(neighbor_norm)) >= 12):
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)
# Identical labels across different source files almost always
# means same-named-but-different symbols (trait impls, wrapper
# methods, common type names). Mirror Pass 1's source_file
# partition for this sub-case. (#1046, leaks #895's fix)
if norm_label == neighbor_norm:
sf_a = node.get("source_file") or ""
sf_b = neighbor.get("source_file") or ""
if sf_a != sf_b:
continue
# Pick the winner from the verified pair only. Selecting it
# from the union of both normalized-label groups pulls
# never-compared nodes (same label, different source_file)
# into the merge, bypassing the #1046/#1178 guards.
winner = _pick_winner([node, neighbor])
uf.union(winner["id"], node_id)
uf.union(winner["id"], neighbor_id)
fuzzy_merges += 1
@@ -296,10 +473,28 @@ def _llm_tiebreak(
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
# Mirror pass 2: plain Jaro for cross-file long labels (#1243).
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
if _xfile and max(len(norm_i), len(norm_j)) >= 12:
score = Jaro.normalized_similarity(norm_i, norm_j) * 100
else:
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
if _is_variant_pair(norm_i, norm_j):
continue
if _short_label_blocked(norm_i, norm_j, score):
continue
_lo, _hi = sorted((norm_i, norm_j), key=len)
if _hi.startswith(_lo) and _hi != _lo:
continue
# Mirror pass 2: decisively-distinct pairs never reach the LLM (#1284).
if _numeric_tokens_differ(norm_i, norm_j):
continue
if _crossfile_fileanchored_blocked(node, neighbor):
continue
c1 = communities.get(node["id"])
c2 = communities.get(neighbor["id"])
if c1 is not None and c2 is not None and c1 == c2:
if (c1 is not None and c2 is not None and c1 == c2
and min(len(norm_i), len(norm_j)) >= 12):
score += _COMMUNITY_BOOST
if low <= score < high:
ambiguous.append((node, neighbor, score))
+620 -119
View File
@@ -4,6 +4,8 @@ import fnmatch
import json
import os
import re
import shlex
from concurrent.futures import ThreadPoolExecutor
from enum import Enum
from pathlib import Path
@@ -24,7 +26,7 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
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', '.astro', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk'}
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml', '.cls', '.trigger'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
@@ -33,18 +35,124 @@ VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.w
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
FILE_COUNT_UPPER = 200 # files - above this, warn about token cost
FILE_COUNT_UPPER = 500 # files - above this, warn about token cost
# Files that may contain secrets - skip silently
# Resource caps for parsing untrusted office/PDF files (F2). A corpus is
# attacker-controllable (graphify runs on cloned/shared folders), and .docx/.xlsx
# are zip+XML containers: a few-KB zip-bomb can decompress to gigabytes and
# OOM-kill the process at load_workbook/Document time. Screen the file before any
# parser touches it.
_OFFICE_MAX_RAW_BYTES = 50 * 1024 * 1024 # 50 MiB on-disk
_OFFICE_MAX_DECOMPRESSED_BYTES = 512 * 1024 * 1024 # 512 MiB total uncompressed
_OFFICE_MAX_COMPRESSION_RATIO = 200 # uncompressed : compressed
def _file_within_size_cap(path: Path, cap: int = _OFFICE_MAX_RAW_BYTES) -> bool:
"""True if *path* exists and its on-disk size is within *cap*."""
try:
return path.stat().st_size <= cap
except OSError:
return False
def _zip_within_caps(path: Path) -> bool:
"""Reject a zip-based office file that is a likely zip/XML bomb.
Two layers, because the zip central-directory sizes are attacker-controlled:
1. A cheap pre-filter on the declared sizes (on-disk cap, summed-uncompressed
cap, compression ratio) that rejects an honest bomb without decompressing.
2. An authoritative pass that stream-decompresses every member with a hard
byte ceiling, so a member that under-declares its size in the central
directory cannot expand past the cap undetected. Decompression is chunked
and bounded, so checking a bomb never materializes more than the ceiling.
"""
import zipfile
if not _file_within_size_cap(path):
return False
try:
with zipfile.ZipFile(path) as zf:
infos = zf.infolist()
compressed = sum(i.compress_size for i in infos) or 1
declared = sum(i.file_size for i in infos)
if declared > _OFFICE_MAX_DECOMPRESSED_BYTES:
return False
if declared / compressed > _OFFICE_MAX_COMPRESSION_RATIO:
return False
total = 0
for info in infos:
with zf.open(info) as member:
while True:
chunk = member.read(1024 * 1024)
if not chunk:
break
total += len(chunk)
if total > _OFFICE_MAX_DECOMPRESSED_BYTES:
return False
except (zipfile.BadZipFile, OSError, EOFError):
return False
return True
# Parent directories whose contents are always sensitive.
# Checked against path.parts[:-1] (parents only) so a root-level file named
# "credentials" or "secrets" is not falsely flagged by this stage.
_SENSITIVE_DIRS = frozenset({
".ssh", ".gnupg", ".aws", ".gcloud", "secrets", ".secrets", "credentials",
})
# Files that may contain secrets - skip silently. These patterns are specific
# (extensions, exact credential-store names) and always apply.
_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'\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),
]
# Generic keyword patterns - these only count when the keyword is LOAD-BEARING
# in the filename (see _generic_keyword_hit), because a keyword buried mid-phrase
# in a long descriptive slug names a topic, not a credential store:
# "token-economics-of-recall.md" is a note ABOUT tokens; "api_token.txt" IS one.
# Uses lookarounds instead of \b so underscore-prefixed names like api_token.txt
# match. Both patterns use (?![a-zA-Z]) so that the trailing-underscore behavior
# is consistent: "secret_store.txt" IS flagged, "tokenizer.py" is NOT (because
# "i" after "token" is alpha and blocks the match).
# `token` is kept separate because its longer suffix "izer"/"ize" is the only
# common false-positive; other keywords have no such well-known derivatives.
_GENERIC_KEYWORD_PATTERNS = [
re.compile(r'(?<![a-zA-Z0-9])(credential|secret|passwd|password|private_key)s?(?![a-zA-Z])', re.IGNORECASE),
re.compile(r'(?<![a-zA-Z0-9])tokens?(?![a-zA-Z])', re.IGNORECASE),
]
# Word separators for the load-bearing check (underscore intentionally included;
# multi-word keywords like private_key are handled by the end-of-stem check,
# which runs before word counting).
_WORD_SPLIT = re.compile(r'[-_\s]+')
def _generic_keyword_hit(name: str) -> bool:
"""True if a generic secret keyword appears load-bearing in the filename.
Secret-store files name their contents, and in English compounds the
content noun is the head, which comes last: "github-personal-access-token",
"api_token", "oauth_token". A keyword that is neither at the end of the
stem nor in a short (<=2 word) name is a topic word in a descriptive slug
("token-economics-of-recall.md", "password-policy-discussion.md") and must
not cause the file to be silently dropped from the graph (#436, #718).
"""
# Stem = name up to the first dot, ignoring leading dots so dotfiles like
# ".token" keep their keyword ("" stems would never match).
stem = name.lstrip('.').split('.')[0]
for pat in _GENERIC_KEYWORD_PATTERNS:
hit = False
for m in pat.finditer(stem):
hit = True
if m.end() == len(stem): # keyword ends the stem -> names the contents
return True
if hit and len([w for w in _WORD_SPLIT.split(stem) if w]) <= 2:
return True # short name like token_config.yaml / secret_handler.txt
return False
# Signals that a .md/.txt file is actually a converted academic paper
_PAPER_SIGNALS = [
re.compile(r'\barxiv\b', re.IGNORECASE),
@@ -66,8 +174,17 @@ _PAPER_SIGNAL_THRESHOLD = 3 # need at least this many signals to call it a pape
def _is_sensitive(path: Path) -> bool:
"""Return True if this file likely contains secrets and should be skipped."""
# Stage 1: any PARENT directory is a known secrets dir (parts[:-1] excludes
# the filename itself so a root-level file named "credentials" is not falsely
# skipped — the name patterns in Stage 2 handle the filename).
if any(part in _SENSITIVE_DIRS for part in path.parts[:-1]):
return True
# Stage 2: filename pattern match
name = path.name
return any(p.search(name) for p in _SENSITIVE_PATTERNS)
if any(p.search(name) for p in _SENSITIVE_PATTERNS):
return True
# Stage 3: generic keywords, only when load-bearing in the name
return _generic_keyword_hit(name)
def _looks_like_paper(path: Path) -> bool:
@@ -92,28 +209,187 @@ _SHEBANG_CODE_INTERPRETERS = {
}
def _shebang_file_type(path: Path) -> FileType | None:
"""Peek at the first line of an extensionless file for a shebang."""
def _split_env_s(value: str, rest: list[str]) -> list[str]:
"""Re-tokenize an `env -S`/`--split-string` packed command, prepending the
operand to any trailing args. Returns the unpacked argv."""
packed = " ".join([value, *rest]).strip()
return shlex.split(packed)
def _env_command_args(args: list[str], *, allow_split: bool = True) -> list[str]:
"""Strip leading env(1) options and var assignments, return the trailing
command argv. Covers macOS/BSD and GNU coreutils env documented spellings.
POSIX/macOS short forms:
env [-0iv] [-C workdir] [-P utilpath] [-S string]
[-u name] [name=value ...] [utility [argument ...]]
GNU coreutils long/compact forms additionally supported:
--argv0=ARG / -a ARG / -aARG
--unset=NAME / --unset NAME / -u NAME / -uNAME
--chdir=DIR / --chdir DIR / -C DIR / -CDIR
--split-string=STRING / --split-string STRING
-S STRING / -SSTRING / -vS STRING / -vSSTRING
--ignore-environment / --null / --debug / --list-signal-handling
--default-signal[=SIG] / --ignore-signal[=SIG] / --block-signal[=SIG]
`-S` / `--split-string` payloads are themselves env-style argument lists
per the GNU shebang synopsis:
#!/usr/bin/env -[v]S[option]... [name=value]... command [args]...
so after splitting the payload we recursively re-parse it with
`allow_split=False` (a nested -S inside a split payload is rejected to
bound recursion).
Unknown hyphen-prefixed args yield [] (we refuse to guess whether
their next token is an interpreter or an operand).
"""
i = 0
while i < len(args):
arg = args[i]
if arg == "--":
return args[i + 1:]
# Split-string forms: tokenize the packed payload, then re-parse it
# as env args (so leading assignments/flags inside the payload are
# skipped before the interpreter is identified).
if allow_split:
if arg == "-S":
if i + 1 >= len(args):
return []
return _env_command_args(
_split_env_s(" ".join(args[i + 1:]), []),
allow_split=False,
)
if arg.startswith("-S") and len(arg) > 2:
return _env_command_args(
_split_env_s(arg[2:], args[i + 1:]),
allow_split=False,
)
if arg == "-vS":
if i + 1 >= len(args):
return []
return _env_command_args(
_split_env_s(" ".join(args[i + 1:]), []),
allow_split=False,
)
if arg.startswith("-vS") and len(arg) > 3:
return _env_command_args(
_split_env_s(arg[3:], args[i + 1:]),
allow_split=False,
)
if arg.startswith("--split-string="):
return _env_command_args(
_split_env_s(arg.split("=", 1)[1], args[i + 1:]),
allow_split=False,
)
if arg == "--split-string":
if i + 1 >= len(args):
return []
return _env_command_args(
_split_env_s(args[i + 1], args[i + 2:]),
allow_split=False,
)
# Options with separate required operand
if arg in {"-u", "-C", "-P", "-a", "--unset", "--chdir", "--argv0"}:
if i + 2 > len(args):
return []
i += 2
continue
# Clumped short option + operand
if (
arg.startswith(("-u", "-C", "-P", "-a"))
and len(arg) > 2
and not arg.startswith("--")
):
i += 1
continue
# Long option with `=` operand
if arg.startswith(("--unset=", "--chdir=", "--argv0=")):
i += 1
continue
# No-operand flags
if arg in {"-", "-i", "-0", "-v", "--ignore-environment", "--null",
"--debug", "--list-signal-handling"}:
i += 1
continue
# Signal-handling long flags (with or without =SIG operand — we treat
# them as no-effect for interpreter-resolution purposes)
if arg.startswith(("--default-signal", "--ignore-signal", "--block-signal")):
i += 1
continue
# Unknown hyphen-prefixed: refuse to guess
if arg.startswith("-"):
return []
# Inline NAME=value assignment
if "=" in arg:
i += 1
continue
# First non-option, non-assignment token starts the command argv
return args[i:]
return []
def _shebang_interpreter(path: Path) -> str | None:
"""Return the interpreter name from a shebang line.
Handles forms that a naive parser misses:
- `#!/usr/bin/env -S python3 -u` (env -S split-args form, anywhere)
- `#!/usr/bin/env -i bash` (no-operand env flags)
- `#!/usr/bin/env -u VAR python3` (env options with operands)
- `#!/usr/bin/env -C /tmp python3` (env -C workdir)
- `#!/usr/bin/env -P /bin python3` (env -P utilpath)
- `#!/usr/bin/env DEBUG=1 python3` (inline var assignment)
- `#!"/usr/local/bin/python with spaces"` (shlex handles quotes)
Returns the basename of the resolved interpreter, or None if there is
no shebang / the file is unreadable / parsing fails.
"""
try:
with path.open("rb") as f:
first = f.read(128)
first = f.read(256)
if not first.startswith(b"#!"):
return None
line = first.split(b"\n")[0].decode(errors="replace")
parts = line[2:].strip().split()
line = first.split(b"\n")[0].decode(errors="replace")[2:].strip()
parts = shlex.split(line)
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
interp = Path(parts[0]).name
if interp == "env":
env_args = _env_command_args(parts[1:])
if not env_args:
return None
interp = Path(env_args[0]).name
return interp
except (OSError, ValueError):
return None
def _shebang_file_type(path: Path) -> FileType | None:
"""Peek at the first line of an extensionless file for a shebang."""
interp = _shebang_interpreter(path)
if interp in _SHEBANG_CODE_INTERPRETERS:
return FileType.CODE
return None
def classify_file(path: Path) -> FileType | None:
# Package manifests (apm.yml, pyproject.toml, go.mod, pom.xml) are parsed
# deterministically, so route them to the AST path (CODE) rather than the LLM
# document path — otherwise apm.yml (a .yml "document") would be LLM-extracted
# and a package would split into duplicate file-anchored nodes (#1377).
from graphify.manifest_ingest import is_package_manifest_path
if is_package_manifest_path(path):
return FileType.CODE
# Compound extensions must be checked before simple suffix lookup
if path.name.lower().endswith(".blade.php"):
return FileType.CODE
@@ -145,6 +421,8 @@ def classify_file(path: Path) -> FileType | None:
def extract_pdf_text(path: Path) -> str:
"""Extract plain text from a PDF file using pypdf."""
if not _file_within_size_cap(path):
return ""
try:
from pypdf import PdfReader
reader = PdfReader(str(path))
@@ -160,6 +438,8 @@ def extract_pdf_text(path: Path) -> str:
def docx_to_markdown(path: Path) -> str:
"""Convert a .docx file to markdown text using python-docx."""
if not _zip_within_caps(path):
return ""
try:
from docx import Document
from docx.oxml.ns import qn
@@ -200,6 +480,8 @@ def docx_to_markdown(path: Path) -> str:
def xlsx_to_markdown(path: Path) -> str:
"""Convert an .xlsx file to markdown text using openpyxl."""
if not _zip_within_caps(path):
return ""
try:
import openpyxl
wb = openpyxl.load_workbook(str(path), read_only=True, data_only=True)
@@ -336,10 +618,22 @@ def convert_office_file(path: Path, out_dir: Path) -> Path | None:
return None
out_dir.mkdir(parents=True, exist_ok=True)
# Use a stable name derived from the original path to avoid collisions
# Use a stable name derived from the original path to avoid collisions.
# Normalize the resolved path to NFC before hashing: on macOS (HFS+/APFS)
# os.walk/rglob return filenames in NFD, while Python string literals and
# directly-constructed Path objects are NFC, so the same source file would
# otherwise hash to different sidecar names across runs — causing --update
# to treat every Office file as new and re-extract it (#1226).
import hashlib
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
import unicodedata
normalized_path = unicodedata.normalize("NFC", str(path.resolve()))
name_hash = hashlib.sha256(normalized_path.encode()).hexdigest()[:8]
out_path = out_dir / f"{path.stem}_{name_hash}.md"
# Once the hash is stable the sidecar name is deterministic; skip re-writing
# an existing sidecar so an unchanged source never churns its mtime (which
# would still flag it as changed in detect_incremental).
if out_path.exists():
return out_path
out_path.write_text(
f"<!-- converted from {path.name} -->\n\n{text}",
encoding="utf-8",
@@ -376,6 +670,11 @@ _SKIP_DIRS = {
"__snapshots__", "snapshots", # Jest/Vitest snapshot dirs
"storybook-static", # Storybook production build output
"dist-protected", # Protected dist variants (same noise as dist)
# Framework cache/build dirs — generated, never architecturally meaningful (#873)
".next", ".nuxt", ".turbo", ".angular",
".idea", ".cache", ".parcel-cache", ".svelte-kit", ".terraform", ".serverless",
".graphify", # graphify's own extraction cache — never index self-generated data
".worktrees", # git worktree convention (#947) — sibling checkouts, always redundant
}
# Large generated files that are never useful to extract
@@ -385,7 +684,7 @@ _SKIP_FILES = {
"composer.lock", "go.sum", "go.work.sum",
}
def _is_noise_dir(part: str) -> bool:
def _is_noise_dir(part: str, parent: "Path | None" = None) -> bool:
"""Return True if this directory name looks like a venv, cache, or dep dir."""
if part in _SKIP_DIRS:
return True
@@ -394,6 +693,9 @@ def _is_noise_dir(part: str) -> bool:
return True
if part.endswith(".egg-info"):
return True
# worktrees/ nested inside a dotted dir (e.g. .claude/worktrees/, .git/worktrees/)
if part == "worktrees" and parent is not None and parent.name.startswith("."):
return True
return False
@@ -462,70 +764,118 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
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))
# Merge .gitignore and .graphifyignore for this dir (#1363). Previously
# the presence of a .graphifyignore made graphify skip that dir's
# .gitignore entirely, so a file excluded only by .gitignore (e.g. a
# neutrally-named secret like prod-dump.sql) silently got indexed into
# the graph — whose artifacts embed file contents and are often
# committed. .gitignore is read first and .graphifyignore last, so
# .graphifyignore patterns (including `!` negations) win on conflict via
# last-match-wins; adding a .graphifyignore can only ever exclude MORE,
# never re-include a .gitignore-excluded file (#945 kept: a project with
# only a .gitignore still gets sensible defaults).
for fname in (".gitignore", ".graphifyignore"):
ignore_file = d / fname
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:
def _is_ignored(
path: Path,
root: Path,
patterns: list[tuple[Path, str]],
*,
_cache: dict[Path, bool] | None = None,
) -> bool:
"""Return True if the path should be ignored per .graphifyignore patterns.
Uses gitignore last-match-wins semantics: all patterns are evaluated in
order; the final matching pattern determines the result. Negation patterns
(starting with !) un-ignore a previously ignored path.
Enforces gitignore's parent-exclusion rule: a ! pattern cannot re-include
a file whose ancestor directory is already excluded.
_cache: optional dict shared across calls within the same scan. Ancestor
directory results are memoised so files under the same subtree don't
re-evaluate the same patterns repeatedly.
"""
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):
def _eval(target: Path) -> bool:
"""Apply last-match-wins to a single target path."""
if _cache is not None and target in _cache:
return _cache[target]
def _matches(rel: str, p: str, anchored: bool) -> bool:
if anchored:
return fnmatch.fnmatch(rel, p)
parts = rel.split("/")
if fnmatch.fnmatch(rel, p):
return True
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
if fnmatch.fnmatch(target.name, p):
return True
return False
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
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:
matched = False
if anchored:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p)
rel_anchor = str(target.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p, anchored=True)
except ValueError:
pass
else:
try:
rel = str(target.relative_to(root)).replace(os.sep, "/")
matched = _matches(rel, p, anchored=False)
except ValueError:
pass
if not matched and anchor != root:
try:
rel_anchor = str(target.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p, anchored=False)
except ValueError:
pass
if matched:
result = not negated # last match wins; ! flips to un-ignore
return result
if matched:
result = not negated # last match wins; ! flips to un-ignore
if _cache is not None:
_cache[target] = result
return result
# Gitignore parent-exclusion rule: a ! re-include cannot rescue a file
# whose ancestor directory is already excluded. Walk ancestors top-down;
# if any ancestor is excluded, the file is excluded regardless of later
# ! patterns targeting the file or a sub-path.
try:
rel_parts = path.relative_to(root).parts
except ValueError:
return _eval(path)
ancestor = root
for part in rel_parts[:-1]:
ancestor = ancestor / part
if _eval(ancestor):
return True
return _eval(path)
def _load_graphifyinclude(root: Path) -> list[tuple[Path, str]]:
@@ -563,7 +913,9 @@ def _is_included(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bo
if not patterns:
return False
def _matches(rel: str, p: str) -> bool:
def _matches(rel: str, p: str, anchored: bool) -> bool:
if anchored:
return fnmatch.fnmatch(rel, p)
parts = rel.split("/")
if fnmatch.fnmatch(rel, p):
return True
@@ -584,21 +936,21 @@ def _is_included(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bo
if anchored:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _matches(rel_anchor, p):
if _matches(rel_anchor, p, anchored=True):
return True
except ValueError:
pass
else:
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
if _matches(rel, p):
if _matches(rel, p, anchored=False):
return True
except ValueError:
pass
if anchor != root:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _matches(rel_anchor, p):
if _matches(rel_anchor, p, anchored=False):
return True
except ValueError:
pass
@@ -637,8 +989,29 @@ def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Pa
return False
def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool | None = None) -> dict:
def _auto_follow_symlinks(root: Path) -> bool:
"""Auto-detect: ``True`` if ``root`` has any direct symlinked child.
Allows "fake working dir" patterns (e.g. a folder full of symlinks pointing
at scattered source dirs across the user's machine) to work transparently
without the caller having to know to pass ``follow_symlinks=True``.
Override is always possible by passing an explicit ``follow_symlinks=True``
or ``follow_symlinks=False`` to :func:`detect` / :func:`detect_incremental`.
"""
try:
for p in root.iterdir():
if p.is_symlink():
return True
except (OSError, PermissionError):
pass
return False
def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace: bool | None = None, extra_excludes: list[str] | None = None) -> dict:
root = root.resolve()
if follow_symlinks is None:
follow_symlinks = _auto_follow_symlinks(root)
google_workspace = google_workspace_enabled() if google_workspace is None else google_workspace
files: dict[FileType, list[str]] = {
FileType.CODE: [],
@@ -651,6 +1024,14 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
skipped_sensitive: list[str] = []
ignore_patterns = _load_graphifyignore(root)
ignore_cache: dict[Path, bool] = {} # shared across all _is_ignored calls in this scan
# CLI --exclude patterns are anchored at the scan root and appended last
# so they win over any .graphifyignore/.gitignore rules (#947).
if extra_excludes:
for pat in extra_excludes:
line = _parse_gitignore_line(pat)
if line:
ignore_patterns.append((root, line))
include_patterns = _load_graphifyinclude(root)
# Always include graphify-out/memory/ - query results filed back into the graph
@@ -674,16 +1055,21 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
continue
if not in_memory_tree:
# 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)
# Dot dirs are allowed — users often want .github/, .claude/, etc.
# Framework caches (.next, .nuxt, …) are caught by _is_noise_dir.
# Negations need no special-casing here: _is_ignored already applies
# last-match-wins (so `!dir/` un-ignores a directory and it won't be
# pruned) and the gitignore parent-exclusion rule (a `!` cannot rescue
# a file beneath an excluded dir), so descending an ignored directory to
# look for a re-included file is never necessary. The previous blanket
# `has_negation` disabled directory pruning for EVERY ignored dir whenever
# any `!` rule existed — e.g. a single `!docs/**` made the walk descend
# bin/, obj/, wwwroot/, generated/, … : a pathological slowdown on large
# repos for no correctness gain.
dirnames[:] = [
d for d in dirnames
if (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
and not _is_noise_dir(d)
and (has_negation or not _is_ignored(dp / d, root, ignore_patterns))
if not _is_noise_dir(d, dp)
and not _is_ignored(dp / d, root, ignore_patterns, _cache=ignore_cache)
]
for fname in filenames:
if fname in _SKIP_FILES:
@@ -693,21 +1079,18 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
seen.add(p)
all_files.append(p)
all_files.sort(key=lambda p: str(p))
converted_dir = root / "graphify-out" / "converted"
for p in all_files:
# For memory dir files, skip hidden/noise filtering
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
if not in_memory:
# Hidden files are already excluded via dir pruning above,
# 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)):
continue
if _is_ignored(p, root, ignore_patterns):
if not in_memory and _is_ignored(p, root, ignore_patterns, _cache=ignore_cache):
continue
if _is_sensitive(p):
skipped_sensitive.append(str(p))
@@ -728,7 +1111,7 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
skipped_sensitive.append(str(p) + f" [Google Workspace export failed: {exc}]")
continue
if md_path:
if _is_ignored(md_path, root, ignore_patterns):
if _is_ignored(md_path, root, ignore_patterns, _cache=ignore_cache):
continue
files[ftype].append(str(md_path))
total_words += count_words(md_path)
@@ -739,7 +1122,7 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
if p.suffix.lower() in OFFICE_EXTENSIONS:
md_path = convert_office_file(p, converted_dir)
if md_path:
if _is_ignored(md_path, root, ignore_patterns):
if _is_ignored(md_path, root, ignore_patterns, _cache=ignore_cache):
continue
files[ftype].append(str(md_path))
total_words += count_words(md_path)
@@ -751,6 +1134,9 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
if ftype != FileType.VIDEO:
total_words += count_words(p)
for ftype in files:
files[ftype].sort()
total_files = sum(len(v) for v in files.values())
needs_graph = total_words >= CORPUS_WARN_THRESHOLD
@@ -765,7 +1151,7 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
warning = (
f"Large corpus: {total_files} files · ~{total_words:,} words. "
f"Semantic extraction will be expensive (many Claude tokens). "
f"Consider running on a subfolder, or use --no-semantic to run AST-only."
f"Consider running on a subfolder."
)
return {
@@ -776,6 +1162,7 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
"warning": warning,
"skipped_sensitive": skipped_sensitive,
"graphifyignore_patterns": len(ignore_patterns),
"scan_root": str(root.resolve()),
}
@@ -792,12 +1179,80 @@ def _md5_file(path: Path) -> str:
return h.hexdigest()
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
"""Load the manifest from a previous run. Returns {} on any error."""
def _stat_and_hash(path_str: str) -> tuple[str, float, str] | None:
"""Stat + MD5 a single file; returns None on OSError (e.g. deleted mid-run)."""
try:
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
p = Path(path_str)
return path_str, p.stat().st_mtime, _md5_file(p)
except OSError:
return None
def _to_relative_for_storage(key: str, root: Path) -> str:
"""Return ``key`` as a forward-slash relative path from ``root``.
Keys outside ``root`` (out-of-tree symlinked sources, external --include
paths) and already-relative keys pass through unchanged — mirrors the
fallback in :func:`graphify.watch._relativize_source_files` so the
on-disk artifact survives the round-trip even when some paths cannot be
portably encoded.
Only ``root`` is resolved — the key itself is relativized symbolically
so an in-root symlink (e.g. ``alias.py -> sub/target.py``) is stored
under its own name. Resolving the key would point the stored entry at
the symlink target, and the original key would then miss on reload and
re-extract on every incremental run.
"""
p = Path(key)
if not p.is_absolute():
return key
try:
rel = os.path.relpath(p, Path(root).resolve())
except (ValueError, OSError):
return key # outside root (e.g. Windows cross-drive)
# ``os.path.relpath`` happily produces ``../foo`` for paths outside
# root; mirror the prior ``relative_to``-raises-ValueError semantics by
# keeping out-of-root entries in their absolute form.
if rel == ".." or rel.startswith(".." + os.sep) or rel.startswith("../"):
return key
return rel.replace(os.sep, "/")
def _to_absolute_from_storage(key: str, root: Path) -> str:
"""Inverse of :func:`_to_relative_for_storage`.
Re-anchor a stored key against ``root``. Already-absolute keys
(legacy manifests, out-of-root entries) pass through unchanged so
that newly-loaded manifests from before this change remain readable.
Uses ``Path(root).resolve()`` so the produced absolute path matches
what :func:`detect` returns (which also resolves the scan root).
"""
p = Path(key)
if p.is_absolute():
return str(p)
return str(Path(root).resolve() / p)
def load_manifest(
manifest_path: str = _MANIFEST_PATH,
*,
root: Path | None = None,
) -> dict:
"""Load the manifest from a previous run. Returns {} on any error.
When ``root`` is provided, stored relative keys are re-anchored against
it so callers see absolute paths regardless of on-disk format. Legacy
manifests with absolute keys pass through unchanged, so a graphify-out/
written by an older version (or by a caller that didn't supply ``root``
to :func:`save_manifest`) remains readable.
"""
try:
raw = json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except Exception:
return {}
if root is None or not isinstance(raw, dict):
return raw
return {_to_absolute_from_storage(k, root): v for k, v in raw.items()}
def save_manifest(
@@ -805,6 +1260,7 @@ def save_manifest(
manifest_path: str = _MANIFEST_PATH,
*,
kind: str = "both",
root: Path | None = None,
) -> None:
"""Save current file mtimes + content hashes for change detection.
@@ -814,34 +1270,68 @@ def save_manifest(
kind="semantic" — written by `graphify extract` after semantic extraction.
Stamps semantic_hash; preserves existing ast_hash.
kind="both" — full pipeline: stamps both hashes (default).
When ``root`` is provided, keys are relativized against it before write
(forward-slash, posix-style) so the on-disk manifest is portable across
machines and checkout locations (#777). Out-of-root entries are written
as absolute so they continue to round-trip on the saving machine.
When ``root`` is None the legacy absolute-keyed format is preserved.
"""
existing = load_manifest(manifest_path)
existing = load_manifest(manifest_path, root=root)
def _normalise_entry(entry):
if isinstance(entry, (int, float)):
return {"mtime": entry, "ast_hash": "", "semantic_hash": ""}
if isinstance(entry, dict) and "hash" in entry and "ast_hash" not in entry:
return {"mtime": entry.get("mtime", 0), "ast_hash": entry["hash"], "semantic_hash": ""}
if isinstance(entry, dict):
return entry
return None
# Seed from the existing manifest so incremental callers passing a subset
# of files don't silently erase entries for untouched files (#917).
# Prune entries whose file no longer exists on disk — those are genuine
# deletions that detect_incremental() should treat as gone.
manifest: dict[str, dict] = {}
for file_list in files.values():
for f in file_list:
try:
p = Path(f)
mtime = p.stat().st_mtime
h = _md5_file(p)
except OSError:
continue # file deleted between detect() and manifest write
prev = existing.get(f, {})
# Normalise legacy {mtime, hash} entries to new schema
if isinstance(prev, (int, float)):
prev = {"mtime": prev, "ast_hash": "", "semantic_hash": ""}
elif isinstance(prev, dict) and "hash" in prev and "ast_hash" not in prev:
prev = {"mtime": prev.get("mtime", 0), "ast_hash": prev["hash"], "semantic_hash": ""}
entry: dict = {"mtime": mtime}
if kind in ("ast", "both"):
entry["ast_hash"] = h
else:
entry["ast_hash"] = prev.get("ast_hash", "")
if kind in ("semantic", "both"):
entry["semantic_hash"] = h
else:
# Preserve semantic_hash only when content is unchanged
entry["semantic_hash"] = prev.get("semantic_hash", "") if h == prev.get("ast_hash", "") else ""
manifest[f] = entry
for f, entry in existing.items():
normalised = _normalise_entry(entry)
if normalised is None:
continue
try:
if Path(f).exists():
manifest[f] = normalised
except OSError:
continue
all_files = [f for file_list in files.values() for f in file_list]
with ThreadPoolExecutor() as pool:
raw = pool.map(_stat_and_hash, all_files)
hashed: dict[str, tuple[float, str]] = {
r[0]: (r[1], r[2]) for r in raw if r is not None
}
for f in all_files:
if f not in hashed:
continue # file deleted between detect() and manifest write
mtime, h = hashed[f]
prev = _normalise_entry(existing.get(f, {})) or {}
entry: dict = {"mtime": mtime}
if kind in ("ast", "both"):
entry["ast_hash"] = h
else:
entry["ast_hash"] = prev.get("ast_hash", "")
if kind in ("semantic", "both"):
entry["semantic_hash"] = h
else:
# Preserve semantic_hash only when content is unchanged
entry["semantic_hash"] = prev.get("semantic_hash", "") if h == prev.get("ast_hash", "") else ""
manifest[f] = entry
if root is not None:
# Persist in portable form: forward-slash relative paths. Keys outside
# ``root`` (out-of-tree symlinked corpora, --include sources) keep
# their absolute form so the manifest round-trips on the saving
# machine even when not every entry can be portably encoded.
manifest = {_to_relative_for_storage(k, root): v for k, v in manifest.items()}
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
Path(manifest_path).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
@@ -850,9 +1340,10 @@ def detect_incremental(
root: Path,
manifest_path: str = _MANIFEST_PATH,
*,
follow_symlinks: bool = False,
follow_symlinks: bool | None = None,
google_workspace: bool | None = None,
kind: str = "semantic",
extra_excludes: list[str] | None = None,
) -> dict:
"""Like detect(), but returns only new or modified files since the last run.
@@ -874,10 +1365,14 @@ def detect_incremental(
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.
incremental runs. ``None`` (default) means auto-detect: ``True`` when ``root``
contains at least one direct symlinked child, ``False`` otherwise.
"""
full = detect(root, follow_symlinks=follow_symlinks, google_workspace=google_workspace)
manifest = load_manifest(manifest_path)
full = detect(root, follow_symlinks=follow_symlinks, google_workspace=google_workspace, extra_excludes=extra_excludes)
# Pass ``root`` so a manifest written with relative keys (post-#777) is
# re-anchored to the absolute form the rest of this function compares
# against. Legacy absolute-keyed manifests pass through unchanged.
manifest = load_manifest(manifest_path, root=root)
if not manifest:
# No previous run - treat everything as new
@@ -912,6 +1407,12 @@ def detect_incremental(
changed = True
else:
stored_mtime = stored.get("mtime")
# Schema-drift guard (#1163): tolerate a nested {mtime: ...}
# dict or any non-numeric value without crashing.
if isinstance(stored_mtime, dict):
stored_mtime = stored_mtime.get("mtime")
if not isinstance(stored_mtime, (int, float)):
stored_mtime = None
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_hash
+390
View File
@@ -0,0 +1,390 @@
"""Read-only diagnostics for MultiDiGraph readiness."""
from __future__ import annotations
import json
import re
from collections import Counter, defaultdict
from copy import deepcopy
from pathlib import Path
from typing import Any
import networkx as nx
_SUPPRESSION_DECL_RE = re.compile(r"^\s*(?P<name>seen_[A-Za-z0-9_]+)\s*[:=]")
_TYPE_TUPLE_RE = re.compile(r"set\[tuple\[(?P<inside>[^\]]+)\]\]")
def _safe_text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, (str, int, float, bool)):
return str(value)
return json.dumps(value, sort_keys=True, default=str, ensure_ascii=False)
def _edge_list(extraction: dict[str, Any]) -> list[Any]:
edges = extraction.get("edges")
if edges is None:
edges = extraction.get("links")
return edges if isinstance(edges, list) else []
def _node_ids(extraction: dict[str, Any]) -> set[str]:
nodes = extraction.get("nodes", [])
if not isinstance(nodes, list):
return set()
return {
str(node["id"])
for node in nodes
if isinstance(node, dict) and "id" in node and node.get("id") is not None
}
def _canonical_edge(edge: Any) -> dict[str, str]:
if not isinstance(edge, dict):
return {
"source": "",
"target": "",
"relation": "",
"confidence": "",
"source_file": "",
"source_location": "",
"context": "",
"_invalid": "non_object_edge",
}
source = edge.get("source", edge.get("from"))
target = edge.get("target", edge.get("to"))
return {
"source": _safe_text(source),
"target": _safe_text(target),
"relation": _safe_text(edge.get("relation")),
"confidence": _safe_text(edge.get("confidence")),
"source_file": _safe_text(edge.get("source_file")),
"source_location": _safe_text(edge.get("source_location")),
"context": _safe_text(edge.get("context")),
"_invalid": "",
}
def _exact_signature(edge: Any) -> str:
if not isinstance(edge, dict):
return "<non-object>"
normalized = dict(edge)
if "source" not in normalized and "from" in normalized:
normalized["source"] = normalized["from"]
if "target" not in normalized and "to" in normalized:
normalized["target"] = normalized["to"]
normalized.pop("from", None)
normalized.pop("to", None)
return json.dumps(
normalized,
sort_keys=True,
default=str,
ensure_ascii=False,
separators=(",", ":"),
)
def _count_extra(counter: Counter[Any]) -> int:
return sum(count - 1 for count in counter.values() if count > 1)
def _variant_group_count(
grouped_edges: dict[tuple[str, str], list[dict[str, str]]],
field: str,
*,
relation_sensitive: bool = False,
) -> int:
groups = 0
for edges in grouped_edges.values():
if relation_sensitive:
by_relation: dict[str, set[str]] = defaultdict(set)
for edge in edges:
by_relation[edge["relation"]].add(edge[field])
groups += sum(1 for values in by_relation.values() if len(values) > 1)
elif len({edge[field] for edge in edges}) > 1:
groups += 1
return groups
def _tuple_arity_from_annotation(line: str) -> int:
match = _TYPE_TUPLE_RE.search(line)
if not match:
return 0
inside = match.group("inside").strip()
if not inside:
return 0
return inside.count(",") + 1
def scan_producer_suppression_sites(path: str | Path) -> dict[str, Any]:
"""Find likely `seen_*` producer-suppression sets in an extractor file."""
source_path = Path(path)
if not source_path.exists():
return {
"path": str(source_path),
"total_sites": 0,
"sites": [],
"error": "file not found",
}
sites: list[dict[str, Any]] = []
lines = source_path.read_text(encoding="utf-8").splitlines()
for lineno, line in enumerate(lines, start=1):
match = _SUPPRESSION_DECL_RE.match(line)
if not match:
continue
sites.append(
{
"line": lineno,
"name": match.group("name"),
"tuple_arity": _tuple_arity_from_annotation(line),
"sample": line.strip()[:120],
}
)
return {
"path": str(source_path),
"total_sites": len(sites),
"sites": sites,
"error": "",
}
def diagnose_extraction(
extraction: dict[str, Any],
*,
directed: bool = True,
root: str | Path | None = None,
max_examples: int = 5,
extract_path: str | Path | None = None,
) -> dict[str, Any]:
"""Summarize same-endpoint edge-collapse risk for one JSON graph/extraction dict."""
from graphify.build import build_from_json
node_ids = _node_ids(extraction)
raw_edges = _edge_list(extraction)
canonical_edges = [_canonical_edge(edge) for edge in raw_edges]
exact_counts: Counter[str] = Counter(_exact_signature(edge) for edge in raw_edges)
directed_pairs: Counter[tuple[str, str]] = Counter()
undirected_pairs: Counter[tuple[str, str]] = Counter()
grouped: dict[tuple[str, str], list[dict[str, str]]] = defaultdict(list)
non_object_edges = 0
missing_endpoint_edges = 0
dangling_endpoint_edges = 0
self_loop_edges = 0
valid_candidate_edges = 0
for edge in canonical_edges:
if edge["_invalid"]:
non_object_edges += 1
continue
source = edge["source"]
target = edge["target"]
if not source or not target:
missing_endpoint_edges += 1
continue
if source not in node_ids or target not in node_ids:
dangling_endpoint_edges += 1
continue
if source == target:
self_loop_edges += 1
valid_candidate_edges += 1
directed_pair = (source, target)
undirected_pair = (source, target) if source <= target else (target, source)
directed_pairs[directed_pair] += 1
undirected_pairs[undirected_pair] += 1
grouped[directed_pair].append(edge)
examples: list[dict[str, Any]] = []
if max_examples > 0:
for (source, target), count in directed_pairs.most_common():
if count < 2:
continue
edges = grouped[(source, target)]
examples.append(
{
"source": source,
"target": target,
"edge_count": count,
"relations": sorted({edge["relation"] for edge in edges}),
"source_files": sorted({edge["source_file"] for edge in edges}),
"source_locations": sorted({edge["source_location"] for edge in edges}),
"contexts": sorted({edge["context"] for edge in edges}),
}
)
if len(examples) >= max_examples:
break
build_error = ""
graph_type = ""
post_build_edge_count: int | None = None
post_build_node_count: int | None = None
try:
graph_input = deepcopy(extraction)
graph: nx.Graph = build_from_json(graph_input, directed=directed, root=root)
graph_type = type(graph).__name__
post_build_edge_count = graph.number_of_edges()
post_build_node_count = graph.number_of_nodes()
except Exception as exc:
build_error = f"{type(exc).__name__}: {exc}"
suppression_path = (
Path(extract_path) if extract_path else Path(__file__).with_name("extract.py")
)
return {
"node_count": len(node_ids),
"raw_edge_count": len(raw_edges),
"non_object_edges": non_object_edges,
"missing_endpoint_edges": missing_endpoint_edges,
"dangling_endpoint_edges": dangling_endpoint_edges,
"self_loop_edges": self_loop_edges,
"valid_candidate_edges": valid_candidate_edges,
"exact_duplicate_edges": _count_extra(exact_counts),
"directed_unique_endpoint_pairs": len(directed_pairs),
"directed_same_endpoint_collapsed_edges": _count_extra(directed_pairs),
"undirected_unique_endpoint_pairs": len(undirected_pairs),
"undirected_same_endpoint_collapsed_edges": _count_extra(undirected_pairs),
"same_endpoint_group_count": sum(1 for count in directed_pairs.values() if count > 1),
"relation_variant_groups": _variant_group_count(grouped, "relation"),
"source_file_variant_groups": _variant_group_count(
grouped, "source_file", relation_sensitive=True
),
"source_location_variant_groups": _variant_group_count(
grouped, "source_location", relation_sensitive=True
),
"context_variant_groups": _variant_group_count(grouped, "context", relation_sensitive=True),
"post_build_graph_type": graph_type,
"post_build_node_count": post_build_node_count,
"post_build_edge_count": post_build_edge_count,
"post_build_error": build_error,
"producer_suppression": scan_producer_suppression_sites(suppression_path),
"examples": examples,
}
def _read_json_file(path: str | Path) -> dict[str, Any]:
"""Read a JSON graph after applying Graphify's graph-load size cap."""
from graphify.security import check_graph_file_size_cap
json_path = Path(path)
check_graph_file_size_cap(json_path)
data = json.loads(json_path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("diagnostic input must be a JSON object")
return data
def diagnose_file(
path: str | Path,
*,
directed: bool | None = None,
root: str | Path | None = None,
max_examples: int = 5,
extract_path: str | Path | None = None,
) -> dict[str, Any]:
"""Diagnose a graph/extraction JSON file without mutating it.
When `directed` is None, the JSON's "directed" flag is honored. Raw
extraction JSON that has no "directed" flag defaults to directed analysis.
"""
data = _read_json_file(path)
if directed is None:
raw_directed = data.get("directed")
effective_directed = raw_directed if isinstance(raw_directed, bool) else True
else:
effective_directed = directed
summary = diagnose_extraction(
data,
directed=effective_directed,
root=root,
max_examples=max_examples,
extract_path=extract_path,
)
summary["input_path"] = str(path)
summary["effective_directed"] = effective_directed
return summary
def format_diagnostic_json(summary: dict[str, Any]) -> dict[str, Any]:
return {
"schema_version": 1,
"summary": {
key: value
for key, value in summary.items()
if key not in {"examples", "producer_suppression"}
},
"examples": summary.get("examples", []),
"producer_suppression": summary.get("producer_suppression", {}),
"notes": [
"Diagnostics are read-only.",
"A normal graph.json is already post-build and cannot recover raw producer edges.",
"Producer suppression sites are heuristic source-code evidence.",
],
}
def format_diagnostic_report(summary: dict[str, Any]) -> str:
suppression = summary.get("producer_suppression", {})
lines = [
"[graphify] MultiDiGraph edge-collapse diagnostic",
f"input: {summary.get('input_path', '<in-memory>')}",
"input_stage: provided JSON (normal graph.json is post-build)",
f"effective_directed: {summary.get('effective_directed', '<direct-call>')}",
f"nodes: {summary['node_count']}",
f"raw_edges: {summary['raw_edge_count']}",
f"valid_candidate_edges: {summary['valid_candidate_edges']}",
f"missing_endpoint_edges: {summary['missing_endpoint_edges']}",
f"dangling_endpoint_edges: {summary['dangling_endpoint_edges']}",
f"self_loop_edges: {summary['self_loop_edges']}",
f"exact_duplicate_edges: {summary['exact_duplicate_edges']}",
f"directed_unique_endpoint_pairs: {summary['directed_unique_endpoint_pairs']}",
(
"directed_same_endpoint_collapsed_edges: "
f"{summary['directed_same_endpoint_collapsed_edges']}"
),
f"undirected_unique_endpoint_pairs: {summary['undirected_unique_endpoint_pairs']}",
(
"undirected_same_endpoint_collapsed_edges: "
f"{summary['undirected_same_endpoint_collapsed_edges']}"
),
f"same_endpoint_group_count: {summary['same_endpoint_group_count']}",
f"relation_variant_groups: {summary['relation_variant_groups']}",
f"source_file_variant_groups: {summary['source_file_variant_groups']}",
f"source_location_variant_groups: {summary['source_location_variant_groups']}",
f"context_variant_groups: {summary['context_variant_groups']}",
f"post_build_graph_type: {summary['post_build_graph_type']}",
f"post_build_edges: {summary['post_build_edge_count']}",
f"producer_suppression_sites: {suppression.get('total_sites', 0)}",
]
if summary.get("post_build_error"):
lines.append(f"post_build_error: {summary['post_build_error']}")
if suppression.get("error"):
lines.append(f"producer_suppression_error: {suppression['error']}")
if suppression.get("sites"):
lines.append("producer_suppression_examples:")
for site in suppression["sites"][:8]:
lines.append(
f" - L{site['line']} {site['name']} arity={site['tuple_arity'] or 'unknown'}"
)
if summary.get("examples"):
lines.append("examples:")
for example in summary["examples"]:
lines.append(
" - "
f"{example['source']} -> {example['target']} "
f"edges={example['edge_count']} "
f"relations={example['relations']} "
f"locations={example['source_locations']} "
f"contexts={example['contexts']}"
)
lines.append(
"note: normal graph.json is post-build; raw producer loss must be measured earlier."
)
return "\n".join(lines)
+271 -12
View File
@@ -1,10 +1,14 @@
# write graph to HTML, JSON, SVG, GraphML, Obsidian vault, and Neo4j Cypher
from __future__ import annotations
import hashlib
import html as _html
import json
import math
import os
import re
import shutil
from collections import Counter
from datetime import date
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
@@ -12,6 +16,83 @@ from graphify.security import sanitize_label
from graphify.analyze import _node_community_map
from graphify.build import edge_data
# Artifacts worth preserving across rebuilds (non-regenerable without LLM or curation).
_BACKUP_ARTIFACTS = [
"graph.json",
"GRAPH_REPORT.md",
".graphify_labels.json",
".graphify_analysis.json",
"manifest.json",
".graphify_semantic_marker",
"cost.json",
]
def backup_if_protected(out_dir: Path) -> "Path | None":
"""Snapshot graph artifacts to a dated subfolder before an overwrite.
Triggers when graph.json exists AND either:
- .graphify_semantic_marker is present (graph cost real LLM tokens), or
- .graphify_labels.json contains at least one non-default community label
(graph has been curated by a human or skill).
Returns the backup folder path, or None if no backup was taken.
Never raises — backup failure prints a warning but never blocks the write.
Set GRAPHIFY_NO_BACKUP=1 to disable.
"""
if os.environ.get("GRAPHIFY_NO_BACKUP"):
return None
out = Path(out_dir)
if not (out / "graph.json").exists():
return None
is_semantic = (out / ".graphify_semantic_marker").exists()
is_curated = False
labels_file = out / ".graphify_labels.json"
if labels_file.exists():
try:
labels = json.loads(labels_file.read_text(encoding="utf-8"))
is_curated = any(v != f"Community {k}" for k, v in labels.items())
except Exception:
pass
if not is_semantic and not is_curated:
return None
reason = "+".join(filter(None, ["semantic" if is_semantic else "", "curated" if is_curated else ""]))
today = date.today().isoformat()
backup_dir = out / today
graph_src = out / "graph.json"
# Skip re-copying if today's backup already has identical graph.json content.
# If content differs (graph changed since the last backup today), overwrite
# the backup in place — one folder per day, always the latest pre-overwrite state.
if backup_dir.exists() and (backup_dir / "graph.json").exists():
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
if src_hash == bak_hash:
return backup_dir # identical content, nothing to do
try:
backup_dir.mkdir(parents=True, exist_ok=True)
copied = 0
for name in _BACKUP_ARTIFACTS:
src = out / name
if src.exists():
try:
shutil.copy2(src, backup_dir / name)
copied += 1
except Exception:
pass
if copied:
print(f"[graphify] backed up {reason} graph ({copied} files) -> {backup_dir.name}/")
return backup_dir
except Exception as exc:
import sys
print(f"[graphify] warning: backup failed ({exc}) - continuing with overwrite", file=sys.stderr)
return None
def _obsidian_tag(name: str) -> str:
"""Sanitize a community name for use as an Obsidian tag.
@@ -21,8 +102,10 @@ def _obsidian_tag(name: str) -> str:
return re.sub(r"[^a-zA-Z0-9_\-/]", "", name.replace(" ", "_"))
def _strip_diacritics(text: str) -> str:
def _strip_diacritics(text: str | None) -> str:
import unicodedata
if not isinstance(text, str):
text = "" if text is None else str(text)
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
@@ -398,11 +481,13 @@ def _git_head() -> str | None:
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:
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None, community_labels: dict[int, 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:
from graphify.security import check_graph_file_size_cap
check_graph_file_size_cap(existing_path)
existing_data = json.loads(existing_path.read_text(encoding="utf-8"))
existing_n = len(existing_data.get("nodes", []))
new_n = G.number_of_nodes()
@@ -410,9 +495,12 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
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.",
f"graph.json has {existing_n} (net -{existing_n - new_n}). "
f"Refusing to overwrite. Possible causes: missing chunk files from "
f"a previous session, or fuzzy dedup collapsed same-named symbols "
f"across files during an --update on an already-current graph. "
f"Run a full rebuild (/graphify .) to be safe, or pass force=True "
f"only if you have verified the reduction is legitimate.",
file=_sys.stderr,
)
return False
@@ -420,12 +508,16 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
pass # unreadable existing file — proceed with write
node_community = _node_community_map(communities)
_labels: dict[int, str] = {int(k): v for k, v in (community_labels or {}).items()}
try:
data = json_graph.node_link_data(G, edges="links")
except TypeError:
data = json_graph.node_link_data(G)
for node in data["nodes"]:
node["community"] = node_community.get(node["id"])
cid = node_community.get(node["id"])
node["community"] = cid
if cid is not None and _labels:
node["community_name"] = _labels.get(cid, f"Community {cid}")
node["norm_label"] = _strip_diacritics(node.get("label", "")).lower()
for link in data["links"]:
if "confidence_score" not in link:
@@ -580,6 +672,30 @@ def to_html(
return
meta_communities = {cid: [str(cid)] for cid in communities}
mc = {cid: len(members) for cid, members in communities.items()}
# Remap hyperedges from semantic node IDs to community IDs
raw_hyperedges = G.graph.get("hyperedges", [])
if raw_hyperedges:
remapped = []
for he in raw_hyperedges:
he_members = he.get("nodes") or he.get("members") or []
comm_ids, seen = [], set()
for nid in he_members:
c = node_to_community.get(nid)
if c is None:
continue
s = str(c)
if s in seen:
continue
seen.add(s)
comm_ids.append(s)
if len(comm_ids) < 2:
continue
remapped.append({
"id": he.get("id", ""),
"label": he.get("label") or he.get("relation", "").replace("_", " "),
"nodes": comm_ids,
})
meta.graph["hyperedges"] = remapped
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)")
@@ -670,7 +786,9 @@ def to_html(
<head>
<meta charset="UTF-8">
<title>graphify - {title}</title>
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<script src="https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js"
integrity="sha384-Ux6phic9PEHJ38YtrijhkzyJ8yQlH8i/+buBR8s3mAZOJrP1gwyvAcIYl3GWtpX1"
crossorigin="anonymous"></script>
{_html_styles()}
</head>
<body>
@@ -705,6 +823,23 @@ def to_html(
generate_html = to_html
def _cap_filename(s: str, limit: int = 200) -> str:
"""Cap a filename stem to ``limit`` UTF-8 bytes so it stays under the 255-byte
filesystem limit even after the ``.md`` extension and dedup suffix are added
(#1094). The cap is on BYTES, not chars, because a label of multibyte
characters (CJK, accented) can exceed 255 bytes well under 255 chars. When
truncation happens, an 8-char hash of the full label is appended so two
distinct labels sharing a long prefix produce distinct, deterministic
filenames instead of colliding."""
b = s.encode("utf-8")
if len(b) <= limit:
return s
digest = hashlib.sha1(s.encode("utf-8")).hexdigest()[:8] # nosec - not security
keep = limit - 9 # "_" + 8 hex chars
truncated = b[:keep].decode("utf-8", "ignore") # "ignore" drops a split trailing char
return f"{truncated}_{digest}"
def to_obsidian(
G: nx.Graph,
communities: dict[int, list[str]],
@@ -731,7 +866,7 @@ def to_obsidian(
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
# Strip trailing .md/.mdx/.markdown so "CLAUDE.md" doesn't become "CLAUDE.md.md"
cleaned = re.sub(r"\.(md|mdx|qmd|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
return _cap_filename(cleaned) if cleaned else "unnamed"
node_filename: dict[str, str] = {}
seen_names: dict[str, int] = {}
@@ -841,12 +976,18 @@ def to_obsidian(
return len(neighbor_cids)
community_notes_written = 0
for cid, members in communities.items():
for cid, all_members in communities.items():
community_name = (
community_labels.get(cid, f"Community {cid}")
if community_labels and cid is not None
else f"Community {cid}"
)
# A community's member list can contain ids with no backing node in G
# (e.g. pruned nodes, stale community assignments from a prior run, or
# synthesized/merge-artifact ids). Dereferencing those via G.nodes[n] or
# node_filename[n] raises KeyError and aborts the whole vault export, so
# skip dangling members rather than crashing (issue #1236).
members = [m for m in all_members if m in G and m in node_filename]
n_members = len(members)
coh_value = cohesion.get(cid) if cohesion else None
@@ -971,7 +1112,7 @@ def to_canvas(
def safe_name(label: str) -> str:
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
cleaned = re.sub(r"\.(md|mdx|qmd|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
return _cap_filename(cleaned) if cleaned else "unnamed"
# Build node_filenames if not provided (same dedup logic as to_obsidian)
if node_filenames is None:
@@ -986,6 +1127,13 @@ def to_canvas(
seen_names[base] = 0
node_filenames[node_id] = base
# Fallback: with no community data (e.g. --no-cluster builds or a missing
# analysis sidecar) the grid below produces nothing and the canvas is written
# as an empty 32-byte shell on an otherwise populated graph. Emit every node
# into one synthetic community so the canvas always reflects the graph (#1324).
if not communities and G.number_of_nodes() > 0:
communities = {0: [str(n) for n in G.nodes()]}
num_communities = len(communities)
cols = math.ceil(math.sqrt(num_communities)) if num_communities > 0 else 1
rows = math.ceil(num_communities / cols) if num_communities > 0 else 1
@@ -1148,7 +1296,10 @@ def push_to_neo4j(
with driver.session() as session:
for node_id, data in G.nodes(data=True):
props = {k: v for k, v in data.items() if isinstance(v, (str, int, float, bool))}
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
props["id"] = node_id
cid = node_community.get(node_id)
if cid is not None:
@@ -1163,7 +1314,10 @@ def push_to_neo4j(
for u, v, data in G.edges(data=True):
rel = _safe_rel(data.get("relation", "RELATED_TO"))
props = {k: v for k, v in data.items() if isinstance(v, (str, int, float, bool))}
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
session.run(
f"MATCH (a {{id: $src}}), (b {{id: $tgt}}) "
f"MERGE (a)-[r:{rel}]->(b) SET r += $props",
@@ -1177,6 +1331,102 @@ def push_to_neo4j(
return {"nodes": nodes_pushed, "edges": edges_pushed}
def push_to_falkordb(
G: nx.Graph,
uri: str,
user: str | None = None,
password: str | None = None,
communities: dict[int, list[str]] | None = None,
graph_name: str = "graphify",
) -> dict[str, int]:
"""Push graph directly to a running FalkorDB instance via the Python SDK.
Requires: pip install falkordb
FalkorDB is OpenCypher-compatible, so the MERGE/SET upsert queries are
identical to push_to_neo4j. Differences from the Neo4j path:
- connects with FalkorDB(host, port, username, password) instead of a bolt
driver; only the host/port are read from the URI, so the scheme is
informational - "falkordb://localhost:6379", "redis://localhost:6379"
and a bare "localhost:6379" are all equivalent (default port 6379).
- a named graph is selected via db.select_graph(graph_name) (default
"graphify"); FalkorDB keys each graph by name in the same instance.
- queries run via graph.query(cypher, params) - there is no session object.
- auth is optional (FalkorDB runs without credentials by default), so user
and password may be None.
- no APOC: the Neo4j path does not use APOC either, so nothing to port.
Uses MERGE so re-running is safe - nodes and edges are upserted, not
duplicated. Returns a dict with counts of nodes and edges pushed.
"""
try:
from falkordb import FalkorDB
except ImportError as e:
raise ImportError(
"falkordb SDK not installed. Run: pip install falkordb"
) from e
from urllib.parse import urlparse
node_community = _node_community_map(communities) if communities else {}
def _safe_rel(relation: str) -> str:
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
def _safe_label(label: str) -> str:
"""Sanitize a FalkorDB node label to prevent Cypher injection."""
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
return sanitized if sanitized else "Entity"
parsed = urlparse(uri if "://" in uri else f"redis://{uri}")
# FalkorDB auth is optional. Only send credentials when a password is
# provided; otherwise connect anonymously and ignore any bolt-style default
# username (e.g. Neo4j's "neo4j"), which FalkorDB rejects as an unknown ACL
# user. Credentials embedded in the URI take precedence over the args.
connect_user = parsed.username or (user if password else None)
connect_password = parsed.password or (password or None)
db = FalkorDB(
host=parsed.hostname or "localhost",
port=parsed.port or 6379,
username=connect_user,
password=connect_password,
)
graph = db.select_graph(graph_name)
nodes_pushed = 0
edges_pushed = 0
for node_id, data in G.nodes(data=True):
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
props["id"] = node_id
cid = node_community.get(node_id)
if cid is not None:
props["community"] = cid
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
graph.query(
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
{"id": node_id, "props": props},
)
nodes_pushed += 1
for u, v, data in G.edges(data=True):
rel = _safe_rel(data.get("relation", "RELATED_TO"))
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
graph.query(
f"MATCH (a {{id: $src}}), (b {{id: $tgt}}) "
f"MERGE (a)-[r:{rel}]->(b) SET r += $props",
{"src": u, "tgt": v, "props": props},
)
edges_pushed += 1
return {"nodes": nodes_pushed, "edges": edges_pushed}
def to_graphml(
G: nx.Graph,
communities: dict[int, list[str]],
@@ -1191,6 +1441,15 @@ def to_graphml(
node_community = _node_community_map(communities)
for node_id in H.nodes():
H.nodes[node_id]["community"] = node_community.get(node_id, -1)
# Drop internal markers (e.g. the AST-provenance "_origin" tag, #1116, and
# the "_src"/"_tgt" direction markers) — they are persistence/runtime details,
# not graph data, and should not leak into the exported file.
for _, attrs in H.nodes(data=True):
for k in [k for k in attrs if k.startswith("_")]:
del attrs[k]
for _, _, attrs in H.edges(data=True):
for k in [k for k in attrs if k.startswith("_")]:
del attrs[k]
nx.write_graphml(H, output_path)
+7618 -473
View File
File diff suppressed because it is too large. Load diff
+162
View File
@@ -0,0 +1,162 @@
"""Intra-file slicing for oversized text documents (#1369).
The extraction packer (`_pack_chunks_by_tokens`) treats each file as atomic and
`_read_files` caps every file at ``_FILE_CHAR_CAP`` characters, so a document
larger than that cap had everything past the cap silently dropped — the model
never saw it, and nothing in the adaptive-retry path could recover it ("a single
file larger than the budget ... packing can't shrink one big file").
This module splits an oversized *splittable text* document (Markdown, plain
text, reStructuredText) into contiguous ``FileSlice`` units at heading /
paragraph / line boundaries so the whole file gets extracted across several
units. Every slice of a file reports the **parent file path** as its source, so
the resulting nodes are never fragmented per-slice — they merge by source_file
exactly as if the file had been extracted in one pass.
Only plain-text documents are sliced: code files need whole-symbol context, and
PDFs/images are read through their own extractors and have no char-offset model.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
# Plain-text document types where boundary-based slicing is meaningful and where
# `_file_to_text` is a straight ``read_text`` (so a char range matches the bytes
# the model is shown). Deliberately excludes code (.py, .ts, ...) and binary
# docs (.pdf) — those are never sliced.
_SPLITTABLE_TEXT_SUFFIXES = frozenset({".md", ".mdx", ".markdown", ".txt", ".rst"})
# Boundary preferences, strongest first. A Markdown heading (``\n#``) keeps a
# section with its title; a blank line keeps a paragraph intact; a bare newline
# avoids cutting mid-line. If none is found in the window we hard-cut.
_BOUNDARY_SEPARATORS = ("\n#", "\n\n", "\n")
@dataclass(frozen=True)
class FileSlice:
"""A contiguous ``[start, end)`` character range of a splittable text file.
``index``/``total`` are for logging only. ``path`` is the real file on disk;
the slice always reports ``path`` as its source so slices don't fragment the
graph.
"""
path: Path
start: int
end: int
index: int
total: int
# A unit of extraction work: either a whole file (``Path``) or one slice of one.
Unit = "Path | FileSlice"
def unit_path(unit: "Path | FileSlice") -> Path:
"""The on-disk path a unit belongs to (the parent file for a slice)."""
return unit.path if isinstance(unit, FileSlice) else unit
def is_splittable_text(path: Path) -> bool:
"""True for plain-text document types that may be sliced."""
return path.suffix.lower() in _SPLITTABLE_TEXT_SUFFIXES
def _best_cut(text: str, start: int, end: int) -> int:
"""Return a cut index in ``(start, end]`` at the strongest nearby boundary.
Searches the window ``text[start:end]`` for the latest heading, then blank
line, then newline, and returns the index just *after* it (a heading cuts
just *before* the ``#`` so the heading leads the next slice). Falls back to a
hard cut at ``end`` when the window has no usable boundary, which still makes
forward progress because ``end > start``.
"""
window = text[start:end]
for sep in _BOUNDARY_SEPARATORS:
idx = window.rfind(sep)
if idx > 0: # a boundary strictly inside the window (non-empty prev slice)
if sep == "\n#":
return start + idx + 1 # keep the newline with the previous slice
return start + idx + len(sep)
return end
def slice_boundaries(text: str, max_chars: int) -> list[tuple[int, int]]:
"""Contiguous ``(start, end)`` ranges covering all of ``text``, each ≤ max_chars.
Ranges are gap-free and non-overlapping, so concatenating the slices
reproduces ``text`` exactly — no content is dropped.
"""
n = len(text)
if n <= max_chars:
return [(0, n)]
bounds: list[tuple[int, int]] = []
pos = 0
while pos < n:
hard = min(pos + max_chars, n)
end = _best_cut(text, pos, hard) if hard < n else n
if end <= pos: # defensive: never stall
end = hard
bounds.append((pos, end))
pos = end
return bounds
def expand_oversized_files(
files: list[Path], max_chars: int
) -> list["Path | FileSlice"]:
"""Replace each oversized splittable-text file with a list of ``FileSlice``s.
Files at or below ``max_chars`` (and all non-splittable files) pass through
unchanged as ``Path``, so behaviour is identical for everything that already
fit. Unreadable files pass through untouched (the reader handles the error).
"""
out: list["Path | FileSlice"] = []
for f in files:
if not is_splittable_text(f):
out.append(f)
continue
try:
text = f.read_text(encoding="utf-8", errors="replace")
except OSError:
out.append(f)
continue
if len(text) <= max_chars:
out.append(f)
continue
ranges = slice_boundaries(text, max_chars)
total = len(ranges)
for i, (s, e) in enumerate(ranges):
out.append(FileSlice(path=f, start=s, end=e, index=i, total=total))
return out
def read_slice_text(fs: FileSlice) -> str:
"""Read just this slice's characters from its parent file."""
text = fs.path.read_text(encoding="utf-8", errors="replace")
return text[fs.start:fs.end]
def bisect_slice(fs: FileSlice) -> tuple[FileSlice, FileSlice] | None:
"""Split a slice into two halves at a newline near its midpoint, or None.
Used by the adaptive-retry path when a single slice still overflows the
model's output: halving it produces a smaller response. Returns None when the
slice is already too small to split meaningfully.
"""
if fs.end - fs.start <= 1:
return None
try:
text = fs.path.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
mid = (fs.start + fs.end) // 2
nl = text.find("\n", mid, fs.end)
cut = nl + 1 if (nl != -1 and fs.start < nl + 1 < fs.end) else mid
if not (fs.start < cut < fs.end):
return None
left = FileSlice(fs.path, fs.start, cut, fs.index, fs.total)
right = FileSlice(fs.path, cut, fs.end, fs.index, fs.total)
return left, right
+34 -7
View File
@@ -16,8 +16,27 @@ def _load_manifest() -> dict:
if _GLOBAL_MANIFEST.exists():
try:
return json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
except Exception:
pass
except Exception as exc:
# Don't silently wipe the user's manifest on a parse error: that
# deletes every tracked repo. Back the bad file up and surface the
# error so the user can recover or report it.
backup = _GLOBAL_MANIFEST.with_suffix(
_GLOBAL_MANIFEST.suffix + f".corrupt.{int(datetime.now(timezone.utc).timestamp())}"
)
try:
_GLOBAL_MANIFEST.rename(backup)
print(
f"[graphify global] manifest at {_GLOBAL_MANIFEST} failed to parse ({exc}); "
f"moved to {backup} and starting fresh. Restore from the backup if this was "
f"unexpected.",
file=sys.stderr,
)
except Exception as rename_exc:
print(
f"[graphify global] manifest at {_GLOBAL_MANIFEST} failed to parse ({exc}) "
f"and could not be backed up ({rename_exc}). Starting fresh.",
file=sys.stderr,
)
return {"version": 1, "repos": {}}
@@ -28,6 +47,8 @@ def _save_manifest(manifest: dict) -> None:
def _load_global_graph() -> nx.Graph:
if _GLOBAL_GRAPH.exists():
from graphify.security import check_graph_file_size_cap
check_graph_file_size_cap(_GLOBAL_GRAPH)
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"])
@@ -80,6 +101,8 @@ def global_add(source_path: Path, repo_tag: str) -> dict:
return {"repo_tag": repo_tag, "nodes_added": 0, "nodes_removed": 0, "skipped": True}
# Load source graph
from graphify.security import check_graph_file_size_cap
check_graph_file_size_cap(source_path)
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"])
@@ -101,20 +124,24 @@ def global_add(source_path: Path, repo_tag: str) -> dict:
for n, d in G.nodes(data=True)
if not d.get("source_file") and d.get("label")
}
nodes_to_skip = set()
# Map each deduplicated external onto the existing global node so that
# edges incident to it can be rewired instead of dropped.
remap = {}
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)
remap[node] = external_labels[data["label"]]
# 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:
if node not in remap:
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:
u = remap.get(u, u)
v = remap.get(v, v)
if u != v: # don't introduce self-loops via remapping
G.add_edge(u, v, **data)
added = prefixed.number_of_nodes() - len(nodes_to_skip)
added = prefixed.number_of_nodes() - len(remap)
_save_global_graph(G)
manifest["repos"][repo_tag] = {
+263 -81
View File
@@ -10,65 +10,75 @@ _HOOK_MARKER_END = "# graphify-hook-end"
_CHECKOUT_MARKER = "# graphify-checkout-hook-start"
_CHECKOUT_MARKER_END = "# graphify-checkout-hook-end"
# __PINNED_PYTHON__ is replaced at install time with the absolute path of the
# Python interpreter that ran `graphify hook install`. For uv-tool and pipx
# installs the interpreter lives inside an isolated venv, so the launcher on
# PATH is the only entry point — and GUI git clients / CI runners often have a
# minimal PATH that omits ~/.local/bin. Pinning sys.executable at install time
# makes the hook work regardless of PATH at git-trigger time.
_PYTHON_DETECT = """\
# Detect the correct Python interpreter (handles pipx, venv, system installs)
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
case "$GRAPHIFY_BIN" in
*.exe) _SHEBANG="" ;;
*) _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//') ;;
esac
case "$_SHEBANG" in
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
esac
# Allowlist: only keep characters valid in a filesystem path to prevent
# injection if the shebang contains shell metacharacters
case "$GRAPHIFY_PYTHON" in
*[!a-zA-Z0-9/_.@-]*) GRAPHIFY_PYTHON="" ;;
esac
if [ -n "$GRAPHIFY_PYTHON" ] && ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON=""
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs).
# _PINNED was recorded at hook-install time; tried first so the hook works even
# when the graphify launcher is not on PATH (common in GUI clients and CI).
GRAPHIFY_PYTHON=""
_PINNED='__PINNED_PYTHON__'
if [ -n "$_PINNED" ] && [ -x "$_PINNED" ] && "$_PINNED" -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="$_PINNED"
fi
# Second probe: read graphify-out/.graphify_python (written by the skill and
# CLI; survives uv-tool reinstalls and is the same source the README documents).
if [ -z "$GRAPHIFY_PYTHON" ]; then
_GFY_PYTHON_FILE="graphify-out/.graphify_python"
if [ -f "$_GFY_PYTHON_FILE" ]; then
_FROM_FILE=$(cat "$_GFY_PYTHON_FILE" 2>/dev/null | tr -d '[:space:]')
case "$_FROM_FILE" in
*[!a-zA-Z0-9/_.@:\\-]*) _FROM_FILE="" ;; # allowlist (covers Windows paths)
esac
if [ -n "$_FROM_FILE" ] && [ -x "$_FROM_FILE" ] && "$_FROM_FILE" -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="$_FROM_FILE"
fi
fi
fi
# Fall back: try python3, then python (Windows has no python3 shim)
# Third probe: resolve via the graphify launcher on PATH (shebang probe).
if [ -z "$GRAPHIFY_PYTHON" ]; then
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
case "$GRAPHIFY_BIN" in
*.exe) _SHEBANG="" ;;
*) _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//') ;;
esac
case "$_SHEBANG" in
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
esac
# Allowlist: only keep characters valid in a filesystem path to prevent
# injection if the shebang contains shell metacharacters.
case "$GRAPHIFY_PYTHON" in
*[!a-zA-Z0-9/_.@-]*) GRAPHIFY_PYTHON="" ;;
esac
if [ -n "$GRAPHIFY_PYTHON" ] && ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON=""
fi
fi
fi
# Last resort: try python3 / python (works for system/venv installs on PATH).
if [ -z "$GRAPHIFY_PYTHON" ]; then
if command -v python3 >/dev/null 2>&1 && python3 -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="python3"
elif command -v python >/dev/null 2>&1 && python -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="python"
else
echo "[graphify hook] could not locate a Python with graphify installed. Add the graphify bin dir to PATH or re-run 'graphify hook install' from the env where graphify lives." >&2
exit 0
fi
fi
"""
_HOOK_SCRIPT = """\
# graphify-hook-start
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
# Installed by: graphify hook install
# Skip during rebase/merge/cherry-pick to avoid blocking --continue with unstaged changes
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
CHANGED=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || git diff --name-only HEAD 2>/dev/null)
if [ -z "$CHANGED" ]; then
exit 0
fi
""" + _PYTHON_DETECT + """
export GRAPHIFY_CHANGED="$CHANGED"
# 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 "
# The Python that the rebuild runs, shared by both hooks. Embedded verbatim into
# the launcher below and re-executed in the detached child. Must not contain the
# double-quote, $, backtick or backslash characters: it is carried inside a
# shell double-quoted `-c "..."` argument (see _detached_launch).
_REBUILD_BODY_COMMIT = """\
import os, signal, sys
from pathlib import Path
@@ -88,16 +98,140 @@ try:
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
signal.alarm(_timeout)
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
_rebuild_code(Path('.'), changed_paths=changed, force=_force)
_root = Path('.')
_saved = Path('graphify-out/.graphify_root')
if _saved.exists():
_txt = _saved.read_text(encoding='utf-8').strip()
if _txt:
_root = Path(_txt)
_rebuild_code(_root, changed_paths=changed, force=_force)
except TimeoutError as exc:
print(f'[graphify hook] {exc}')
sys.exit(1)
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
"""
_REBUILD_BODY_CHECKOUT = """\
from graphify.watch import _rebuild_code, _apply_resource_limits
from pathlib import Path
import os, signal, sys
try:
_apply_resource_limits()
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
signal.alarm(_timeout)
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
# post-checkout: branch switch can touch arbitrary files; full rebuild path
# (no changed_paths) is correct here. The flock inside _rebuild_code still
# prevents pile-ups when commit + checkout fire back-to-back.
_root = Path('.')
_saved = Path('graphify-out/.graphify_root')
if _saved.exists():
_txt = _saved.read_text(encoding='utf-8').strip()
if _txt:
_root = Path(_txt)
_rebuild_code(_root, force=_force)
except TimeoutError as exc:
print(f'[graphify] {exc}')
sys.exit(1)
except Exception as exc:
print(f'[graphify] Rebuild failed: {exc}')
sys.exit(1)
"""
# Cross-platform detached-launch shim (#1161). The hooks used to background the
# rebuild with `nohup "$GRAPHIFY_PYTHON" -c "..." &`, but Git for Windows' bundled
# MSYS shell ships no nohup (nor setsid), so that line died with
# 'nohup: command not found' and the rebuild silently never ran — git commit/pull
# still returned 0, so the graph just went stale with no signal. graphify already
# requires Python, so we let Python do the detaching: a tiny outer process spawns
# the real rebuild fully detached and returns immediately, so the hook never
# blocks. POSIX uses start_new_session (the setsid equivalent); Windows uses
# DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, breaking away from any job object
# when allowed. This payload is carried inside a shell double-quoted -c argument,
# so it deliberately uses only single-quoted Python strings (no ", $, ` or \\).
_LAUNCHER_TEMPLATE = """\
import os, subprocess, sys
_src = '''
__REBUILD_BODY__
'''
_log = os.environ.get('GRAPHIFY_REBUILD_LOG') or os.path.join(os.path.expanduser('~'), '.cache', 'graphify-rebuild.log')
try:
os.makedirs(os.path.dirname(_log), exist_ok=True)
_out = open(_log, 'a', buffering=1, encoding='utf-8', errors='replace')
except OSError:
_out = subprocess.DEVNULL
_kw = dict(stdout=_out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, cwd=os.getcwd(), close_fds=True)
_cmd = [sys.executable, '-c', _src]
if os.name == 'nt':
_flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
try:
subprocess.Popen(_cmd, creationflags=_flags | 0x01000000, **_kw) # + CREATE_BREAKAWAY_FROM_JOB
except OSError:
subprocess.Popen(_cmd, creationflags=_flags, **_kw)
else:
subprocess.Popen(_cmd, start_new_session=True, **_kw)
"""
def _detached_launch(rebuild_body: str) -> str:
"""Return a POSIX-sh line that runs ``rebuild_body`` as a detached background
Python process via ``$GRAPHIFY_PYTHON``.
Replaces the old ``nohup ... &`` form, which failed on Git for Windows'
shell (no nohup/setsid) and let the rebuild silently never run (#1161).
The launcher writes the child's output to ``$GRAPHIFY_REBUILD_LOG`` and
returns the instant the child is spawned, so the git hook never blocks.
"""
launcher = _LAUNCHER_TEMPLATE.replace("__REBUILD_BODY__", rebuild_body)
return '"$GRAPHIFY_PYTHON" -c "' + launcher + '"\n'
_HOOK_SCRIPT = """\
# graphify-hook-start
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
# Installed by: graphify hook install
# Deterministic clustering: networkx louvain iterates string-keyed sets whose
# order is randomized per-process by PYTHONHASHSEED, so community assignments
# churn run-to-run. Pinning it makes graphify-out reproducible.
export PYTHONHASHSEED=0
# Skip during rebase/merge/cherry-pick to avoid blocking --continue with unstaged changes
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
CHANGED=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || git diff --name-only HEAD 2>/dev/null)
if [ -z "$CHANGED" ]; then
exit 0
fi
# Skip when only graphify-out/ artifacts changed (avoids rebuild loop when graph outputs are tracked in git)
_NON_GRAPH=$(echo "$CHANGED" | grep -v '^graphify-out/' || true)
if [ -z "$_NON_GRAPH" ]; then
exit 0
fi
""" + _PYTHON_DETECT + """
export GRAPHIFY_CHANGED="$CHANGED"
# Run the rebuild detached so git commit returns immediately. Full-repo rebuilds
# can take hours; blocking the post-commit hook stalls the shell. The Python
# launcher below detaches the child cross-platform, so it works on Git for
# Windows' shell too (which lacks the coreutils backgrounding tools) (#1161).
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
echo "[graphify hook] launching background rebuild (log: $_GRAPHIFY_LOG)"
""" + _detached_launch(_REBUILD_BODY_COMMIT) + """# graphify-hook-end
"""
@@ -106,6 +240,11 @@ _CHECKOUT_SCRIPT = """\
# Auto-rebuilds the knowledge graph (code only) when switching branches.
# Installed by: graphify hook install
# Deterministic clustering: networkx louvain iterates string-keyed sets whose
# order is randomized per-process by PYTHONHASHSEED, so community assignments
# churn run-to-run. Pinning it makes graphify-out reproducible.
export PYTHONHASHSEED=0
PREV_HEAD=$1
NEW_HEAD=$2
BRANCH_SWITCH=$3
@@ -130,31 +269,9 @@ GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
""" + _PYTHON_DETECT + """
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
echo "[graphify] Branch switched - launching background rebuild (log: $_GRAPHIFY_LOG)"
nohup $GRAPHIFY_PYTHON -c "
from graphify.watch import _rebuild_code, _apply_resource_limits
from pathlib import Path
import os, signal, sys
try:
_apply_resource_limits()
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
signal.alarm(_timeout)
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
# post-checkout: branch switch can touch arbitrary files; full rebuild path
# (no changed_paths) is correct here. The flock inside _rebuild_code still
# prevents pile-ups when commit + checkout fire back-to-back.
_rebuild_code(Path('.'), force=_force)
except TimeoutError as exc:
print(f'[graphify] {exc}')
sys.exit(1)
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
""" + _detached_launch(_REBUILD_BODY_CHECKOUT) + """# graphify-checkout-hook-end
"""
@@ -167,6 +284,25 @@ def _git_root(path: Path) -> Path | None:
return None
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")
def _reject_windows_path(value: str, source: str) -> None:
"""Raise if a hooks path looks like a Windows absolute path (#1385).
On POSIX/WSL ``Path("C:\\Users\\...").is_absolute()`` is False, so an absolute
Windows hooks path gets joined under the repo root and mkdir'd as a literal
junk directory (backslashes and all), while install reports success and the
real ``.git/hooks`` gets nothing. Fail loudly instead so the user can fix it.
"""
if _WINDOWS_DRIVE_RE.match(value) or "\\" in value:
raise RuntimeError(
f"git hooks path from {source} looks like a Windows path: {value!r}. "
f"On WSL/POSIX this can't resolve to a real directory. Unset it with "
f"`git config --local --unset core.hooksPath`, or set a POSIX path."
)
def _hooks_dir(root: Path) -> Path:
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
try:
@@ -175,6 +311,7 @@ def _hooks_dir(root: Path) -> Path:
# configparser lowercases option names; git's hooksPath becomes hookspath
custom = cfg.get("core", "hookspath", fallback="").strip()
if custom:
_reject_windows_path(custom, "core.hooksPath")
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
@@ -199,14 +336,23 @@ def _hooks_dir(root: Path) -> Path:
)
# In a linked worktree .git is a file not a directory, so constructing
# root/.git/hooks directly fails. Ask git for the real hooks path instead.
# NOTE: do NOT pass --path-format=absolute — added in git 2.31; older git
# echoes it back as a literal argument, contaminating stdout and causing a
# phantom directory to be created (#907). git -C <root> already returns an
# absolute path for worktree/external-gitdir cases, and a path relative to
# <root> for normal repos — anchoring on root covers both.
import subprocess as _sp
try:
res = _sp.run(
["git", "-C", str(root), "rev-parse", "--path-format=absolute", "--git-path", "hooks"],
["git", "-C", str(root), "rev-parse", "--git-path", "hooks"],
capture_output=True, text=True,
)
if res.returncode == 0:
d = Path(res.stdout.strip())
raw = res.stdout.strip()
# A valid hooks path can never contain newlines or NUL. Their presence
# means git echoed an unrecognised flag back (old git behaviour).
if res.returncode == 0 and raw and not any(c in raw for c in ("\n", "\r", "\x00")):
_reject_windows_path(raw, "git rev-parse --git-path hooks")
d = (root / raw).resolve()
d.mkdir(parents=True, exist_ok=True)
return d
except (OSError, FileNotFoundError):
@@ -251,16 +397,52 @@ def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) ->
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
def _user_hooks_dir(hooks_dir: Path) -> Path:
"""Return the user-editable hooks directory.
Husky 9 sets core.hooksPath to .husky/_ (wrapper scripts auto-generated by
Husky), while user-editable hooks live in the parent .husky/. Return the
parent when the resolved dir ends in '_' so install/status/uninstall target
the correct location (#987).
"""
if hooks_dir.name == "_":
return hooks_dir.parent
return hooks_dir
def install(path: Path = Path(".")) -> str:
"""Install graphify post-commit and post-checkout hooks in the nearest git repo."""
root = _git_root(path)
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hooks_dir = _hooks_dir(root)
hooks_dir = _user_hooks_dir(_hooks_dir(root))
commit_msg = _install_hook(hooks_dir, "post-commit", _HOOK_SCRIPT, _HOOK_MARKER)
checkout_msg = _install_hook(hooks_dir, "post-checkout", _CHECKOUT_SCRIPT, _CHECKOUT_MARKER)
# Pin the current interpreter so the hook works even when the graphify
# launcher is not on PATH at git-trigger time (uv tool / pipx isolation).
# sys.executable is the Python running this very install command, so it is
# always the correct isolated-venv interpreter. The placeholder is replaced
# in both scripts before writing; the allowlist in _PYTHON_DETECT strips any
# characters unsafe in a shell path, and import-verification catches a stale
# pinned path so it safely falls through to the dynamic detection.
# Apply the same allowlist used in _PYTHON_DETECT for all other probes.
# This rejects any character that is not a valid plain filesystem path
# character, preventing $(...), backtick, double-quote, semicolon, etc.
# from being injected into the generated shell scripts. The allowlist
# includes ':' and '\' so Windows paths (C:\...) are accepted.
import re as _re
_safe = sys.executable
if _re.search(r"[^a-zA-Z0-9/_.@:\\-]", _safe):
# Path contains characters outside the allowlist (spaces, quotes, etc.).
# Embed an empty string so the pinned probe is skipped and the hook
# falls through to the dynamic detection — safe degradation.
_safe = ""
pinned = _safe
hook = _HOOK_SCRIPT.replace("__PINNED_PYTHON__", pinned)
checkout = _CHECKOUT_SCRIPT.replace("__PINNED_PYTHON__", pinned)
commit_msg = _install_hook(hooks_dir, "post-commit", hook, _HOOK_MARKER)
checkout_msg = _install_hook(hooks_dir, "post-checkout", checkout, _CHECKOUT_MARKER)
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
@@ -271,7 +453,7 @@ def uninstall(path: Path = Path(".")) -> str:
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hooks_dir = _hooks_dir(root)
hooks_dir = _user_hooks_dir(_hooks_dir(root))
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
@@ -283,7 +465,7 @@ def status(path: Path = Path(".")) -> str:
root = _git_root(path)
if root is None:
return "Not in a git repository."
hooks_dir = _hooks_dir(root)
hooks_dir = _user_hooks_dir(_hooks_dir(root))
def _check(name: str, marker: str) -> str:
p = hooks_dir / name
+50
View File
@@ -0,0 +1,50 @@
"""Single source of truth for node-ID normalization.
Three independent producers must agree on node IDs or the graph splits a single
entity into disconnected ghost nodes:
1. The AST extractor (``extract._make_id``) — deterministic, per-language.
2. The semantic subagents (LLM) — follow the node-ID spec in the skill prompt.
3. The graph builder (``build._normalize_id``) — reconciles edge endpoints when
the LLM emits IDs with slightly different punctuation or casing than the AST.
Historically the normalization recipe was copy-pasted into ``extract._make_id``
and ``build._normalize_id`` and kept in sync only by mirrored docstrings, which
is exactly how the recurring ID-drift bug class crept in (#811 Unicode collapse,
#550 same-filename collisions, #1033 AST-vs-LLM file-node mismatch, #1104). This
module exists so the recipe lives in one place and the two callers can no longer
diverge.
The recipe: NFKC-normalize (so composed/decomposed Unicode forms collapse),
replace runs of non-word characters with a single underscore (``re.UNICODE`` so
CJK/Cyrillic/Arabic/accented-Latin letters survive instead of collapsing to a
per-file node), collapse repeated underscores, strip leading/trailing
underscores, and casefold.
"""
from __future__ import annotations
import re
import unicodedata
__all__ = ["normalize_id", "make_id"]
def normalize_id(s: str) -> str:
r"""Normalize a single ID string to its canonical form.
Idempotent: ``normalize_id(normalize_id(s)) == normalize_id(s)``.
"""
s = unicodedata.normalize("NFKC", s)
s = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
s = re.sub(r"_+", "_", s)
return s.strip("_").casefold()
def make_id(*parts: str) -> str:
"""Build a canonical node ID from one or more name parts.
Parts are joined with ``_`` (after stripping stray ``_``/``.`` edges from each
part) and then run through :func:`normalize_id`, so the result is identical to
what the builder produces from the joined string.
"""
return normalize_id("_".join(p.strip("_.") for p in parts if p))
+1400 -155
View File
File diff suppressed because it is too large. Load diff
+247
View File
@@ -0,0 +1,247 @@
"""Deterministic package-manifest ingestion (#1377).
Package manifests (``apm.yml``, ``pyproject.toml``, ``go.mod``, ``pom.xml``)
declare a package and its dependencies. Left to the LLM document path, the same
package gets a different file-anchored node id from its own manifest than from
each dependent's dependency reference, so it splits into duplicate nodes. This
module parses manifests deterministically and emits ONE canonical package node
per package -- keyed by NAME via :func:`graphify.ids.make_id` -- plus
``depends_on`` edges, so a package referenced from N manifests collapses to a
single hub node (the dependency stub and the package's own definition node share
the canonical id and merge at build time).
Mirrors ``mcp_ingest``: recognized by filename, routed to the deterministic AST
path (never the LLM), so a manifest is extracted exactly once.
"""
from __future__ import annotations
import re
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
from graphify.ids import make_id
__all__ = ["is_package_manifest_path", "extract_package_manifest", "PACKAGE_MANIFEST_NAMES"]
# manifest filename (lowercased) -> ecosystem tag
PACKAGE_MANIFEST_NAMES: dict[str, str] = {
"apm.yml": "apm",
"apm.yaml": "apm",
"pyproject.toml": "python",
"go.mod": "go",
"pom.xml": "maven",
}
_MAX_MANIFEST_BYTES = 2_000_000 # 2 MB cap — manifests are small; this rejects junk
def is_package_manifest_path(path: Path) -> bool:
"""True if ``path`` is a recognized package manifest (by filename)."""
return path.name.lower() in PACKAGE_MANIFEST_NAMES
def _pkg_id(name: str) -> str:
"""Canonical package node id, keyed by package NAME so every reference to the
same package -- its own manifest and any dependent's dependency line -- maps
to one node."""
return make_id("pkg", name)
def extract_package_manifest(path: Path) -> dict[str, Any]:
"""Parse a package manifest into a canonical package node + ``depends_on`` edges."""
try:
if path.stat().st_size > _MAX_MANIFEST_BYTES:
return {"nodes": [], "edges": [], "error": "manifest too large to index"}
text = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return {"nodes": [], "edges": [], "error": f"manifest read error: {exc}"}
eco = PACKAGE_MANIFEST_NAMES[path.name.lower()]
try:
info = _PARSERS[eco](text)
except Exception as exc: # noqa: BLE001 — a malformed manifest must not abort extraction
return {"nodes": [], "edges": [], "error": f"manifest parse error: {exc}"}
if not info or not info.get("name"):
return {"nodes": [], "edges": []}
name = info["name"]
str_path = str(path)
pkg_nid = _pkg_id(name)
node: dict[str, Any] = {
"id": pkg_nid,
"label": name,
"file_type": "code", # valid schema type; `type` distinguishes packages
"type": "package",
"ecosystem": eco,
"source_file": str_path,
"source_location": "L1",
}
if info.get("version"):
node["version"] = info["version"]
nodes: list[dict] = [node]
edges: list[dict] = []
seen: set[str] = set()
for dep in info.get("deps", []):
if not dep:
continue
dep_nid = _pkg_id(dep)
if dep_nid == pkg_nid or dep_nid in seen:
continue
seen.add(dep_nid)
# The edge targets the dependency's canonical package id. If that package's
# own manifest is in the corpus, the edge resolves to its (single) node; if
# the dependency is external, build_from_json prunes the dangling edge. We
# deliberately do NOT emit a stub node — a stub with an empty source_file
# would risk clobbering the real node's source_file under id-dedup.
edges.append({
"source": pkg_nid,
"target": dep_nid,
"relation": "depends_on",
"context": "dependency",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str_path,
"source_location": "L1",
"weight": 1.0,
})
return {"nodes": nodes, "edges": edges}
# ── per-ecosystem parsers: text -> {"name", "version"?, "deps": [str]} | None ──
def _coerce_deps(value: Any) -> list[str]:
"""A dependency block may be a list of names or a name->spec map."""
if isinstance(value, dict):
return [str(k) for k in value]
if isinstance(value, list):
out: list[str] = []
for item in value:
if isinstance(item, str):
out.append(item)
elif isinstance(item, dict) and item:
out.append(str(next(iter(item))))
return out
return []
def _parse_apm(text: str) -> dict | None:
try:
import yaml
except ImportError:
return _parse_apm_fallback(text)
data = yaml.safe_load(text)
if not isinstance(data, dict):
return None
return {
"name": data.get("name"),
"version": data.get("version"),
"deps": _coerce_deps(data.get("dependencies")),
}
def _parse_apm_fallback(text: str) -> dict | None:
"""Minimal line parser for apm.yml when PyYAML is unavailable: a top-level
``name:`` plus a simple ``dependencies:`` block (list items or a name map)."""
name = None
deps: list[str] = []
in_deps = False
for line in text.splitlines():
if not in_deps:
m = re.match(r'^name:\s*["\']?([^"\'\s#]+)', line)
if m:
name = m.group(1)
continue
if re.match(r'^dependencies:\s*$', line):
in_deps = True
continue
if in_deps:
dm = (re.match(r'^\s*-\s*["\']?([^"\'\s#:]+)', line)
or re.match(r'^\s{2,}([A-Za-z0-9._/@-]+)\s*:', line))
if dm:
deps.append(dm.group(1))
elif re.match(r'^\S', line): # next top-level key ends the block
in_deps = False
return {"name": name, "version": None, "deps": deps} if name else None
def _pep508_name(spec: str) -> str:
"""`requests>=2.0` -> `requests`; `pkg[extra]==1; python_version<'3.9'` -> `pkg`."""
return re.split(r'[\s<>=!~;\[\(]', spec.strip(), maxsplit=1)[0]
def _parse_pyproject(text: str) -> dict | None:
try:
import tomllib as _toml
except ImportError:
try:
import tomli as _toml # type: ignore
except ImportError:
return None
data = _toml.loads(text)
proj = data.get("project", {}) if isinstance(data.get("project"), dict) else {}
poetry = (data.get("tool", {}) or {}).get("poetry", {}) if isinstance(data.get("tool"), dict) else {}
name = proj.get("name") or (poetry.get("name") if isinstance(poetry, dict) else None)
if not name:
return None
deps: list[str] = [_pep508_name(s) for s in (proj.get("dependencies") or []) if isinstance(s, str)]
if isinstance(poetry, dict):
for dep in (poetry.get("dependencies") or {}):
if str(dep).lower() != "python":
deps.append(str(dep))
return {"name": name, "version": proj.get("version") or (poetry.get("version") if isinstance(poetry, dict) else None), "deps": deps}
def _parse_gomod(text: str) -> dict | None:
name = None
deps: list[str] = []
in_block = False
for line in text.splitlines():
s = line.strip()
if name is None:
m = re.match(r'^module\s+(\S+)', s)
if m:
name = m.group(1)
continue
if re.match(r'^require\s*\(', s):
in_block = True
continue
if in_block:
if s.startswith(')'):
in_block = False
continue
dm = re.match(r'^(\S+)\s+v\S+', s)
if dm:
deps.append(dm.group(1))
else:
dm = re.match(r'^require\s+(\S+)\s+v\S+', s)
if dm:
deps.append(dm.group(1))
return {"name": name, "version": None, "deps": deps} if name else None
def _parse_pom(text: str) -> dict | None:
# Drop the default namespace so findtext/findall don't need the {uri} prefix.
text = re.sub(r'\sxmlns="[^"]*"', '', text, count=1)
root = ET.fromstring(text)
aid = root.findtext("artifactId")
gid = root.findtext("groupId")
if not aid:
return None
name = f"{gid}:{aid}" if gid else aid
deps: list[str] = []
for dep in root.findall(".//dependencies/dependency"):
da = dep.findtext("artifactId")
dg = dep.findtext("groupId")
if da:
deps.append(f"{dg}:{da}" if dg else da)
return {"name": name, "version": root.findtext("version"), "deps": deps}
_PARSERS = {
"apm": _parse_apm,
"python": _parse_pyproject,
"go": _parse_gomod,
"maven": _parse_pom,
}
+389
View File
@@ -0,0 +1,389 @@
"""mcp_ingest.py — Extract MCP (Model Context Protocol) server configuration files.
Reads `.mcp.json` / `claude_desktop_config.json` / `mcp.json` / `mcp_servers.json`
and turns the `mcpServers` map into Graphify nodes and edges.
Symmetry with `serve.py`: Graphify exposes itself AS an MCP server. This module
indexes MCP servers AS a corpus type, completing the loop — an agent that runs
graphify with `--mcp` can now query its own configured MCP layer.
Entry point:
extract_mcp_config(path: Path) -> dict[str, list[dict]]
Returns `{"nodes": [...], "edges": [...]}` compatible with Graphify's
extraction-result format. Returns `{"nodes": [...], "edges": [...], "error": "..."}`
when the file is malformed, too large, or has no `mcpServers` map — the empty
result keeps it indistinguishable from "no MCP config here" for downstream
callers.
Detected filenames (case-sensitive, matched on basename):
- .mcp.json (Claude Code project config)
- claude_desktop_config.json (Claude Desktop)
- mcp.json (generic / per-tool)
- mcp_servers.json (alternate naming)
Schema emitted:
Node kinds:
- file the config file itself (label = filename)
- mcp_server one per entry under mcpServers
- mcp_command executable (npx, uvx, node, python, ...) — global ID
- mcp_package npm / pypi package id parsed from args — global ID
- env_var env variable NAME only — global ID. VALUES ARE NEVER READ.
Edge relations:
- contains file -> mcp_server
- references mcp_server -> mcp_command
- references mcp_server -> mcp_package
- requires_env mcp_server -> env_var (new relation; distinguishes
env dependencies from generic refs)
Security:
- Env var VALUES are never read, persisted, labelled, or surfaced. Only env
var NAMES become nodes. (`env: {"API_KEY": "sk-..."}` -> node "API_KEY" only.)
- File size capped at 1 MiB (matches extract_json).
- All labels go through `sanitize_label` (control characters stripped, length
capped) before emission.
- Args are NOT persisted as nodes/edges to avoid leaking paths or secrets that
some servers embed as positional args.
Cross-config emergent edges:
Because `mcp_command`, `mcp_package`, and `env_var` nodes use global IDs (no
per-file stem prefix), the same package or env var across two MCP configs
produces shared nodes — naturally surfacing "what configs depend on this
thing?" via graph traversal. Server nodes ARE stem-scoped so two configs
declaring different servers under the same key (e.g., both have "filesystem")
do not collide.
"""
from __future__ import annotations
import json
import re
import unicodedata
from pathlib import Path
from typing import Any
from graphify.ids import make_id as _shared_make_id
from graphify.security import sanitize_label
MCP_CONFIG_FILENAMES: frozenset[str] = frozenset({
".mcp.json",
"claude_desktop_config.json",
"mcp.json",
"mcp_servers.json",
})
_MAX_BYTES = 1_048_576 # 1 MiB — same cap as extract_json
_MAX_SERVERS_PER_FILE = 200 # generous; flags pathological configs
def is_mcp_config_path(path: Path) -> bool:
"""Return True when ``path`` is a recognised MCP config filename."""
return path.name in MCP_CONFIG_FILENAMES
def extract_mcp_config(path: Path) -> dict[str, Any]:
"""Parse an MCP config file into Graphify nodes and edges.
Behaviour matches other extractors in `extract.py`:
- returns ``{"nodes": [...], "edges": [...]}`` on success
- returns ``{"nodes": [], "edges": [], "error": "<reason>"}`` on parse
failure, oversize file, or missing ``mcpServers`` map
"""
try:
with path.open("rb") as fh:
raw = fh.read(_MAX_BYTES + 1)
except OSError as exc:
return {"nodes": [], "edges": [], "error": f"mcp_ingest read error: {exc}"}
if len(raw) > _MAX_BYTES:
return {"nodes": [], "edges": [], "error": "mcp config too large to index"}
try:
text = raw.decode("utf-8")
except UnicodeDecodeError as exc:
return {"nodes": [], "edges": [], "error": f"mcp_ingest decode error: {exc}"}
try:
doc = json.loads(text)
except json.JSONDecodeError as exc:
return {"nodes": [], "edges": [], "error": f"mcp_ingest json error: {exc}"}
if not isinstance(doc, dict):
return {"nodes": [], "edges": [], "error": "mcp_ingest: root is not an object"}
servers = doc.get("mcpServers")
if not isinstance(servers, dict):
# Some tools nest the map (e.g., {"mcp": {"servers": {...}}}). Try one
# well-known alternate shape but do not search exhaustively.
nested = doc.get("mcp")
if isinstance(nested, dict):
servers = nested.get("servers")
if not isinstance(servers, dict):
return {"nodes": [], "edges": [], "error": "mcp_ingest: no mcpServers map"}
str_path = str(path)
file_nid = _make_id(str_path)
nodes: list[dict[str, Any]] = []
edges: list[dict[str, Any]] = []
seen_node_ids: set[str] = set()
seen_edge_keys: set[tuple[str, str, str]] = set()
_add_node(
nodes, seen_node_ids,
nid=file_nid,
label=path.name,
kind="mcp_config_file",
source_file=str_path,
line=1,
)
file_stem = _file_stem(path)
server_count = 0
for server_name, spec in servers.items():
if not isinstance(server_name, str) or not server_name:
continue
if not isinstance(spec, dict):
# Skip non-object server entries silently — the broken entry is
# the user's, not ours.
continue
if server_count >= _MAX_SERVERS_PER_FILE:
break
server_count += 1
_emit_server(
server_name=server_name,
spec=spec,
file_nid=file_nid,
file_stem=file_stem,
source_file=str_path,
nodes=nodes,
edges=edges,
seen_node_ids=seen_node_ids,
seen_edge_keys=seen_edge_keys,
)
return {"nodes": nodes, "edges": edges}
def _emit_server(
*,
server_name: str,
spec: dict[str, Any],
file_nid: str,
file_stem: str,
source_file: str,
nodes: list[dict[str, Any]],
edges: list[dict[str, Any]],
seen_node_ids: set[str],
seen_edge_keys: set[tuple[str, str, str]],
) -> None:
"""Emit nodes/edges for one entry under ``mcpServers``."""
server_nid = _make_id(file_stem, "mcp_server", server_name)
_add_node(
nodes, seen_node_ids,
nid=server_nid,
label=server_name,
kind="mcp_server",
source_file=source_file,
line=1, # JSON doesn't expose line numbers without a parser pass
)
_add_edge(
edges, seen_edge_keys,
source=file_nid,
target=server_nid,
relation="contains",
source_file=source_file,
line=1,
)
command = spec.get("command")
if isinstance(command, str) and command.strip():
cmd_label = command.strip()
cmd_nid = _make_id("mcp_command", cmd_label)
_add_node(
nodes, seen_node_ids,
nid=cmd_nid,
label=cmd_label,
kind="mcp_command",
source_file=source_file,
line=1,
)
_add_edge(
edges, seen_edge_keys,
source=server_nid,
target=cmd_nid,
relation="references",
source_file=source_file,
line=1,
context="command",
)
args = spec.get("args")
if isinstance(args, list):
package = _detect_package_from_args(args)
if package:
pkg_nid = _make_id("mcp_package", package)
_add_node(
nodes, seen_node_ids,
nid=pkg_nid,
label=package,
kind="mcp_package",
source_file=source_file,
line=1,
)
_add_edge(
edges, seen_edge_keys,
source=server_nid,
target=pkg_nid,
relation="references",
source_file=source_file,
line=1,
context="package",
)
env = spec.get("env")
if isinstance(env, dict):
# ONLY KEYS. Values may contain secrets and are never read here.
for env_name in env.keys():
if not isinstance(env_name, str) or not env_name:
continue
env_nid = _make_id("env_var", env_name)
_add_node(
nodes, seen_node_ids,
nid=env_nid,
label=env_name,
kind="env_var",
source_file=source_file,
line=1,
)
_add_edge(
edges, seen_edge_keys,
source=server_nid,
target=env_nid,
relation="requires_env",
source_file=source_file,
line=1,
)
# ── Package detection from args ───────────────────────────────────────────────
# Patterns observed in real MCP server configs:
# ["-y", "@modelcontextprotocol/server-filesystem", "/data"] (npx)
# ["-y", "@org/pkg@1.2.3"]
# ["mcp-server-fetch"] (uvx / python)
# ["mcp-server-time", "--local-timezone=UTC"]
# ["@scoped/some-mcp"] (pnpx)
# ["mcp-server-fetch"] (uvx direct)
_NPM_PKG_RE = re.compile(r"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*(?:@[\w.\-+]+)?$")
_PY_MCP_PKG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*-mcp(?:-[a-z0-9._-]+)?$|^mcp-[a-z0-9][a-z0-9._-]*$")
_ARG_FLAG_RE = re.compile(r"^-{1,2}\w")
def _detect_package_from_args(args: list[Any]) -> str | None:
"""Return the first arg that looks like an npm or pypi package id, else None.
Skips short flags (-y, --yes) and option arguments (--local-timezone=UTC).
"""
for raw in args:
if not isinstance(raw, str):
continue
arg = raw.strip()
if not arg or _ARG_FLAG_RE.match(arg):
continue
if _NPM_PKG_RE.match(arg):
return _strip_version(arg)
if _PY_MCP_PKG_RE.match(arg):
return arg
return None
def _strip_version(pkg: str) -> str:
"""Drop the ``@version`` suffix from an npm package id, preserving the scope.
Scoped: ``@scope/name`` or ``@scope/name@1.2.3`` — there are at most two
``@`` chars; the second is the version separator.
Unscoped: ``name`` or ``name@1.2.3``.
"""
if pkg.startswith("@"):
version_at = pkg.find("@", 1)
return pkg if version_at == -1 else pkg[:version_at]
version_at = pkg.find("@")
return pkg if version_at == -1 else pkg[:version_at]
# ── Node / edge construction (Graphify schema) ────────────────────────────────
def _add_node(
nodes: list[dict[str, Any]],
seen: set[str],
*,
nid: str,
label: str,
kind: str,
source_file: str,
line: int,
) -> None:
"""Append a node if not already present. ``kind`` is metadata, not file_type."""
if not nid or nid in seen:
return
seen.add(nid)
nodes.append({
"id": nid,
"label": sanitize_label(label),
"file_type": "code",
"source_file": source_file,
"source_location": f"L{line}",
"metadata": {"mcp_kind": kind},
})
def _add_edge(
edges: list[dict[str, Any]],
seen: set[tuple[str, str, str]],
*,
source: str,
target: str,
relation: str,
source_file: str,
line: int,
context: str | None = None,
) -> None:
"""Append an edge if (source, target, relation) is not already present."""
if not source or not target or source == target:
return
key = (source, target, relation)
if key in seen:
return
seen.add(key)
edge: dict[str, Any] = {
"source": source,
"target": target,
"relation": relation,
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": source_file,
"source_location": f"L{line}",
"weight": 1.0,
}
if context:
edge["context"] = context
edges.append(edge)
# ── ID helpers (kept local; mirror extract.py shape) ──────────────────────────
def _make_id(*parts: str) -> str:
"""Build a stable node ID via the single shared recipe (#1378)."""
return _shared_make_id(*parts)
def _file_stem(path: Path) -> str:
"""Mirror extract._file_stem: include parent dir name to disambiguate."""
parent = path.parent.name
if parent and parent not in (".", ""):
return f"{parent}.{path.stem}"
return path.stem
+212
View File
@@ -0,0 +1,212 @@
"""Runtime compatibility probe for Graphify MultiDiGraph mode.
Verifies that the current NetworkX runtime supports the behaviors a future
opt-in --multigraph build will rely on. The probe is BEHAVIOR-based, not
version-based — both NX 3.4.2 (Py 3.10 lane) and NX 3.6.1+ (Py 3.11+ lane)
pass. The probe result is cached for the process lifetime via lru_cache.
No call sites added yet; downstream multigraph PRs will gate on
require_multigraph_capabilities() before enabling MDG mode.
"""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from functools import lru_cache
import sys
from typing import Any
import networkx as nx
from networkx.readwrite import json_graph
@dataclass(frozen=True)
class CapabilityCheck:
name: str
ok: bool
detail: str
@dataclass(frozen=True)
class MultigraphCapabilityResult:
python_version: str
networkx_version: str
checks: tuple[CapabilityCheck, ...]
@property
def ok(self) -> bool:
return all(check.ok for check in self.checks)
@property
def failed(self) -> tuple[CapabilityCheck, ...]:
return tuple(check for check in self.checks if not check.ok)
def error_message(self) -> str:
if self.ok:
return (
"Graphify MultiDiGraph capability probe passed "
f"(Python {self.python_version}, NetworkX {self.networkx_version})."
)
failed = "; ".join(f"{check.name}: {check.detail}" for check in self.failed)
return (
"error: --multigraph requires NetworkX keyed MultiDiGraph node-link "
"round-trip support. "
f"Detected Python {self.python_version}, NetworkX {self.networkx_version}. "
f"Failed capability check(s): {failed}. "
"Default simple graph mode remains available."
)
def _check(name: str, func: Callable[[], bool | str]) -> CapabilityCheck:
try:
detail = func()
except Exception as exc:
return CapabilityCheck(name, False, f"{type(exc).__name__}: {exc}")
if detail is True:
return CapabilityCheck(name, True, "ok")
if isinstance(detail, str):
return CapabilityCheck(name, False, detail)
return CapabilityCheck(name, False, f"unexpected result {detail!r}")
def _build_probe_graph() -> nx.MultiDiGraph:
graph = nx.MultiDiGraph()
graph.add_node("a", label="A")
graph.add_node("b", label="B")
graph.add_edge("a", "b", key="calls:a.py:L1", relation="calls", source_file="a.py")
graph.add_edge("a", "b", key="imports:a.py:L2", relation="imports", source_file="a.py")
return graph
def _probe_keyed_parallel_edges() -> bool | str:
graph = _build_probe_graph()
if not graph.is_multigraph() or not graph.is_directed():
return f"probe graph type was {type(graph).__name__}"
if graph.number_of_edges("a", "b") != 2:
return f"expected 2 keyed parallel edges, got {graph.number_of_edges('a', 'b')}"
keys = set(graph["a"]["b"].keys())
expected = {"calls:a.py:L1", "imports:a.py:L2"}
if keys != expected:
return f"expected keys {sorted(expected)}, got {sorted(keys)}"
return True
def _probe_node_link_round_trip() -> bool | str:
graph = _build_probe_graph()
data = json_graph.node_link_data(graph, edges="links")
if data.get("multigraph") is not True:
return f"serialized multigraph flag was {data.get('multigraph')!r}"
if data.get("directed") is not True:
return f"serialized directed flag was {data.get('directed')!r}"
links = data.get("links")
if not isinstance(links, list) or len(links) != 2:
length = 0 if not isinstance(links, list) else len(links)
return f"serialized links length was {length}"
serialized_keys: set[str] = set()
for edge in links:
if isinstance(edge, dict):
edge_key = edge.get("key")
if isinstance(edge_key, str):
serialized_keys.add(edge_key)
expected = {"calls:a.py:L1", "imports:a.py:L2"}
if serialized_keys != expected:
return f"serialized keys {sorted(serialized_keys)} did not match {sorted(expected)}"
loaded = json_graph.node_link_graph(data, edges="links")
if not isinstance(loaded, nx.MultiDiGraph):
return f"round-trip graph type was {type(loaded).__name__}"
if loaded.number_of_edges("a", "b") != 2:
return f"round-trip edge count was {loaded.number_of_edges('a', 'b')}"
loaded_keys = set(loaded["a"]["b"].keys())
if loaded_keys != expected:
return f"round-trip keys {sorted(loaded_keys)} did not match {sorted(expected)}"
return True
def _probe_duplicate_key_overwrite_semantics() -> bool | str:
graph = nx.MultiDiGraph()
graph.add_edge("x", "y", key="same", marker="first")
graph.add_edge("x", "y", key="same", marker="second")
edges = list(graph.edges(keys=True, data=True))
if len(edges) != 1:
return f"expected one edge after duplicate-key add, got {len(edges)}"
if edges[0][3].get("marker") != "second":
return f"expected second attr overwrite, got {edges[0][3].get('marker')!r}"
return True
def _probe_reserved_key_attr_rejected() -> bool | str:
"""Verify the Python language guarantee that NetworkX add_edge inherits.
Python forbids passing the same keyword argument twice — once explicitly
and once via **kwargs. This probe confirms that protection still applies
to nx.MultiDiGraph.add_edge: a future loader that builds attrs from JSON
will be reliably protected from accidentally setting `key` via attrs while
also passing `key=` explicitly.
The probe always passes on any Python 3.x version. Its purpose is to
document the invariant explicitly in the probe suite so that if a future
Python version relaxes this rule (extremely unlikely), the probe surfaces
the regression.
"""
graph = nx.MultiDiGraph()
attrs: dict[str, Any] = {"key": "attr-key", "relation": "calls"}
try:
graph.add_edge("a", "b", key="schema-key", **attrs)
except TypeError:
return True
return "add_edge accepted duplicate key keyword and attr; loader must not rely on this"
def _probe_remove_edges_from_two_tuple_semantics() -> bool | str:
graph = nx.MultiDiGraph()
graph.add_edge("a", "b", key="one")
graph.add_edge("a", "b", key="two")
graph.remove_edges_from([("a", "b")])
remaining = graph.number_of_edges("a", "b")
if remaining != 1:
return f"expected one remaining edge after two-tuple removal, got {remaining}"
return True
def _probe_to_undirected_preserves_multigraph_type() -> bool | str:
graph = _build_probe_graph()
undirected = graph.to_undirected()
undirected_view = graph.to_undirected(as_view=True)
if not isinstance(undirected, nx.MultiGraph):
return f"to_undirected() returned {type(undirected).__name__}"
if not isinstance(undirected_view, nx.MultiGraph):
return f"to_undirected(as_view=True) returned {type(undirected_view).__name__}"
return True
@lru_cache(maxsize=1)
def probe_multigraph_capabilities() -> MultigraphCapabilityResult:
checks = (
_check("keyed_parallel_edges", _probe_keyed_parallel_edges),
_check("node_link_edges_links_round_trip", _probe_node_link_round_trip),
_check("duplicate_key_overwrite_semantics", _probe_duplicate_key_overwrite_semantics),
_check("reserved_key_attr_rejected", _probe_reserved_key_attr_rejected),
_check(
"remove_edges_from_two_tuple_semantics",
_probe_remove_edges_from_two_tuple_semantics,
),
_check(
"to_undirected_preserves_multigraph_type",
_probe_to_undirected_preserves_multigraph_type,
),
)
return MultigraphCapabilityResult(
python_version=(
f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
),
networkx_version=nx.__version__,
checks=checks,
)
def require_multigraph_capabilities() -> MultigraphCapabilityResult:
result = probe_multigraph_capabilities()
if not result.ok:
raise RuntimeError(result.error_message())
return result
+142
View File
@@ -0,0 +1,142 @@
from __future__ import annotations
from pathlib import Path
from graphify.extract import extract_sql
def _quote_ident(name: str) -> str:
"""Double-quote a PostgreSQL identifier, escaping embedded double-quotes."""
return '"' + name.replace('"', '""') + '"'
def introspect_postgres(dsn: str | None = None) -> dict:
"""Connect to PostgreSQL, reconstruct DDL, and extract via extract_sql()."""
try:
import psycopg
except ModuleNotFoundError:
raise ImportError(
"psycopg is required for --postgres. "
"Install with: pip install 'graphify[postgres]'"
)
try:
conn = psycopg.connect(dsn or "") # empty string = PG* env vars
except psycopg.OperationalError as exc:
# Sanitize: strip the DSN/credentials that psycopg may embed in the
# OperationalError message (e.g. "connection to server … failed: …\nDETAIL: …")
msg = str(exc).split("\n")[0]
raise ConnectionError(f"could not connect to PostgreSQL: {msg}") from None
try:
conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE")
# 1. Query tables
with conn.cursor() as cur:
cur.execute("""
SELECT table_schema, table_name, table_type
FROM information_schema.tables
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;
""")
tables = cur.fetchall()
# 2. Query views
cur.execute("""
SELECT table_schema, table_name, view_definition
FROM information_schema.views
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;
""")
views = cur.fetchall()
# 3. Query routines (functions/procedures), including language
cur.execute("""
SELECT routine_schema, routine_name, routine_type,
routine_definition, external_language
FROM information_schema.routines
WHERE routine_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY routine_schema, routine_name;
""")
routines = cur.fetchall()
# 4. Query foreign keys — grouped by constraint to handle composites
cur.execute("""
SELECT
tc.constraint_name,
kcu1.table_schema,
kcu1.table_name,
ARRAY_AGG(kcu1.column_name ORDER BY kcu1.ordinal_position) AS columns,
kcu2.table_schema AS foreign_table_schema,
kcu2.table_name AS foreign_table_name,
ARRAY_AGG(kcu2.column_name ORDER BY kcu2.ordinal_position) AS foreign_columns
FROM
information_schema.table_constraints AS tc
JOIN information_schema.referential_constraints AS rc
ON tc.constraint_name = rc.constraint_name
AND tc.table_schema = rc.constraint_schema
JOIN information_schema.key_column_usage AS kcu1
ON tc.constraint_name = kcu1.constraint_name
AND tc.table_schema = kcu1.table_schema
JOIN information_schema.key_column_usage AS kcu2
ON rc.unique_constraint_name = kcu2.constraint_name
AND rc.unique_constraint_schema = kcu2.table_schema
AND kcu1.position_in_unique_constraint = kcu2.ordinal_position
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_schema NOT IN ('pg_catalog', 'information_schema')
GROUP BY tc.constraint_name, kcu1.table_schema, kcu1.table_name,
kcu2.table_schema, kcu2.table_name
ORDER BY kcu1.table_schema, kcu1.table_name;
""")
fks = cur.fetchall()
finally:
conn.close()
ddl = []
# Tables — quote identifiers to handle reserved words, hyphens, mixed-case
for schema, name, ttype in tables:
if ttype == "BASE TABLE":
ddl.append(f"CREATE TABLE {_quote_ident(schema)}.{_quote_ident(name)} (id INT);")
# Views — real body if available, stub if NULL (permission denied)
for schema, name, body in views:
if body:
ddl.append(f"CREATE VIEW {_quote_ident(schema)}.{_quote_ident(name)} AS {body};")
else:
ddl.append(f"CREATE VIEW {_quote_ident(schema)}.{_quote_ident(name)} AS SELECT 1;")
# Functions & Procedures — real body if available, stub if NULL
# Use $gfx$ as the dollar-quote tag to avoid collision with $$ inside bodies.
# Use external_language from the catalog; fall back to plpgsql if NULL/blank.
for schema, name, rtype, body, ext_lang in routines:
lang = (ext_lang or "plpgsql").lower()
fn_sig = f"{_quote_ident(schema)}.{_quote_ident(name)}()"
stub_body = "BEGIN SELECT 1; END;"
if rtype in ("FUNCTION", "PROCEDURE"):
actual_body = body if body else stub_body
# Represent PROCEDUREs as FUNCTION so tree-sitter-sql can parse them
ddl.append(
f"CREATE FUNCTION {fn_sig} RETURNS void"
f" AS $gfx$ {actual_body} $gfx$ LANGUAGE {lang};"
)
# FK edges — one ALTER TABLE per constraint (handles composite FKs correctly)
for constraint_name, t_schema, t_name, cols, r_schema, r_name, r_cols in fks:
col_list = ", ".join(_quote_ident(c) for c in cols)
ref_col_list = ", ".join(_quote_ident(c) for c in r_cols)
ddl.append(
f"ALTER TABLE {_quote_ident(t_schema)}.{_quote_ident(t_name)} "
f"ADD CONSTRAINT {_quote_ident(constraint_name)} "
f"FOREIGN KEY ({col_list}) REFERENCES {_quote_ident(r_schema)}.{_quote_ident(r_name)}({ref_col_list});"
)
ddl_string = "\n".join(ddl)
# Determine host/dbname for virtual path DSN sanitization
info = psycopg.conninfo.conninfo_to_dict(dsn or "")
host = info.get("host", "localhost")
dbname = info.get("dbname", "db")
virtual_path = Path(f"postgresql://{host}/{dbname}")
# Pass virtual path and in-memory DDL content to extract_sql
result = extract_sql(virtual_path, content=ddl_string)
return result
+751
View File
@@ -0,0 +1,751 @@
"""graphify prs — graph-aware PR dashboard.
Fast terminal overview of open PRs with CI/review state, worktree mapping,
and optional graph-impact analysis (which communities a PR touches) and
Opus-powered triage ranking.
Usage:
graphify prs # dashboard of all open PRs
graphify prs <number> # deep dive on one PR
graphify prs --triage # Opus ranks your review queue
graphify prs --worktrees # show worktree → branch → PR mapping
graphify prs --conflicts # PRs sharing graph communities (merge-order risk)
graphify prs --base <branch> # filter to PRs targeting this base (default: v8)
"""
from __future__ import annotations
import json
import os
import re
import subprocess
import sys
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
# ── ANSI colours ─────────────────────────────────────────────────────────────
_NO_COLOR = not sys.stdout.isatty() or os.environ.get("NO_COLOR")
def _c(code: str, text: str) -> str:
if _NO_COLOR:
return text
return f"\033[{code}m{text}\033[0m"
def green(t: str) -> str: return _c("32", t)
def red(t: str) -> str: return _c("31", t)
def yellow(t: str) -> str: return _c("33", t)
def cyan(t: str) -> str: return _c("36", t)
def bold(t: str) -> str: return _c("1", t)
def dim(t: str) -> str: return _c("2", t)
def magenta(t: str) -> str: return _c("35", t)
_ANSI_RE = re.compile(r"\033\[[0-9;]*m")
def _pad(s: str, width: int) -> str:
"""Pad an ANSI-colored string to visible width (strips escape codes for length calc)."""
visible_len = len(_ANSI_RE.sub("", s))
return s + " " * max(0, width - visible_len)
# ── Data model ────────────────────────────────────────────────────────────────
@dataclass
class PRInfo:
number: int
title: str
branch: str
base_branch: str
author: str
is_draft: bool
review_decision: str # APPROVED | CHANGES_REQUESTED | ""
ci_status: str # SUCCESS | FAILURE | PENDING | NONE
updated_at: datetime
expected_base: str = "main" # set by fetch_prs via _detect_default_branch
worktree_path: str | None = None
# Graph impact — populated when graph.json exists
communities_touched: list[int] = field(default_factory=list)
nodes_affected: int = 0
files_changed: list[str] = field(default_factory=list)
@property
def status(self) -> str:
return _classify(self, self.expected_base)
@property
def days_old(self) -> int:
return (datetime.now(timezone.utc) - self.updated_at).days
@property
def blast_radius(self) -> str:
if not self.nodes_affected:
return ""
n = self.nodes_affected
c = len(self.communities_touched)
return f"{n} node{'s' if n != 1 else ''} / {c} communit{'ies' if c != 1 else 'y'}"
# ── Classification ────────────────────────────────────────────────────────────
_STATUS_ORDER = ["WRONG-BASE", "CI-FAIL", "CHANGES-REQ", "DRAFT", "STALE", "PENDING", "APPROVED", "READY"]
_STALE_DAYS = 14
def _classify(pr: "PRInfo", base: str = "v8") -> str:
if pr.base_branch != base:
return "WRONG-BASE"
if pr.ci_status == "FAILURE":
return "CI-FAIL"
if pr.review_decision == "CHANGES_REQUESTED":
return "CHANGES-REQ"
if pr.is_draft:
return "DRAFT"
if pr.days_old >= _STALE_DAYS:
return "STALE"
if pr.review_decision == "APPROVED":
return "APPROVED"
if pr.ci_status == "PENDING":
return "PENDING"
return "READY"
def _status_color(status: str) -> str:
return {
"READY": green(status),
"APPROVED": bold(green(status)),
"CI-FAIL": red(status),
"CHANGES-REQ": red(status),
"WRONG-BASE": dim(status),
"STALE": dim(status),
"DRAFT": yellow(status),
"PENDING": yellow(status),
}.get(status, status)
def _ci_icon(status: str) -> str:
return {"SUCCESS": green("✓"), "FAILURE": red("✗"), "PENDING": yellow("…"), "NONE": dim("–")}.get(status, "?")
# ── GitHub data fetching ──────────────────────────────────────────────────────
def _gh(*args: str) -> list | dict | None:
try:
result = subprocess.run(
["gh", *args],
capture_output=True, text=True, timeout=30
)
if result.returncode != 0:
return None
return json.loads(result.stdout)
except (subprocess.TimeoutExpired, json.JSONDecodeError, FileNotFoundError):
return None
def _detect_default_branch(repo: str | None = None) -> str:
"""Auto-detect the repo's default branch via gh, then git, then fall back to 'main'."""
# Try gh first — works for any repo, not just the current directory
args = ["repo", "view", "--json", "defaultBranchRef"]
if repo:
args += ["--repo", repo]
data = _gh(*args)
if data and data.get("defaultBranchRef", {}).get("name"):
return data["defaultBranchRef"]["name"]
# Fall back to git symbolic-ref for the current repo
try:
result = subprocess.run(
["git", "symbolic-ref", "refs/remotes/origin/HEAD"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
# refs/remotes/origin/main → main
ref = result.stdout.strip()
return ref.split("/")[-1] if ref else "main"
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
return "main"
_CI_FAILURE_CONCLUSIONS = frozenset({"FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"})
def _parse_ci(rollup: list) -> str:
if not rollup:
return "NONE"
conclusions = {r.get("conclusion") for r in rollup if r.get("conclusion")}
if conclusions & _CI_FAILURE_CONCLUSIONS:
return "FAILURE"
statuses = {r.get("status") for r in rollup}
if "IN_PROGRESS" in statuses or "QUEUED" in statuses:
return "PENDING"
if "SUCCESS" in conclusions:
return "SUCCESS"
return "NONE"
def fetch_prs(repo: str | None = None, base: str | None = None, limit: int = 50) -> list[PRInfo]:
resolved_base = base or _detect_default_branch(repo)
args = [
"pr", "list", "--state", "open", "--limit", str(limit),
"--json", "number,title,headRefName,baseRefName,author,isDraft,"
"reviewDecision,statusCheckRollup,updatedAt",
]
if repo:
args += ["--repo", repo]
raw = _gh(*args)
if raw is None:
raise RuntimeError("gh CLI not found or not authenticated. Run: gh auth login")
prs = []
for item in raw:
updated = datetime.fromisoformat(item["updatedAt"].replace("Z", "+00:00"))
prs.append(PRInfo(
number=item["number"],
title=item["title"],
branch=item["headRefName"],
base_branch=item["baseRefName"],
author=item["author"]["login"] if item.get("author") else "?",
is_draft=item.get("isDraft", False),
review_decision=item.get("reviewDecision") or "",
ci_status=_parse_ci(item.get("statusCheckRollup") or []),
updated_at=updated,
expected_base=resolved_base,
))
return prs
def fetch_pr_files(number: int, repo: str | None = None) -> list[str]:
args = ["pr", "diff", str(number), "--name-only"]
if repo:
args += ["--repo", repo]
try:
result = subprocess.run(["gh", *args], capture_output=True, text=True, timeout=30)
if result.returncode != 0:
return []
return [l.strip() for l in result.stdout.splitlines() if l.strip()]
except (subprocess.TimeoutExpired, FileNotFoundError):
return []
# ── Graph-native impact (used by MCP tools — works on nx.Graph directly) ─────
def _path_match(graph_src: str, pr_file: str) -> bool:
"""True if graph_src and pr_file refer to the same file (path-boundary safe)."""
if graph_src == pr_file:
return True
return graph_src.endswith("/" + pr_file) or pr_file.endswith("/" + graph_src)
def compute_pr_impact(files: list[str], G: "nx.Graph") -> tuple[list[int], int]:
"""Return (communities_touched, nodes_affected) for a set of changed files.
Builds a file→(communities, count) index first so lookup is O(nodes + files)
rather than O(nodes × files).
"""
# Build index once
file_comms: dict[str, set[int]] = {}
file_count: dict[str, int] = {}
for _, data in G.nodes(data=True):
src = data.get("source_file") or ""
if not src:
continue
if src not in file_comms:
file_comms[src] = set()
file_count[src] = 0
c = data.get("community")
if c is not None:
file_comms[src].add(int(c))
file_count[src] += 1
comms: set[int] = set()
nodes = 0
matched: set[str] = set()
for f in files:
for src, src_comms in file_comms.items():
if src not in matched and _path_match(src, f):
comms |= src_comms
nodes += file_count[src]
matched.add(src)
return sorted(comms), nodes
def format_prs_text(prs: list["PRInfo"], base: str) -> str:
"""Plain-text PR summary for MCP output (no ANSI)."""
actionable = [p for p in prs if p.base_branch == base]
wrong = len(prs) - len(actionable)
lines = [f"Open PRs targeting {base}: {len(actionable)} ({wrong} on wrong base, not shown)\n"]
for p in sorted(actionable, key=lambda x: (_STATUS_ORDER.index(x.status) if x.status in _STATUS_ORDER else 99, x.days_old)):
impact = f" blast_radius={p.blast_radius}" if p.blast_radius else ""
lines.append(
f"#{p.number} [{p.status}] CI={p.ci_status} review={p.review_decision or 'none'} "
f"age={p.days_old}d author={p.author}{impact}\n {p.title}"
)
return "\n\n".join(lines)
# ── Worktree mapping ──────────────────────────────────────────────────────────
def fetch_worktrees() -> dict[str, str]:
"""Returns {branch: worktree_path}."""
try:
result = subprocess.run(
["git", "worktree", "list", "--porcelain"],
capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
return {}
except (subprocess.TimeoutExpired, FileNotFoundError):
return {}
mapping: dict[str, str] = {}
current_path = None
for line in result.stdout.splitlines():
if not line:
current_path = None # blank line = record separator; reset to avoid leaking across detached HEADs
elif line.startswith("worktree "):
current_path = line[9:]
elif line.startswith("branch refs/heads/") and current_path:
mapping[line[18:]] = current_path
return mapping
# ── Graph impact analysis ─────────────────────────────────────────────────────
def _load_graph_json(graph_path: Path) -> dict | None:
if not graph_path.exists():
return None
from graphify.security import check_graph_file_size_cap
try:
check_graph_file_size_cap(graph_path)
return json.loads(graph_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError, ValueError):
return None
def build_community_labels(data: dict, top_n: int = 4) -> dict[int, list[str]]:
"""Return {community_id: [top_labels]} extracted from graph node data."""
comm_labels: dict[int, list[str]] = defaultdict(list)
for node in data.get("nodes", []):
c = node.get("community")
if c is None:
continue
label = node.get("label") or node.get("id") or ""
if label:
comm_labels[int(c)].append(label)
return {c: labels[:top_n] for c, labels in comm_labels.items()}
def attach_graph_impact(
prs: list[PRInfo], graph_path: Path, repo: str | None = None
) -> dict[int, list[str]]:
"""Fetch PR file lists concurrently, compute graph impact, return community labels."""
data = _load_graph_json(graph_path)
if not data:
return {}
# Build file → {community, node_count} index
file_to_communities: dict[str, set[int]] = {}
file_to_nodes: dict[str, int] = {}
for node in data.get("nodes", []):
src = node.get("source_file") or ""
if not src:
continue
comm = node.get("community")
if src not in file_to_communities:
file_to_communities[src] = set()
file_to_nodes[src] = 0
if comm is not None:
file_to_communities[src].add(int(comm))
file_to_nodes[src] += 1
# Fetch diffs concurrently — gh pr diff is the bottleneck (network I/O)
actionable = [pr for pr in prs if pr.status != "WRONG-BASE"]
workers = min(8, len(actionable)) if actionable else 1
with ThreadPoolExecutor(max_workers=workers) as pool:
future_to_pr = {
pool.submit(fetch_pr_files, pr.number, repo): pr
for pr in actionable
}
for fut in as_completed(future_to_pr):
pr = future_to_pr[fut]
try:
files = fut.result()
except Exception:
files = []
pr.files_changed = files
comms: set[int] = set()
nodes = 0
matched: set[str] = set()
for f in files:
for gf, gcomms in file_to_communities.items():
if gf not in matched and _path_match(gf, f):
comms |= gcomms
nodes += file_to_nodes.get(gf, 0)
matched.add(gf)
pr.communities_touched = sorted(comms)
pr.nodes_affected = nodes
return build_community_labels(data)
# ── Dashboard rendering ───────────────────────────────────────────────────────
def _truncate(s: str, n: int) -> str:
return s if len(s) <= n else s[:n - 1] + "…"
def render_dashboard(prs: list[PRInfo], base: str = "v8", show_wrong_base: bool = False) -> None:
actionable = [p for p in prs if p.base_branch == base]
wrong_base = [p for p in prs if p.base_branch != base]
# Sort: READY first, then by status order, then by recency
actionable.sort(key=lambda p: (_STATUS_ORDER.index(p.status) if p.status in _STATUS_ORDER else 99, p.days_old))
print()
print(bold(f" graphify prs · base: {base} · {len(actionable)} PRs"))
print()
if not actionable:
print(dim(" No open PRs targeting this base branch."))
else:
# Header
print(f" {'#':>4} {'CI':2} {'STATUS':13} {'UPDATED':8} {'IMPACT':22} TITLE")
print(f" {'─'*4} {'─'*2} {'─'*13} {'─'*8} {'─'*22} {'─'*40}")
for pr in actionable:
status_str = _pad(_status_color(pr.status), 13)
ci_str = _ci_icon(pr.ci_status)
age = f"{pr.days_old}d" if pr.days_old > 0 else "today"
impact = _pad(dim(_truncate(pr.blast_radius, 22)), 22) if pr.blast_radius else _pad(dim("–"), 22)
wt = f" {cyan('⬡')}" if pr.worktree_path else " "
draft = dim(" [draft]") if pr.is_draft else ""
title = _truncate(pr.title, 52)
num = _pad(bold(f"#{pr.number}"), 6)
print(f" {num}{wt} {ci_str} {status_str} {age:>6} {impact} {title}{draft}")
# Summary line
by_status: dict[str, int] = {}
for p in actionable:
by_status[p.status] = by_status.get(p.status, 0) + 1
parts = []
if by_status.get("READY"): parts.append(green(f"{by_status['READY']} ready"))
if by_status.get("APPROVED"): parts.append(bold(green(f"{by_status['APPROVED']} approved")))
if by_status.get("PENDING"): parts.append(yellow(f"{by_status['PENDING']} pending CI"))
if by_status.get("CI-FAIL"): parts.append(red(f"{by_status['CI-FAIL']} CI failing"))
if by_status.get("CHANGES-REQ"):parts.append(red(f"{by_status['CHANGES-REQ']} changes requested"))
if by_status.get("DRAFT"): parts.append(yellow(f"{by_status['DRAFT']} draft"))
if by_status.get("STALE"): parts.append(dim(f"{by_status['STALE']} stale"))
if wrong_base:
parts.append(dim(f"{len(wrong_base)} wrong base"))
print()
print(f" {' · '.join(parts)}")
print()
if wrong_base and show_wrong_base:
print(dim(f" ── {len(wrong_base)} PRs targeting wrong base ──"))
for pr in sorted(wrong_base, key=lambda p: p.number, reverse=True):
print(dim(f" #{pr.number:4} base={pr.base_branch:12} {_truncate(pr.title, 60)}"))
print()
def render_worktrees(prs: list[PRInfo], worktrees: dict[str, str]) -> None:
print()
print(bold(" Worktrees"))
print()
if not worktrees:
print(dim(" No active worktrees found."))
print()
return
pr_by_branch = {p.branch: p for p in prs}
for branch, path in sorted(worktrees.items()):
pr = pr_by_branch.get(branch)
if pr:
status = _status_color(pr.status)
print(f" {cyan(path)}")
print(f" {dim('branch:')} {branch} -> PR {bold(f'#{pr.number}')} [{status}] {_truncate(pr.title, 50)}")
else:
print(f" {cyan(path)}")
print(f" {dim('branch:')} {branch} {dim('(no open PR)')}")
print()
def render_conflicts(
prs: list[PRInfo],
base: str = "v8",
community_labels: dict[int, list[str]] | None = None,
) -> None:
actionable = [p for p in prs if p.base_branch == base and p.communities_touched]
if not actionable:
print(dim("\n No graph impact data - run with a valid graph.json to detect conflicts.\n"))
return
# Build community → [PRs] map
comm_to_prs: dict[int, list[PRInfo]] = {}
for pr in actionable:
for c in pr.communities_touched:
comm_to_prs.setdefault(c, []).append(pr)
conflicts = {c: ps for c, ps in comm_to_prs.items() if len(ps) > 1}
if not conflicts:
print(green("\n No community overlap between open PRs - safe to merge in any order.\n"))
return
print()
print(bold(" Community conflicts (PRs sharing the same graph community)"))
print()
labels = community_labels or {}
for comm, ps in sorted(conflicts.items(), key=lambda x: -len(x[1])):
comm_label_str = ""
if comm in labels and labels[comm]:
comm_label_str = dim(" — " + ", ".join(labels[comm]))
print(f" {yellow(f'Community {comm}')}{comm_label_str} ({len(ps)} PRs overlap)")
for pr in ps:
print(f" #{pr.number:4} {_pad(_status_color(pr.status), 13)} {_truncate(pr.title, 55)}")
print()
def render_pr_detail(pr: PRInfo, repo: str | None = None) -> None:
print()
print(bold(f" PR #{pr.number} · {_status_color(pr.status)}"))
print(f" {pr.title}")
print()
print(f" {dim('branch:')} {pr.branch} -> {pr.base_branch}")
print(f" {dim('author:')} {pr.author}")
print(f" {dim('updated:')} {pr.days_old}d ago")
print(f" {dim('CI:')} {_ci_icon(pr.ci_status)} {pr.ci_status}")
if pr.review_decision:
print(f" {dim('review:')} {pr.review_decision}")
if pr.worktree_path:
print(f" {dim('worktree:')} {cyan(pr.worktree_path)}")
if pr.blast_radius:
print()
print(f" {bold('Graph impact:')} {pr.blast_radius}")
print(f" {dim('communities:')} {pr.communities_touched}")
if pr.files_changed:
print(f" {dim('files changed:')} {len(pr.files_changed)}")
for f in pr.files_changed[:10]:
print(f" {dim(f)}")
if len(pr.files_changed) > 10:
print(dim(f" … and {len(pr.files_changed) - 10} more"))
print()
# ── Triage (multi-backend) ────────────────────────────────────────────────────
# Best model per backend for reasoning tasks (different from extraction defaults)
_TRIAGE_MODEL_DEFAULTS: dict[str, str] = {
"claude": "claude-opus-4-7",
"kimi": "kimi-k2.6",
"openai": "gpt-4.1-mini",
"gemini": "gemini-3-flash-preview",
}
def _resolve_triage_backend() -> tuple[str, str]:
"""Return (backend, model) using GRAPHIFY_TRIAGE_BACKEND or first available key."""
from graphify.llm import BACKENDS, _get_backend_api_key, _default_model_for_backend
explicit = os.environ.get("GRAPHIFY_TRIAGE_BACKEND", "").strip()
if explicit in BACKENDS:
model = (os.environ.get("GRAPHIFY_TRIAGE_MODEL")
or _TRIAGE_MODEL_DEFAULTS.get(explicit)
or _default_model_for_backend(explicit))
return explicit, model
for b in ("claude", "kimi", "openai", "gemini"):
if _get_backend_api_key(b):
model = (os.environ.get("GRAPHIFY_TRIAGE_MODEL")
or _TRIAGE_MODEL_DEFAULTS.get(b)
or _default_model_for_backend(b))
return b, model
import shutil
if shutil.which("claude"):
return "claude-cli", "claude-code-plan"
return "ollama", _default_model_for_backend("ollama")
def triage_with_opus(prs: list[PRInfo], base: str) -> None:
try:
from graphify.llm import BACKENDS, _get_backend_api_key
except ImportError:
print(red(" graphify.llm not available - cannot run triage."), file=sys.stderr)
sys.exit(1)
candidates = [p for p in prs if p.base_branch == base and p.status not in ("WRONG-BASE", "STALE")]
if not candidates:
print(dim(" No actionable PRs to triage."))
return
lines = []
for pr in candidates:
impact = f", blast_radius={pr.blast_radius}" if pr.blast_radius else ""
lines.append(
f"PR #{pr.number} [{pr.status}] CI={pr.ci_status} review={pr.review_decision or 'none'} "
f"age={pr.days_old}d author={pr.author}{impact}\n title: {pr.title}"
)
prompt = (
"You are a senior engineer helping triage a PR review queue. "
"Given these open PRs, rank them by review priority for the repo maintainer. "
"For each PR give: priority number, one sentence on what action to take and why. "
"Be direct and specific. Format each as: #<number> — <action>.\n\n"
+ "\n\n".join(lines)
)
try:
backend, model = _resolve_triage_backend()
except Exception as e:
print(red(f" Could not resolve triage backend: {e}"), file=sys.stderr)
sys.exit(1)
print()
print(bold(" Triage") + dim(f" ({backend} / {model})"))
print()
try:
if backend == "claude":
import anthropic
client = anthropic.Anthropic(api_key=_get_backend_api_key("claude"))
with client.messages.stream(
model=model, max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
) as stream:
print(" ", end="", flush=True)
for text in stream.text_stream:
print(text.replace("\n", "\n "), end="", flush=True)
print("\n")
elif backend in ("kimi", "openai", "gemini", "ollama"):
from openai import OpenAI
cfg = BACKENDS[backend]
api_key = _get_backend_api_key(backend) or "ollama"
client = OpenAI(api_key=api_key, base_url=cfg.get("base_url", ""))
with client.chat.completions.create(
model=model, max_tokens=1024, stream=True,
messages=[{"role": "user", "content": prompt}],
) as stream:
print(" ", end="", flush=True)
for chunk in stream:
delta = chunk.choices[0].delta.content if chunk.choices else None
if delta:
print(delta.replace("\n", "\n "), end="", flush=True)
print("\n")
elif backend == "claude-cli":
import platform as _platform, shutil as _shutil, subprocess as _sp
_claude = "claude"
if _platform.system() == "Windows":
_claude = _shutil.which("claude.cmd") or _shutil.which("claude") or "claude"
proc = _sp.run(
[_claude, "-p", "--no-session-persistence"],
input=prompt, capture_output=True, text=True, timeout=120,
)
if proc.returncode != 0:
print(red(f" claude -p failed: {proc.stderr.strip()[:300]}"), file=sys.stderr)
else:
try:
result = json.loads(proc.stdout).get("result") or proc.stdout
except json.JSONDecodeError:
result = proc.stdout
for line in result.splitlines():
print(f" {line}")
print()
except Exception as e:
print(f"\n\n {red(f'Triage failed: {e}')}", file=sys.stderr)
# ── Entry point ───────────────────────────────────────────────────────────────
def cmd_prs(argv: list[str]) -> None:
base: str | None = None # auto-detected from repo if not given
repo: str | None = None
do_triage = False
do_worktrees = False
do_conflicts = False
show_wrong_base = False
pr_number: int | None = None
graph_path = Path("graphify-out/graph.json")
i = 0
while i < len(argv):
arg = argv[i]
if arg == "--triage":
do_triage = True
elif arg == "--worktrees":
do_worktrees = True
elif arg == "--conflicts":
do_conflicts = True
elif arg == "--wrong-base":
show_wrong_base = True
elif arg in ("--base", "-b") and i + 1 < len(argv):
base = argv[i + 1]; i += 1
elif arg.startswith("--base="):
base = arg.split("=", 1)[1]
elif arg in ("--repo", "-R") and i + 1 < len(argv):
repo = argv[i + 1]; i += 1
elif arg.startswith("--graph="):
graph_path = Path(arg.split("=", 1)[1])
elif arg == "--graph" and i + 1 < len(argv):
graph_path = Path(argv[i + 1]); i += 1
elif arg.lstrip("#").isdigit():
pr_number = int(arg.lstrip("#"))
elif arg in ("-h", "--help"):
print(__doc__)
return
i += 1
if base is None:
base = _detect_default_branch(repo)
try:
prs = fetch_prs(repo=repo, base=base)
except RuntimeError as e:
print(red(f" Error: {e}"), file=sys.stderr)
sys.exit(1)
worktrees = fetch_worktrees()
for pr in prs:
pr.worktree_path = worktrees.get(pr.branch)
# Graph impact is expensive (concurrent gh pr diff calls) — only fetch when
# the user actually needs it: deep dive, triage, and conflict detection.
community_labels: dict[int, list[str]] = {}
needs_impact = graph_path.exists() and (pr_number is not None or do_triage or do_conflicts)
if needs_impact:
community_labels = attach_graph_impact(prs, graph_path, repo)
if pr_number is not None:
match = next((p for p in prs if p.number == pr_number), None)
if not match:
print(red(f" PR #{pr_number} not found in open PRs."), file=sys.stderr)
sys.exit(1)
render_pr_detail(match, repo)
return
if do_triage:
render_dashboard(prs, base, show_wrong_base)
triage_with_opus(prs, base)
return
if do_worktrees:
render_worktrees(prs, worktrees)
return
if do_conflicts:
render_dashboard(prs, base, show_wrong_base)
render_conflicts(prs, base, community_labels)
return
render_dashboard(prs, base, show_wrong_base)
+70
View File
@@ -0,0 +1,70 @@
"""Query logging for graphify — append-only JSONL, fail-silent."""
from __future__ import annotations
import json
import os
import re
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
_NODES_RE = re.compile(r"(\d+)\s+nodes?\s+found")
def _log_path() -> Path | None:
if os.environ.get("GRAPHIFY_QUERY_LOG_DISABLE", "").lower() in ("1", "true", "yes"):
return None
override = os.environ.get("GRAPHIFY_QUERY_LOG", "").strip()
if override:
return Path(override).expanduser()
return Path.home() / ".cache" / "graphify-queries.log"
def _log_responses() -> bool:
return os.environ.get("GRAPHIFY_QUERY_LOG_RESPONSES", "").lower() in ("1", "true", "yes")
def nodes_from_result(result: str) -> int | None:
m = _NODES_RE.search(result or "")
return int(m.group(1)) if m else None
def log_query(
*,
kind: str,
question: str,
corpus: str,
result: str | None = None,
nodes_returned: int | None = None,
duration_ms: float | None = None,
**extra: Any,
) -> None:
"""Append one JSONL record to the query log. Never raises."""
try:
path = _log_path()
if path is None:
return
if nodes_returned is None and result is not None:
nodes_returned = nodes_from_result(result)
rec: dict[str, Any] = {
"ts": datetime.now(timezone.utc).isoformat(),
"kind": kind,
"question": question,
"corpus": corpus,
"nodes_returned": nodes_returned,
}
if result is not None:
rec["result_chars"] = len(result)
if duration_ms is not None:
rec["duration_ms"] = round(duration_ms, 3)
for k, v in extra.items():
if v is not None:
rec[k] = v
if result is not None and _log_responses():
rec["response"] = result
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as fh:
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
except Exception:
pass
+24 -2
View File
@@ -28,6 +28,10 @@ def generate(
) -> str:
today = date.today().isoformat()
# JSON deserialization produces string keys; normalize to int so .get(cid) works.
if community_labels:
community_labels = {int(k) if isinstance(k, str) else k: v for k, v in community_labels.items()}
confidences = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
total = len(confidences) or 1
ext_pct = round(confidences.count("EXTRACTED") / total * 100)
@@ -115,6 +119,21 @@ def generate(
else:
lines.append("- None detected - all connections are within the same source files.")
# Circular imports surfaced from file-level dependency graph.
from .analyze import find_import_cycles
cycles = find_import_cycles(G)
lines += ["", "## Import Cycles"]
if cycles:
for c in cycles:
cycle = c.get("cycle", [])
length = c.get("length", len(cycle))
if not cycle:
continue
cycle_path = " -> ".join(cycle + [cycle[0]])
lines.append(f"- {length}-file cycle: `{cycle_path}`")
else:
lines.append("- None detected.")
hyperedges = G.graph.get("hyperedges", [])
if hyperedges:
lines += ["", "## Hyperedges (group relationships)"]
@@ -140,7 +159,7 @@ def generate(
lines += [
"",
f"### Community {cid} - \"{label}\"",
f"Cohesion: {score}",
f"Cohesion: {score:.2f}",
f"Nodes ({len(real_nodes)}): {', '.join(display)}{suffix}",
]
@@ -160,7 +179,10 @@ def generate(
isolated = [
n for n in G.nodes()
if G.degree(n) <= 1 and not _is_file_node(G, n) and not _is_concept_node(G, n)
if G.degree(n) <= 1
and not _is_file_node(G, n)
and not _is_concept_node(G, n)
and G.nodes[n].get("file_type") != "rationale"
]
thin_communities = {
cid: nodes for cid, nodes in communities.items()
+363
View File
@@ -0,0 +1,363 @@
"""scip_ingest.py — SCIP JSON ingestion (simplified subset).
Reads a simplified SCIP-style JSON structure and converts it into
Graphify nodes and edges. NOT a full SCIP protobuf implementation —
this is a skeleton that consumes the simplified shape described below.
Not wired to the CLI in this phase.
Entry point:
ingest_scip_json(doc: object, source_file: str = "",
language: str = "python") -> dict[str, Any]
Returns {"nodes": [...], "edges": [...]} compatible with Graphify's
extraction result format. All edges emitted are endpoint-safe — the
function builds a symbol → node_id index in a first pass and either
resolves relationship targets via that index or creates a stub
external node so `build_from_json()` will keep the edge.
Supported (simplified) JSON shape:
documents[]: { relative_path, language, symbols[] }
symbols[]: { symbol, kind, display_name, documentation[],
relationships[], occurrences[] }
relationships[]: { symbol, is_reference, is_implementation,
is_type_definition, is_definition }
occurrences[]: { range[], symbol, symbol_roles }
This shape diverges from the official SCIP protobuf (where occurrences
live on the document, not on each symbol). We consume the simplified
shape that LLM-generated SCIP-style JSON commonly produces. Future
cycles may add document-level occurrence support.
"""
from __future__ import annotations
import hashlib
import re
from typing import Any
from graphify.security import sanitize_metadata
def ingest_scip_json(
doc: object,
source_file: str = "",
language: str = "python",
) -> dict[str, Any]:
"""Convert a SCIP-style JSON document into Graphify nodes and edges.
Parameter ``doc`` is ``object`` (not ``dict[str, Any]``) because SCIP
documents come from external tools — we may be handed arbitrary
deserialized JSON. The first check rejects anything that isn't a dict
and returns the empty result.
Two-pass design:
1. Build a ``symbol_str → node_id`` index across every valid symbol
in every valid document, plus collect per-symbol metadata.
2. Emit nodes for every indexed symbol and then emit relationship
edges. Relationship targets are resolved via the index when
present; otherwise a stub ``scip_external`` node is added so
edges never dangle.
"""
nodes: list[dict[str, Any]] = []
edges: list[dict[str, Any]] = []
seen_node_ids: set[str] = set()
seen_edges: set[tuple[str, str, str, str | None]] = set()
if not isinstance(doc, dict):
return {"nodes": nodes, "edges": edges}
documents = doc.get("documents", [])
if not isinstance(documents, list):
return {"nodes": nodes, "edges": edges}
# ---- pass 1: build symbol → node_id indices -----------------------------
# Two indices so relationship resolution can be document-aware:
# per_doc: (symbol_id, doc_path) → node_id (same-document precedence)
# global: symbol_id → list[node_id] (cross-document fallback,
# used only when unambiguous)
per_doc_index: dict[tuple[str, str], str] = {}
global_index: dict[str, list[str]] = {}
# Per-symbol metadata kept for pass-2 node emission (avoids re-walking
# the document tree).
symbol_records: list[dict[str, Any]] = []
for document in documents:
if not isinstance(document, dict):
continue
doc_path = _coerce_str(document.get("relative_path"), source_file)
doc_language = _coerce_str(document.get("language"), language)
symbols = document.get("symbols", [])
if not isinstance(symbols, list):
continue
for symbol in symbols:
if not isinstance(symbol, dict):
continue
symbol_id = _coerce_str(symbol.get("symbol"), "")
if not symbol_id:
continue
node_id = _make_scip_node_id(symbol_id, doc_path)
per_doc_index.setdefault((symbol_id, doc_path), node_id)
# Dedupe node_ids in the global index — duplicate symbol records
# within the SAME document produce identical node_ids, and we
# don't want them to look like cross-document ambiguity.
candidates = global_index.setdefault(symbol_id, [])
if node_id not in candidates:
candidates.append(node_id)
symbol_records.append(
{
"node_id": node_id,
"symbol_id": symbol_id,
"doc_path": doc_path,
"language": doc_language,
"raw": symbol,
}
)
# ---- pass 2: emit nodes + relationship edges -----------------------------
for record in symbol_records:
_emit_symbol_node(record, nodes, seen_node_ids)
_emit_relationships(
record,
per_doc_index,
global_index,
nodes,
edges,
seen_node_ids,
seen_edges,
)
return {"nodes": nodes, "edges": edges}
def _emit_symbol_node(
record: dict[str, Any],
nodes: list[dict[str, Any]],
seen_node_ids: set[str],
) -> None:
"""Append the canonical node for a SCIP symbol record."""
node_id = record["node_id"]
if node_id in seen_node_ids:
return
raw = record["raw"]
symbol_id = record["symbol_id"]
doc_path = record["doc_path"]
kind = _coerce_str(raw.get("kind"), "unknown")
display_name = _coerce_str(raw.get("display_name"), "")
documentation = raw.get("documentation", [])
description = ""
if isinstance(documentation, list) and documentation:
first = documentation[0]
if isinstance(first, str):
description = first
occurrences = raw.get("occurrences", [])
sourceline = _first_occurrence_line(occurrences)
suffix = symbol_id.split("#")[-1] if "#" in symbol_id else symbol_id
label = display_name or suffix or symbol_id
seen_node_ids.add(node_id) # label uses display_name or suffix (never empty for valid symbols)
nodes.append(
{
"id": node_id,
"label": label,
"file_type": _scip_kind_to_file_type(kind),
"source_file": doc_path,
"source_location": f"L{sourceline}" if sourceline else "",
"metadata": sanitize_metadata(_build_scip_metadata(symbol_id, kind, description)),
}
)
def _emit_relationships(
record: dict[str, Any],
per_doc_index: dict[tuple[str, str], str],
global_index: dict[str, list[str]],
nodes: list[dict[str, Any]],
edges: list[dict[str, Any]],
seen_node_ids: set[str],
seen_edges: set[tuple[str, str, str, str | None]],
) -> None:
"""Append edges (and stub nodes when needed) for a symbol's relationships.
Relationship target resolution order:
1. Same-document `(target_symbol, doc_path)` — duplicate local symbol
names across files route to THIS file's symbol, not another's.
2. Unique cross-document match — when the symbol exists in exactly
one document and that document is different from the source.
3. Stub external node — for symbols not declared in any document
OR ambiguous duplicates across multiple documents (refusing to
guess silently).
"""
raw = record["raw"]
source_node_id = record["node_id"]
doc_path = record["doc_path"]
occurrences = raw.get("occurrences", [])
sourceline = _first_occurrence_line(occurrences)
relationships = raw.get("relationships")
if not isinstance(relationships, list):
return
for rel in relationships:
if not isinstance(rel, dict):
continue
target_symbol = _coerce_str(rel.get("symbol"), "")
if not target_symbol:
continue
target_node_id = _resolve_relationship_target(
target_symbol,
doc_path,
per_doc_index,
global_index,
)
if target_node_id is None:
# External relationship target: emit a stub node so the edge
# is never dangling. The stub uses the source document's path
# as its host context.
target_node_id = _make_scip_node_id(target_symbol, doc_path)
if target_node_id not in seen_node_ids:
seen_node_ids.add(target_node_id)
suffix = target_symbol.split("#")[-1] if "#" in target_symbol else target_symbol
nodes.append(
{
"id": target_node_id,
"label": suffix or target_symbol,
"file_type": "code",
"source_file": doc_path,
"source_location": "",
"metadata": sanitize_metadata(
_build_scip_metadata(target_symbol, "external", "")
),
}
)
relation = _scip_relation_for(rel)
source_location = f"L{sourceline}" if sourceline else ""
key = (source_node_id, target_node_id, relation, source_location)
if key in seen_edges:
continue
seen_edges.add(key)
edges.append(
{
"source": source_node_id,
"target": target_node_id,
"relation": relation,
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": doc_path,
"source_location": source_location,
"weight": 1.0,
"context": "scip",
"metadata": sanitize_metadata({"scip_relationship": rel}),
}
)
def _resolve_relationship_target(
target_symbol: str,
source_doc_path: str,
per_doc_index: dict[tuple[str, str], str],
global_index: dict[str, list[str]],
) -> str | None:
"""Resolve a SCIP relationship target to an emitted node id, or None.
Resolution order:
1. Same-document match — `(target_symbol, source_doc_path)`.
2. Unique cross-document match — exactly one node id in the global
index for this symbol AND it isn't the same document we already
tried.
3. None — symbol is either absent globally OR ambiguous (defined in
multiple documents). The caller emits a stub external node.
"""
same_doc = per_doc_index.get((target_symbol, source_doc_path))
if same_doc is not None:
return same_doc
candidates = global_index.get(target_symbol, [])
if len(candidates) == 1:
return candidates[0]
return None
def _is_true(value: object) -> bool:
"""Return True only when value is exactly the boolean True.
Used for SCIP relationship flags. Truthy strings like ``"false"`` are
common in untrusted external JSON and must NOT count as a set flag.
"""
return value is True
def _scip_relation_for(rel: dict[str, Any]) -> str:
"""Pick the Graphify relation tag for a SCIP relationship dict.
Flags are accepted only when the value is exactly ``True`` — protects
against truthy-but-misleading values like ``"false"`` in external JSON.
"""
if _is_true(rel.get("is_implementation")):
return "scip_impl"
if _is_true(rel.get("is_type_definition")):
return "scip_typed"
if _is_true(rel.get("is_definition")):
return "scip_def"
return "scip_ref"
def _first_occurrence_line(occurrences: object) -> int:
"""Read the 1-based line number from the first occurrence range, defensively.
Note: ``bool`` is a subclass of ``int`` in Python — ``isinstance(True, int)``
is True. We explicitly exclude booleans so a malformed ``range: [True, …]``
cannot produce ``source_location = "LTrue"``.
"""
if not isinstance(occurrences, list) or not occurrences:
return 0
first = occurrences[0]
if not isinstance(first, dict):
return 0
rng = first.get("range", [])
if not isinstance(rng, list) or len(rng) < 1:
return 0
line = rng[0]
if isinstance(line, bool) or not isinstance(line, int) or line < 0:
return 0
return line
def _coerce_str(value: object, default: str) -> str:
"""Return ``value`` if it is a string, else the ``default`` (also a string)."""
if isinstance(value, str):
return value
if isinstance(default, str):
return default
return ""
def _make_scip_node_id(symbol: str, source_file: str) -> str:
"""Derive a stable Graphify node ID from a SCIP symbol identifier.
Uses SHA-1 truncated to 12 hex chars (48 bits). This is an identifier,
not a security boundary — collision risk is acceptable at this scale
given the per-document scoping prefix.
"""
raw = f"{source_file}:{symbol}"
h = hashlib.sha1(raw.encode(), usedforsecurity=False).hexdigest()[:12]
parts = symbol.split("#")
suffix = parts[-1] if parts else symbol
suffix = re.sub(r"[^a-zA-Z0-9_]", "_", suffix).strip("_").lower()
if suffix:
return f"scip_{suffix}_{h}"
return f"scip_{h}"
def _scip_kind_to_file_type(kind: str) -> str:
"""Map SCIP symbol kind to a Graphify file_type."""
# All SCIP symbols are code entities (functions, methods, classes, …);
# the `kind` is preserved in metadata for downstream consumers.
_ = kind # acknowledged but not currently used for file_type routing
return "code"
def _build_scip_metadata(symbol_id: str, kind: str, description: str) -> dict[str, str]:
"""Build metadata for a SCIP node."""
meta: dict[str, str] = {
"scip_symbol": symbol_id,
"scip_kind": kind,
}
if description:
meta["scip_description"] = description
return meta
+244 -29
View File
@@ -1,13 +1,16 @@
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
from __future__ import annotations
import contextlib
import html
import http.client
import os
import re
import urllib.error
import urllib.parse
import urllib.request
from collections.abc import Mapping
from pathlib import Path
from typing import Any
import ipaddress
import socket
@@ -16,17 +19,84 @@ _ALLOWED_SCHEMES = {"http", "https"}
_MAX_FETCH_BYTES = 52_428_800 # 50 MB hard cap for binary downloads
_MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
# Graph-load memory-bomb cap: reject .json files larger than this before
# JSON-parsing them into a dict. Without this, a multi-gigabyte (or
# specifically crafted) graph.json can exhaust process memory during
# json.loads + node_link_graph rehydration.
# Default fallback cap. Kept as a module-level constant so the value is
# discoverable and so existing callers/tests that reference it directly keep
# working; the effective cap is resolved at call time by
# ``_max_graph_file_bytes`` (which lets ``GRAPHIFY_MAX_GRAPH_BYTES`` override it).
_MAX_GRAPH_FILE_BYTES = 512 * 1024 * 1024 # 512 MiB
def _max_graph_file_bytes() -> int:
"""Return the graph.json size cap in bytes.
Honors the ``GRAPHIFY_MAX_GRAPH_BYTES`` environment variable so users with
large codebases can raise the limit without editing source. The value may
be plain bytes (``671088640``) or carry an ``MB`` / ``GB`` suffix
(``640MB``, ``2GB`` — case-insensitive, decimal multipliers of 1024).
Falls back to ``_MAX_GRAPH_FILE_BYTES`` (512 MiB) when the env var is unset,
blank, or unparseable.
Read fresh on every call so the env var can be set before import and still
take effect.
"""
raw = os.environ.get("GRAPHIFY_MAX_GRAPH_BYTES", "").strip()
if not raw:
return _MAX_GRAPH_FILE_BYTES
text = raw.upper()
multiplier = 1
if text.endswith("GB"):
multiplier = 1024 * 1024 * 1024
text = text[:-2].strip()
elif text.endswith("MB"):
multiplier = 1024 * 1024
text = text[:-2].strip()
try:
value = int(text)
except ValueError:
return _MAX_GRAPH_FILE_BYTES
if value <= 0:
return _MAX_GRAPH_FILE_BYTES
return value * multiplier
# AWS metadata, link-local, and common cloud metadata endpoints
_BLOCKED_HOSTS = {"metadata.google.internal", "metadata.google.com"}
# RFC 6598 Shared Address Space (CGN) -- is_private misses this on Python <3.11
_CGN_NETWORK = ipaddress.ip_network("100.64.0.0/10")
# RFC 6052 NAT64 Well-Known Prefix -- is_reserved=True in Python but these embed
# public IPv4 addresses and are legitimate public internet traffic, not SSRF vectors.
_NAT64_WKP = ipaddress.ip_network("64:ff9b::/96")
# ---------------------------------------------------------------------------
# URL validation
# ---------------------------------------------------------------------------
def _ip_is_blocked(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
"""Return True if *ip* falls in a private/reserved/internal range.
Shared by validate_url (pre-flight DNS check) and the SSRF-guarded
connection classes (connect-time check) so both use identical logic.
NAT64 well-known-prefix addresses are unwrapped to their embedded IPv4
before the check, since those carry legitimate public traffic.
"""
# For NAT64 addresses, check the embedded IPv4 instead of the wrapper
if isinstance(ip, ipaddress.IPv6Address) and ip in _NAT64_WKP:
ip = ipaddress.ip_address(int(ip) & 0xFFFFFFFF)
return (
ip.is_private
or ip.is_reserved
or ip.is_loopback
or ip.is_link_local
or ip in _CGN_NETWORK
)
def validate_url(url: str) -> str:
"""Raise ValueError if *url* is not http or https, or targets a private/internal IP.
@@ -57,7 +127,7 @@ def validate_url(url: str) -> str:
for info in infos:
addr = info[4][0]
ip = ipaddress.ip_address(addr)
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local or ip in _CGN_NETWORK:
if _ip_is_blocked(ip):
raise ValueError(
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
f"Got: {url!r}"
@@ -70,35 +140,89 @@ def validate_url(url: str) -> str:
return url
@contextlib.contextmanager
def _ssrf_guarded_socket():
"""Patch socket.getaddrinfo for the duration of a fetch to catch DNS rebinding.
# ---------------------------------------------------------------------------
# SSRF-guarded connections
#
# Instead of monkey-patching the process-global socket.getaddrinfo (a
# non-thread-safe TOCTOU hazard when multiple fetches run concurrently),
# we subclass the HTTP(S) connection so each connection resolves DNS exactly
# once, validates the resulting IP, and then connects to that exact IP. There
# is no second resolution, so a DNS-rebind attack cannot swap in a private
# address (e.g. 169.254.169.254) between validation and connection.
# ---------------------------------------------------------------------------
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.
def _resolve_and_validate(host: str, port: int) -> tuple[int, str]:
"""Resolve *host* once and return (family, validated_ip) for the first
address that is not in a blocked range.
Raises OSError if every resolved address is private/reserved/internal,
matching the failure mode urllib/http.client expect from connect().
"""
original = socket.getaddrinfo
infos = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
for family, _type, _proto, _canon, sockaddr in infos:
addr = sockaddr[0]
try:
ip = ipaddress.ip_address(addr)
except ValueError:
continue
if _ip_is_blocked(ip):
raise OSError(
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
)
return family, addr
raise OSError(f"SSRF blocked: no usable address resolved from '{host}'")
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 or ip in _CGN_NETWORK:
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 _SSRFGuardedHTTPConnection(http.client.HTTPConnection):
"""HTTPConnection that resolves + validates DNS once, then connects to the
exact validated IP (no second resolution = no DNS-rebind TOCTOU)."""
def connect(self) -> None:
family, ip = _resolve_and_validate(self.host, self.port)
self.sock = socket.create_connection(
(ip, self.port),
self.timeout,
self.source_address,
)
if self._tunnel_host:
self._tunnel()
class _SSRFGuardedHTTPSConnection(http.client.HTTPSConnection):
"""HTTPSConnection variant of _SSRFGuardedHTTPConnection.
Connects to the validated IP but performs the TLS handshake with
server_hostname set to the original hostname so SNI / certificate
validation work correctly (validating against the IP would break TLS).
"""
def connect(self) -> None:
family, ip = _resolve_and_validate(self.host, self.port)
sock = socket.create_connection(
(ip, self.port),
self.timeout,
self.source_address,
)
if self._tunnel_host:
self.sock = sock
self._tunnel()
sock = self.sock
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
class _SSRFGuardedHTTPHandler(urllib.request.HTTPHandler):
"""urllib handler that routes http:// through _SSRFGuardedHTTPConnection."""
def http_open(self, req):
return self.do_open(_SSRFGuardedHTTPConnection, req)
class _SSRFGuardedHTTPSHandler(urllib.request.HTTPSHandler):
"""urllib handler that routes https:// through _SSRFGuardedHTTPSConnection."""
def https_open(self, req):
return self.do_open(_SSRFGuardedHTTPSConnection, req)
class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
@@ -114,7 +238,14 @@ class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
def _build_opener() -> urllib.request.OpenerDirector:
return urllib.request.build_opener(_NoFileRedirectHandler)
# build_opener replaces the default HTTP(S)Handlers with our SSRF-guarded
# subclasses, so every connection resolves+validates DNS once and connects
# to that exact IP. Thread-safe: no process-global state is mutated.
return urllib.request.build_opener(
_SSRFGuardedHTTPHandler,
_SSRFGuardedHTTPSHandler,
_NoFileRedirectHandler,
)
# ---------------------------------------------------------------------------
@@ -141,7 +272,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 _ssrf_guarded_socket(), opener.open(req, timeout=timeout) as resp:
with 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)
@@ -220,6 +351,35 @@ def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
return resolved
def check_graph_file_size_cap(path: Path) -> None:
"""Reject *path* if its size exceeds the configured graph-file cap.
Protects callers from memory bombs by failing fast before a multi-GiB
graph.json is read into memory and JSON-parsed. Silently returns when
``path.stat()`` cannot be read — the caller's own existence/path check
is expected to surface a clearer error in that case.
The cap is resolved on every call via :func:`_max_graph_file_bytes`, so the
``GRAPHIFY_MAX_GRAPH_BYTES`` env var can be set before import and still
apply.
Raises:
ValueError - file size exceeds the cap. The message includes the
observed size, the cap, and how to raise the limit.
"""
cap = _max_graph_file_bytes()
try:
size = path.stat().st_size
except OSError:
return
if size > cap:
raise ValueError(
f"graph file {path} is {size:_d} bytes, exceeds {cap:_d}-byte cap\n"
f"(set GRAPHIFY_MAX_GRAPH_BYTES=<bytes> or "
f"GRAPHIFY_MAX_GRAPH_BYTES=<N>GB to raise the limit)"
)
# ---------------------------------------------------------------------------
# Label sanitisation (mirrors code-review-graph's _sanitize_name pattern)
# ---------------------------------------------------------------------------
@@ -240,3 +400,58 @@ def sanitize_label(text: str | None) -> str:
if len(text) > _MAX_LABEL_LEN:
text = text[:_MAX_LABEL_LEN]
return text
# ---------------------------------------------------------------------------
# Metadata sanitisation (recursive, bounded, HTML-safe)
# ---------------------------------------------------------------------------
_METADATA_MAX_VALUE_LEN = 512
_METADATA_MAX_LIST_ITEMS = 50
def _sanitize_metadata_string(value: object) -> str:
"""Return a control-character-free, HTML-escaped, bounded string."""
text = _CONTROL_CHAR_RE.sub("", str(value))
text = html.escape(text, quote=True)
if len(text) > _METADATA_MAX_VALUE_LEN:
text = text[:_METADATA_MAX_VALUE_LEN]
return text # html is imported at module level (line 5)
def _sanitize_metadata_value(value: object) -> object:
"""Sanitize a metadata value while preserving simple JSON-compatible types."""
if isinstance(value, bool):
# bool is a subclass of int — must be checked first to avoid coercion.
return value
if isinstance(value, str):
return _sanitize_metadata_string(value)
if isinstance(value, dict):
return sanitize_metadata(value)
if isinstance(value, (list, tuple)):
return [_sanitize_metadata_value(item) for item in value[:_METADATA_MAX_LIST_ITEMS]]
if isinstance(value, (int, float)) or value is None:
return value
return _sanitize_metadata_string(value)
def sanitize_metadata(metadata: Mapping[str, Any] | None) -> dict[str, object]:
"""Sanitize metadata keys and values before graph export.
Metadata is less constrained than node labels: it can contain nested
dicts, lists, source snippets, external index symbols, and docstring
text. This helper keeps the data JSON-compatible, strips control
characters, escapes HTML-sensitive characters in strings, caps long
strings/lists, and drops entries whose key becomes empty after
sanitization.
"""
if metadata is None:
return {}
result: dict[str, object] = {}
for key, value in metadata.items():
clean_key = _sanitize_metadata_string(key)
if not clean_key:
continue
result[clean_key] = _sanitize_metadata_value(value)
return result
+319
View File
@@ -0,0 +1,319 @@
# Semantic fragment sanitizer — converts sentence-like rationale nodes into
# attributes on related nodes and removes invalid file_type values.
#
# Currently called from the skill merge scripts (skill-opencode.md,
# skill-codex.md) so that rationale text never leaks into the knowledge
# graph as standalone nodes. (Future: graphify.llm may wire this into
# _parse_llm_json / _merge_into for non-skill code paths; not done in
# this cycle.)
from __future__ import annotations
import json
import re
from pathlib import Path
# Labels longer than this many characters, or containing >= this many words,
# are candidates for being sentence-like rationale text rather than entity names.
_RATIONALE_MIN_CHARS = 80
_RATIONALE_MIN_WORDS = 8
# Validation limits for untrusted semantic-fragment payloads. See
# validate_semantic_fragment(). Issue #825: returned-JSON normalization for
# OpenCode and Codex agents requires a Python enforcement boundary so a
# malicious or runaway agent response cannot exhaust memory or escape the
# graphify-out chunk directory via crafted node/edge IDs.
MAX_SEMANTIC_FRAGMENT_BYTES = 25 * 1024 * 1024
MAX_SEMANTIC_FRAGMENT_NODES = 10_000
MAX_SEMANTIC_FRAGMENT_EDGES = 100_000
MAX_SEMANTIC_FRAGMENT_HYPEREDGES = 10_000
MAX_SEMANTIC_HYPEREDGE_NODES = 256
MAX_SEMANTIC_ID_LENGTH = 256
VALID_SEMANTIC_FILE_TYPES = frozenset({"code", "document", "paper", "image", "rationale", "concept"})
_SEMANTIC_ID_RE = re.compile(r"^[A-Za-z0-9._:-]+$")
def validate_semantic_fragment(fragment: object) -> list[str]:
"""Return validation errors for an untrusted semantic extraction fragment.
Empty list means valid. Called by skill merge code before
sanitize_semantic_fragment() so malformed or malicious agent JSON is
rejected before it touches the graph. Parameter is `object` (not `dict`)
because we may be handed arbitrary deserialized JSON — the first check
rejects anything that isn't a dict.
"""
if not isinstance(fragment, dict):
return ["fragment must be a JSON object"]
errors: list[str] = []
try:
payload = json.dumps(fragment, ensure_ascii=False).encode("utf-8")
except (TypeError, ValueError) as exc:
return [f"fragment is not JSON-serializable: {exc}"]
if len(payload) > MAX_SEMANTIC_FRAGMENT_BYTES:
errors.append(f"payload is {len(payload)} bytes; max is {MAX_SEMANTIC_FRAGMENT_BYTES}")
nodes = fragment.get("nodes", [])
edges = fragment.get("edges", [])
if not isinstance(nodes, list):
errors.append("nodes must be a list")
nodes = []
elif len(nodes) > MAX_SEMANTIC_FRAGMENT_NODES:
errors.append(f"nodes has {len(nodes)} entries; max is {MAX_SEMANTIC_FRAGMENT_NODES}")
if not isinstance(edges, list):
errors.append("edges must be a list")
edges = []
elif len(edges) > MAX_SEMANTIC_FRAGMENT_EDGES:
errors.append(f"edges has {len(edges)} entries; max is {MAX_SEMANTIC_FRAGMENT_EDGES}")
for i, node in enumerate(nodes):
if not isinstance(node, dict):
errors.append(f"nodes[{i}] must be an object")
continue
_validate_semantic_id(errors, f"nodes[{i}].id", node.get("id"))
file_type = node.get("file_type")
if file_type is not None and file_type not in VALID_SEMANTIC_FILE_TYPES:
errors.append(
f"nodes[{i}].file_type {file_type!r} is not one of "
f"{sorted(VALID_SEMANTIC_FILE_TYPES)}"
) # validate file_type before any sanitize path can run
for i, edge in enumerate(edges):
if not isinstance(edge, dict):
errors.append(f"edges[{i}] must be an object")
continue
_validate_semantic_id(errors, f"edges[{i}].source", edge.get("source"))
_validate_semantic_id(errors, f"edges[{i}].target", edge.get("target"))
hyperedges = fragment.get("hyperedges", [])
if hyperedges is None:
hyperedges = []
if not isinstance(hyperedges, list):
errors.append("hyperedges must be a list")
else:
if len(hyperedges) > MAX_SEMANTIC_FRAGMENT_HYPEREDGES:
errors.append(
f"hyperedges has {len(hyperedges)} entries; "
f"max is {MAX_SEMANTIC_FRAGMENT_HYPEREDGES}"
)
for i, he in enumerate(hyperedges):
if not isinstance(he, dict):
errors.append(f"hyperedges[{i}] must be an object")
continue
_validate_semantic_id(errors, f"hyperedges[{i}].id", he.get("id"))
he_nodes = he.get("nodes")
if not isinstance(he_nodes, list):
errors.append(f"hyperedges[{i}].nodes must be a list")
continue
if len(he_nodes) > MAX_SEMANTIC_HYPEREDGE_NODES:
errors.append(
f"hyperedges[{i}].nodes has {len(he_nodes)} entries; "
f"max is {MAX_SEMANTIC_HYPEREDGE_NODES}"
)
for j, ref in enumerate(he_nodes):
_validate_semantic_id(errors, f"hyperedges[{i}].nodes[{j}]", ref)
return errors
def load_validated_semantic_fragment(path: Path) -> tuple[dict | None, list[str]]:
"""Load and validate a semantic chunk, rejecting oversize files before parsing.
The size guard runs against `path.stat().st_size` so an attacker-supplied
multi-gigabyte chunk file cannot blow up memory at `read_text()` time.
JSON decode errors are returned as validation errors rather than raised,
so callers can `continue` past bad chunks without a try/except.
"""
try:
size = path.stat().st_size
except OSError as exc:
return None, [f"could not stat {path}: {exc}"]
if size > MAX_SEMANTIC_FRAGMENT_BYTES:
return None, [f"payload is {size} bytes; max is {MAX_SEMANTIC_FRAGMENT_BYTES}"]
try:
fragment = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
return None, [f"invalid JSON: {exc}"]
except OSError as exc:
return None, [f"could not read {path}: {exc}"]
errors = validate_semantic_fragment(fragment)
return (None, errors) if errors else (fragment, [])
def _validate_semantic_id(errors: list[str], field: str, value: object) -> None:
if not isinstance(value, str):
errors.append(f"{field} must be a string")
return
if not value:
errors.append(f"{field} must not be empty")
return
if len(value) > MAX_SEMANTIC_ID_LENGTH:
errors.append(f"{field} is {len(value)} chars; max is {MAX_SEMANTIC_ID_LENGTH}")
if "/" in value or "\\" in value or ".." in value:
errors.append(f"{field} must not contain path separators or '..'")
if not _SEMANTIC_ID_RE.fullmatch(value):
errors.append(f"{field} contains unsupported characters")
def sanitize_semantic_fragment(fragment: dict) -> dict:
"""Clean up a semantic extraction fragment in-place.
Operations:
1. Removes nodes with ``file_type: "rationale"`` or ``file_type: "concept"``
that were emitted by an LLM (these are not valid semantic entity types).
2. Detects nodes whose label reads like a sentence / rationale paragraph
AND that participate in a ``rationale_for`` edge, then converts the
label into a ``rationale`` attribute on the target node and removes
the source-node + its edges. The ``rationale_for`` edge signal applies
regardless of the source node's ``file_type`` — sentence-like nodes
with allowed types (``document``, ``code``) are still cleaned up when
they're explicitly marked as rationale.
3. Strips nodes whose only distinguishing field is the label itself
(empty id — likely LLM hallucination).
4. Filters hyperedges so they cannot reference removed or unknown node
IDs after the cleanup passes above. A hyperedge with fewer than two
surviving members is dropped.
Returns the same dict for convenience.
"""
_invalid_ft = frozenset({"rationale", "concept"})
nodes: list[dict] = fragment.get("nodes", [])
edges: list[dict] = fragment.get("edges", [])
hyperedges: list[dict] = fragment.get("hyperedges", []) or []
# ---- build lookup maps --------------------------------------------------
node_by_id: dict[str, dict] = {}
for n in nodes:
nid = n.get("id", "")
if nid:
node_by_id[nid] = n
# Pre-collect node IDs that source a `rationale_for` edge — these are
# candidates for sentence-like cleanup even when file_type is allowed.
rationale_for_sources: set[str] = set()
for e in edges:
if e.get("relation") == "rationale_for":
src = e.get("source", "")
if src:
rationale_for_sources.add(src)
# ---- pass 1: identify nodes to remove + rationale candidates -----------
rationale_candidates: list[dict] = []
remove_ids: set[str] = set()
keep_nodes: list[dict] = []
for n in nodes:
nid = n.get("id", "")
if not nid:
# Node without an id cannot be referenced — discard.
continue
ft = n.get("file_type", "")
label = n.get("label", "")
if ft in _invalid_ft:
# Explicitly-invalid file_type ("rationale" or "concept"): if
# the label looks like a sentence we may convert to attribute.
if _is_sentence_like_rationale_label(label):
rationale_candidates.append(n)
remove_ids.add(nid)
continue
if nid in rationale_for_sources and _is_sentence_like_rationale_label(label):
# Allowed file_type, but the node sources a `rationale_for` edge
# AND its label is sentence-like prose. Treat it as rationale
# cleanup material rather than a real graph entity.
rationale_candidates.append(n)
remove_ids.add(nid)
continue
keep_nodes.append(n)
# ---- pass 2: convert sentence-nodes → rationale attributes --------------
# Only `rationale_for` edges propagate the rationale text. Other outgoing
# edges (e.g. references, conceptually_related_to) are NOT used as
# attribute-propagation paths — that would corrupt unrelated nodes by
# attaching rationale meant for a different target.
rationale_attrs: dict[str, list[str]] = {}
for rn in rationale_candidates:
rn_id = rn.get("id", "")
text = rn.get("label", "").strip()
for e in edges:
if e.get("relation") != "rationale_for":
continue
if e.get("source") != rn_id:
continue
target_id = e.get("target")
if target_id not in node_by_id or target_id in remove_ids:
continue
rationale_attrs.setdefault(target_id, []).append(text)
for target_id, texts in rationale_attrs.items():
if target_id in node_by_id and target_id not in remove_ids:
_append_rationale_attr(node_by_id[target_id], texts)
# ---- pass 3: strip edges referencing removed nodes ----------------------
keep_edges: list[dict] = []
for e in edges:
src = e.get("source", "")
tgt = e.get("target", "")
if src in remove_ids or tgt in remove_ids:
continue
keep_edges.append(e)
# ---- pass 4: filter hyperedges to surviving node IDs --------------------
surviving_ids: set[str] = {n.get("id", "") for n in keep_nodes}
surviving_ids.discard("")
keep_hyperedges: list[dict] = []
for he in hyperedges:
if not isinstance(he, dict):
continue
he_nodes = he.get("nodes")
if not isinstance(he_nodes, list):
continue
filtered = [ref for ref in he_nodes if isinstance(ref, str) and ref in surviving_ids]
if len(filtered) < 2:
# A hyperedge needs at least two surviving members to be meaningful.
continue
if len(filtered) != len(he_nodes):
he = dict(he)
he["nodes"] = filtered
keep_hyperedges.append(he)
fragment["nodes"] = keep_nodes
fragment["edges"] = keep_edges
fragment["hyperedges"] = keep_hyperedges
return fragment
def _is_sentence_like_rationale_label(label: str) -> bool:
"""Return True if *label* looks like prose / rationale text rather than an
entity or concept name.
Heuristics (no false positives on short-concept-edge-cases):
- Longer than *_RATIONALE_MIN_CHARS* chars, OR
- At least *_RATIONALE_MIN_WORDS* whitespace-delimited tokens, AND
- Contains at least one sentence-ending punctuation mark (``. ! ?``) or a
colon (common in "Decision: ..." rationales).
"""
if not label:
return False
label = label.strip()
if len(label) < _RATIONALE_MIN_CHARS:
word_count = len(label.split())
if word_count < _RATIONALE_MIN_WORDS:
return False
# Must look like actual prose: has sentence-ending punctuation or a colon.
return bool(re.search(r"[.!?:]", label))
def _append_rationale_attr(node: dict, texts: list[str]) -> None:
"""Append one or more rationale strings to *node*'s ``rationale`` attribute.
If the attribute already exists the new texts are appended with a
double-newline separator so downstream consumers can distinguish distinct
rationale fragments.
"""
existing = node.get("rationale", "")
new_text = "\n\n".join(texts).strip()
if existing:
node["rationale"] = existing + "\n\n" + new_text
else:
node["rationale"] = new_text
+681 -26
View File
@@ -1,13 +1,20 @@
# MCP stdio server - exposes graph query tools to Claude and other agents
from __future__ import annotations
import json
import math
import re
import sys
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.security import sanitize_label, check_graph_file_size_cap
from graphify.build import edge_data
try:
import jieba as _jieba # type: ignore[import-untyped]
except ImportError:
_jieba = None
def _load_graph(graph_path: str) -> nx.Graph:
try:
@@ -16,6 +23,7 @@ def _load_graph(graph_path: str) -> nx.Graph:
raise ValueError(f"Graph path must be a .json file, got: {graph_path!r}")
if not resolved.exists():
raise FileNotFoundError(f"Graph file not found: {resolved}")
check_graph_file_size_cap(resolved)
safe = resolved
data = json.loads(safe.read_text(encoding="utf-8"))
if "links" not in data and "edges" in data:
@@ -43,40 +51,162 @@ def _communities_from_graph(G: nx.Graph) -> dict[int, list[str]]:
return communities
def _strip_diacritics(text: str) -> str:
def _strip_diacritics(text: str | None) -> str:
import unicodedata
if not isinstance(text, str):
text = "" if text is None else str(text)
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
def _search_tokens(text: str) -> list[str]:
"""Split text into word tokens, stripping punctuation and diacritics."""
return re.findall(r"\w+", _strip_diacritics(str(text)).lower())
def _has_chinese(text: str) -> bool:
return any("一" <= ch <= "鿿" for ch in text)
def _segment_chinese(text: str) -> list[str]:
"""Segment Chinese text and keep the original term for exact matching."""
if _jieba is not None:
segments = [w for w in _jieba.cut(text) if len(w.strip()) > 0]
else:
segments = [text[i:i + 2] for i in range(len(text) - 1)] or [text]
if len(text) > 1 and text not in segments:
segments.append(text)
return segments
def _is_searchable(term: str) -> bool:
"""True if term is Chinese, non-English, or an English word longer than 2 chars."""
if all("a" <= ch <= "z" for ch in term):
return len(term) > 2
return True
def _query_terms(question: str) -> list[str]:
"""Split a query into searchable terms, segmenting Chinese text."""
terms: list[str] = []
for raw in question.split():
if _has_chinese(raw):
for seg in _segment_chinese(raw.lower().strip()):
seg = seg.strip()
if seg and _is_searchable(seg):
terms.append(seg)
else:
# Strip punctuation without touching Unicode characters (avoid NFKD mangling non-Latin scripts)
for tok in re.findall(r"\w+", raw.lower()):
if _is_searchable(tok):
terms.append(tok)
return terms
_EXACT_MATCH_BONUS = 1000.0
_PREFIX_MATCH_BONUS = 100.0
_SUBSTRING_MATCH_BONUS = 1.0
_SOURCE_MATCH_BONUS = 0.5
def _compute_idf(G: nx.Graph, terms: list[str]) -> dict[str, float]:
"""IDF weights for query terms, cached in G.graph['_idf_cache'].
Common terms like 'error' or 'exception' that match hundreds of nodes get
low weights; rare identifiers like 'FooBarService' get high weights.
Cache is stored on the graph object itself so it auto-invalidates when
_maybe_reload() replaces G with a new object.
"""
cache: dict[str, float] = G.graph.setdefault("_idf_cache", {})
N = G.number_of_nodes() or 1
uncached = [t for t in terms if t not in cache]
if uncached:
df: dict[str, int] = {t: 0 for t in uncached}
for _, data in G.nodes(data=True):
norm_label = (
data.get("norm_label") or _strip_diacritics(data.get("label") or "")
).lower()
for t in uncached:
if t in norm_label:
df[t] += 1
for t in uncached:
cache[t] = math.log(1 + N / (1 + df[t]))
return {t: cache.get(t, math.log(1 + N)) for t in terms}
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
scored = []
norm_terms = [_strip_diacritics(t).lower() for t in terms]
norm_terms = [tok for t in terms for tok in _search_tokens(t)]
idf = _compute_idf(G, norm_terms)
# Whole-query string for full-label matching (mirrors _find_node's `term`).
joined = " ".join(norm_terms)
# Weight the full-query bonus by the rarest constituent term so a specific
# multi-word label still outweighs common-token noise; floor at 1.0.
joined_w = max((idf.get(t, 1.0) for t in norm_terms), default=1.0)
for nid, data in G.nodes(data=True):
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
bare_label = norm_label.rstrip("()")
# Tokenized form of the label (punctuation stripped, same transform as the
# query). norm_label may still carry punctuation like ':' or '-', which a
# tokenized query can never equal; comparing token-joined forms on both
# sides makes "uoce: dehumidifier driver" match query "uoce dehumidifier
# driver".
label_tokens = " ".join(_search_tokens(data.get("label") or ""))
source = (data.get("source_file") or "").lower()
score = 0.0
# Full-query tier: a multi-word query that equals (or prefixes) the whole
# label must dominate the per-token bag-of-words sums below, so `path`/
# `query` resolve the same node `explain` does (via _find_node). Without
# this, no single token equals a multi-word label, the per-token exact
# tier never fires, and every node sharing the token set ties -> arbitrary
# node-id sort -> wrong/disconnected endpoint -> false "No path found".
if joined:
nid_lower = nid.lower()
if joined in (norm_label, bare_label, label_tokens, nid_lower):
score += _EXACT_MATCH_BONUS * 10 * joined_w
elif (
norm_label.startswith(joined)
or bare_label.startswith(joined)
or label_tokens.startswith(joined)
):
score += _PREFIX_MATCH_BONUS * 10 * joined_w
for t in norm_terms:
w = idf.get(t, 1.0)
# Three-tier precedence: exact > prefix > substring (take the
# strongest tier per term so a single term cannot double-count).
if t == norm_label or t == bare_label:
score += _EXACT_MATCH_BONUS
score += _EXACT_MATCH_BONUS * w
elif norm_label.startswith(t) or bare_label.startswith(t):
score += _PREFIX_MATCH_BONUS
score += _PREFIX_MATCH_BONUS * w
elif t in norm_label:
score += _SUBSTRING_MATCH_BONUS
score += _SUBSTRING_MATCH_BONUS * w
if t in source:
score += _SOURCE_MATCH_BONUS
score += _SOURCE_MATCH_BONUS * w
if score > 0:
scored.append((score, nid))
return sorted(scored, reverse=True)
# Sort by score desc; break ties toward the shorter label so a concise exact
# match beats a longer superset that happens to share the same score.
scored.sort(key=lambda s: (-s[0], len(G.nodes[s[1]].get("label") or s[1]), s[1]))
return scored
def _pick_seeds(scored: list[tuple[float, str]], max_k: int = 3, gap_ratio: float = 0.2) -> list[str]:
"""Select BFS seed nodes, stopping when score drops too far below the top.
Prevents high-frequency noise terms (error, exception) from stealing seed
slots from a dominant identifier match. When FooBarService scores 1000 and
error nodes score 1.0, only FooBarService is seeded — the score gap is 99.9%
which is well above the 20% threshold that would allow additional seeds.
"""
if not scored:
return []
top_score = scored[0][0]
seeds = []
for score, nid in scored[:max_k]:
if seeds and score < top_score * gap_ratio:
break
seeds.append(nid)
return seeds
_CONTEXT_HINTS: tuple[tuple[str, tuple[str, ...]], ...] = (
@@ -89,6 +219,44 @@ _CONTEXT_HINTS: tuple[tuple[str, tuple[str, ...]], ...] = (
)
_CONTEXT_FILTER_ALIASES: dict[str, str] = {
"param": "parameter_type",
"params": "parameter_type",
"parameter": "parameter_type",
"parameters": "parameter_type",
"argument": "parameter_type",
"arguments": "parameter_type",
"arg": "parameter_type",
"args": "parameter_type",
"return": "return_type",
"returns": "return_type",
"returned": "return_type",
"generic": "generic_arg",
"generics": "generic_arg",
"template": "generic_arg",
"templates": "generic_arg",
"annotation": "attribute",
"annotations": "attribute",
"decorator": "attribute",
"decorators": "attribute",
"calls": "call",
"called": "call",
"invoke": "call",
"invocation": "call",
"fields": "field",
"property": "field",
"properties": "field",
"member": "field",
"members": "field",
"imports": "import",
"imported": "import",
"module": "import",
"modules": "import",
"exports": "export",
"exported": "export",
}
def _normalize_context_filters(filters: list[str] | None) -> list[str]:
if not filters:
return []
@@ -96,7 +264,10 @@ def _normalize_context_filters(filters: list[str] | None) -> list[str]:
seen: set[str] = set()
for value in filters:
key = _strip_diacritics(str(value)).strip().lower()
if key and key not in seen:
if not key:
continue
key = _CONTEXT_FILTER_ALIASES.get(key, key)
if key not in seen:
seen.add(key)
normalized.append(key)
return normalized
@@ -219,7 +390,7 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
f"NODE {sanitize_label(d.get('label', nid))} "
f"[src={sanitize_label(str(d.get('source_file', '')))} "
f"loc={sanitize_label(str(d.get('source_location', '')))} "
f"community={sanitize_label(str(d.get('community', '')))}]"
f"community={sanitize_label(str(d.get('community_name') or d.get('community', '')))}]"
)
lines.append(line)
for u, v in edges:
@@ -237,7 +408,16 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
lines.append(line)
output = "\n".join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f"\n... (truncated to ~{token_budget} token budget)"
cut_at = output[:char_budget].rfind("\n")
cut_at = cut_at if cut_at > 0 else char_budget
total_nodes = sum(1 for l in lines if l.startswith("NODE "))
shown_nodes = output[:cut_at].count("\nNODE ") + (1 if output.startswith("NODE ") else 0)
cut_count = total_nodes - shown_nodes
output = (
output[:cut_at]
+ f"\n... (truncated — {cut_count} more nodes cut by ~{token_budget}-token budget."
f" Narrow with context_filter=['call'] or use get_node for a specific symbol)"
)
return output
@@ -250,9 +430,9 @@ def _query_graph_text(
token_budget: int = 2000,
context_filters: list[str] | None = None,
) -> str:
terms = [t.lower() for t in question.split() if len(t) > 2]
terms = _query_terms(question)
scored = _score_nodes(G, terms)
start_nodes = [nid for _, nid in scored[:3]]
start_nodes = _pick_seeds(scored)
if not start_nodes:
return "No matching nodes found."
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
@@ -275,19 +455,27 @@ def _find_node(G: nx.Graph, label: str) -> list[str]:
Results are ordered by three-tier precedence: exact match, then prefix match,
then substring match. Node-ID exact matches are grouped with label exact matches.
"""
term = _strip_diacritics(label).lower()
term = " ".join(_search_tokens(label))
if not term:
return []
exact: list[str] = []
prefix: list[str] = []
substring: list[str] = []
for nid, d in G.nodes(data=True):
norm_label = d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower()
bare_label = norm_label.rstrip("()")
label_tokens = " ".join(_search_tokens(d.get("label") or ""))
nid_lower = nid.lower()
if term == norm_label or term == bare_label or term == nid_lower:
if term == norm_label or term == bare_label or term == label_tokens or term == nid_lower:
exact.append(nid)
elif norm_label.startswith(term) or bare_label.startswith(term) or nid_lower.startswith(term):
elif (
norm_label.startswith(term)
or bare_label.startswith(term)
or label_tokens.startswith(term)
or nid_lower.startswith(term)
):
prefix.append(nid)
elif term in norm_label:
elif term in norm_label or term in label_tokens:
substring.append(nid)
return exact + prefix + substring
@@ -322,19 +510,61 @@ def _filter_blank_stdin() -> None:
sys.stdin = open(0, "r", closefd=False)
def serve(graph_path: str = "graphify-out/graph.json") -> None:
"""Start the MCP server. Requires pip install mcp."""
def _build_server(graph_path: str):
"""Build the configured low-level MCP Server (shared by every transport).
All graph query tools and resources are registered here over a single
``mcp.server.Server`` instance; the caller picks the transport (stdio or
Streamable HTTP) and runs it. Hot-reload of graph.json works the same way
regardless of transport, since reloads happen inside the tool handlers.
"""
import threading
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
from mcp.types import AnyUrl
except ImportError as e:
raise ImportError("mcp not installed. Run: pip install mcp") from e
raise ImportError('mcp not installed. Run: pip install "graphifyy[mcp]"') from e
G = _load_graph(graph_path)
communities = _communities_from_graph(G)
# Hot-reload state: mtime+size key lets us detect graph.json changes without
# polling. Initialised from the file stat at startup so the first tool call
# never triggers a redundant reload.
_reload_lock = threading.Lock()
try:
_s = Path(graph_path).stat()
_reload_state: dict = {"mtime_ns": _s.st_mtime_ns, "size": _s.st_size}
except FileNotFoundError:
_reload_state = {"mtime_ns": 0, "size": -1}
def _maybe_reload() -> None:
nonlocal G, communities
try:
s = Path(graph_path).stat()
key = (s.st_mtime_ns, s.st_size)
except FileNotFoundError:
return
if key == (_reload_state["mtime_ns"], _reload_state["size"]):
return
with _reload_lock:
try:
s = Path(graph_path).stat()
key = (s.st_mtime_ns, s.st_size)
except FileNotFoundError:
return
if key == (_reload_state["mtime_ns"], _reload_state["size"]):
return # another thread already reloaded
try:
new_G = _load_graph(graph_path)
except SystemExit:
return # keep serving stale graph on transient read error
G = new_G
communities = _communities_from_graph(new_G)
_reload_state["mtime_ns"], _reload_state["size"] = key
server = Server("graphify")
@server.list_tools()
@@ -413,15 +643,64 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
"required": ["source", "target"],
},
),
types.Tool(
name="list_prs",
description=(
"List open GitHub PRs with CI status, review state, and graph impact "
"(which communities each PR touches, blast radius). Use this before starting "
"work to check if a PR already covers the area you're about to change."
),
inputSchema={
"type": "object",
"properties": {
"base": {"type": "string", "description": "Base branch to filter PRs by (auto-detected if omitted)"},
"repo": {"type": "string", "description": "GitHub repo (owner/repo). Defaults to current repo."},
},
},
),
types.Tool(
name="get_pr_impact",
description=(
"Get detailed graph impact for a specific PR: which files it changes, "
"which knowledge-graph communities are affected, and how many nodes are touched. "
"Use this to assess merge risk or check for overlap with your current work."
),
inputSchema={
"type": "object",
"properties": {
"pr_number": {"type": "integer", "description": "PR number to analyse"},
"repo": {"type": "string", "description": "GitHub repo (owner/repo). Defaults to current repo."},
},
"required": ["pr_number"],
},
),
types.Tool(
name="triage_prs",
description=(
"Return all actionable open PRs (correct base, not stale) with full graph impact data "
"so you can reason about review priority, merge order, and conflict risk. "
"Call this when the user asks 'what PRs should I review?' or 'what's ready to merge?'"
),
inputSchema={
"type": "object",
"properties": {
"base": {"type": "string", "description": "Base branch to filter PRs by (auto-detected if omitted)"},
"repo": {"type": "string", "description": "GitHub repo (owner/repo). Defaults to current repo."},
},
},
),
]
def _tool_query_graph(arguments: dict) -> str:
import time as _time
from graphify import querylog
question = arguments["question"]
mode = arguments.get("mode", "bfs")
depth = min(int(arguments.get("depth", 3)), 6)
budget = int(arguments.get("token_budget", 2000))
context_filter = arguments.get("context_filter")
return _query_graph_text(
_t0 = _time.perf_counter()
result = _query_graph_text(
G,
question,
mode=mode,
@@ -429,6 +708,17 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
token_budget=budget,
context_filters=context_filter,
)
querylog.log_query(
kind="mcp_query",
question=question,
corpus=str(graph_path),
result=result,
mode=mode,
depth=depth,
token_budget=budget,
duration_ms=(_time.perf_counter() - _t0) * 1000,
)
return result
def _tool_get_node(arguments: dict) -> str:
label = arguments["label"].lower()
@@ -443,7 +733,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
f" ID: {sanitize_label(nid)}",
f" Source: {sanitize_label(str(d.get('source_file', '')))} {sanitize_label(str(d.get('source_location', '')))}",
f" Type: {sanitize_label(str(d.get('file_type', '')))}",
f" Community: {sanitize_label(str(d.get('community', '')))}",
f" Community: {sanitize_label(str(d.get('community_name') or d.get('community', '')))}",
f" Degree: {G.degree(nid)}",
])
@@ -491,7 +781,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
return "\n".join(lines)
def _tool_god_nodes(arguments: dict) -> str:
from .analyze import god_nodes as _god_nodes
from graphify.analyze import god_nodes as _god_nodes
nodes = _god_nodes(G, top_n=int(arguments.get("top_n", 10)))
lines = ["God nodes (most connected):"]
lines += [f" {i}. {n['label']} - {n['degree']} edges" for i, n in enumerate(nodes, 1)]
@@ -564,6 +854,91 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
prefix = ("\n".join(warnings) + "\n") if warnings else ""
return prefix + f"Shortest path ({hops} hops):\n " + " ".join(segments)
def _tool_list_prs(arguments: dict) -> str:
from graphify.prs import fetch_prs, fetch_worktrees, format_prs_text, _detect_default_branch
repo = arguments.get("repo") or None
base = arguments.get("base") or _detect_default_branch(repo)
try:
prs = fetch_prs(repo=repo, base=base)
except RuntimeError as e:
return f"Error: {e}"
worktrees = fetch_worktrees()
for pr in prs:
pr.worktree_path = worktrees.get(pr.branch)
return format_prs_text(prs, base)
def _tool_get_pr_impact(arguments: dict) -> str:
from graphify.prs import fetch_pr_files, compute_pr_impact, _gh, _parse_ci
number = int(arguments["pr_number"])
repo = arguments.get("repo") or None
# Use gh pr view directly — works for any base branch, not just the default
view_args = ["pr", "view", str(number), "--json",
"title,headRefName,baseRefName,author,isDraft,reviewDecision,statusCheckRollup,updatedAt"]
if repo:
view_args += ["--repo", repo]
pr_data = _gh(*view_args)
if pr_data is None:
return f"PR #{number} not found or gh not authenticated."
files = fetch_pr_files(number, repo)
if not files:
return f"PR #{number}: no changed files found (may require gh auth)."
comms, nodes = compute_pr_impact(files, G)
ci = _parse_ci(pr_data.get("statusCheckRollup") or [])
lines = [
f"PR #{number}: {pr_data['title']}",
f"CI: {ci} Review: {pr_data.get('reviewDecision') or 'none'}",
f"Base: {pr_data['baseRefName']} Author: {(pr_data.get('author') or {}).get('login', '?')}",
f"\nGraph impact: {nodes} nodes across {len(comms)} communities",
f"Communities touched: {comms}",
f"Files changed ({len(files)}):",
]
lines += [f" {f}" for f in files[:20]]
if len(files) > 20:
lines.append(f" … and {len(files) - 20} more")
return "\n".join(lines)
def _tool_triage_prs(arguments: dict) -> str:
from concurrent.futures import ThreadPoolExecutor, as_completed
from graphify.prs import fetch_prs, fetch_worktrees, fetch_pr_files, compute_pr_impact, _STATUS_ORDER, _detect_default_branch
repo = arguments.get("repo") or None
base = arguments.get("base") or _detect_default_branch(repo)
try:
prs = fetch_prs(repo=repo, base=base)
except RuntimeError as e:
return f"Error: {e}"
worktrees = fetch_worktrees()
for pr in prs:
pr.worktree_path = worktrees.get(pr.branch)
actionable = [p for p in prs if p.base_branch == base and p.status not in ("WRONG-BASE", "STALE")]
if not actionable:
return f"No actionable PRs targeting {base}."
# Fetch diffs concurrently then compute graph impact using in-memory G
workers = min(8, len(actionable))
with ThreadPoolExecutor(max_workers=workers) as pool:
future_to_pr = {pool.submit(fetch_pr_files, pr.number, repo): pr for pr in actionable}
for fut in as_completed(future_to_pr):
pr = future_to_pr[fut]
try:
files = fut.result()
except Exception:
files = []
if files:
pr.files_changed = files
pr.communities_touched, pr.nodes_affected = compute_pr_impact(files, G)
header = (
f"Actionable PRs targeting {base}: {len(actionable)}\n"
"Rank these by review priority. Higher blast_radius = more graph communities affected = higher merge risk.\n"
)
lines = [header]
for p in sorted(actionable, key=lambda x: (_STATUS_ORDER.index(x.status) if x.status in _STATUS_ORDER else 99)):
impact = f" blast_radius={p.blast_radius}" if p.blast_radius else ""
wt = f" worktree={p.worktree_path}" if p.worktree_path else ""
lines.append(
f"PR #{p.number} [{p.status}] CI={p.ci_status} review={p.review_decision or 'none'} "
f"age={p.days_old}d author={p.author}{impact}{wt}\n title: {p.title}"
)
return "\n\n".join(lines)
_handlers = {
"query_graph": _tool_query_graph,
"get_node": _tool_get_node,
@@ -572,6 +947,9 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
"god_nodes": _tool_god_nodes,
"graph_stats": _tool_graph_stats,
"shortest_path": _tool_shortest_path,
"list_prs": _tool_list_prs,
"get_pr_impact": _tool_get_pr_impact,
"triage_prs": _tool_triage_prs,
}
def _load_community_labels() -> dict[int, str]:
@@ -596,6 +974,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
@server.read_resource()
async def read_resource(uri: AnyUrl) -> str:
_maybe_reload()
uri_str = str(uri)
if uri_str == "graphify://report":
report_path = Path(graph_path).parent / "GRAPH_REPORT.md"
@@ -647,6 +1026,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
_maybe_reload()
handler = _handlers.get(name)
if not handler:
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
@@ -655,8 +1035,19 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
except Exception as exc:
return [types.TextContent(type="text", text=f"Error executing {name}: {exc}")]
return server
def serve(graph_path: str = "graphify-out/graph.json") -> None:
"""Start the MCP server over stdio (the default, per-developer transport)."""
try:
from mcp.server.stdio import stdio_server
except ImportError as e:
raise ImportError('mcp not installed. Run: pip install "graphifyy[mcp]"') from e
import asyncio
server = _build_server(graph_path)
async def main() -> None:
async with stdio_server() as streams:
await server.run(streams[0], streams[1], server.create_initialization_options())
@@ -665,6 +1056,270 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
asyncio.run(main())
class _MCPASGIApp:
"""Raw-ASGI wrapper around the Streamable HTTP session manager.
Passed to a Starlette ``Route`` as a class instance (not a function) so
Starlette treats it as an ASGI app: it serves the exact mount path for all
methods (GET/POST/DELETE) with no request/response wrapping and no
trailing-slash redirect — mirroring how FastMCP mounts the same manager.
"""
def __init__(self, manager) -> None:
self._manager = manager
async def __call__(self, scope, receive, send) -> None:
await self._manager.handle_request(scope, receive, send)
class _ApiKeyMiddleware:
"""Pure-ASGI API-key gate for the HTTP transport.
Implemented as raw ASGI (not Starlette's BaseHTTPMiddleware) on purpose:
BaseHTTPMiddleware buffers responses and breaks the Streamable HTTP SSE
stream. This short-circuits with 401 before the request ever reaches the
session manager, leaving the streaming path untouched for authorized calls.
"""
def __init__(self, app, api_key: str) -> None:
self.app = app
self._expected = api_key.encode("utf-8")
async def __call__(self, scope, receive, send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
import hmac
headers = dict(scope.get("headers") or [])
provided = headers.get(b"x-api-key")
if provided is None:
# RFC 6750: the auth scheme token is case-insensitive.
scheme, _, token = headers.get(b"authorization", b"").partition(b" ")
if scheme.lower() == b"bearer" and token:
provided = token.strip()
# Constant-time compare; reject when no key was supplied at all.
if provided is None or not hmac.compare_digest(provided, self._expected):
body = b'{"error": "unauthorized"}'
await send({
"type": "http.response.start",
"status": 401,
"headers": [
(b"content-type", b"application/json"),
(b"content-length", str(len(body)).encode("ascii")),
],
})
await send({"type": "http.response.body", "body": body})
return
await self.app(scope, receive, send)
def _build_http_app(
graph_path: str,
*,
host: str = "127.0.0.1",
port: int = 8080,
api_key: str | None = None,
path: str = "/mcp",
json_response: bool = False,
stateless: bool = False,
session_timeout: float | None = 3600.0,
):
"""Build the Starlette ASGI app for the Streamable HTTP transport.
Split out from :func:`serve_http` (which blocks on uvicorn) so the wiring
can be exercised with an in-process ASGI test client.
``session_timeout`` reaps stateful sessions idle for that many seconds so a
long-running shared server does not leak memory when IDE clients disconnect
without sending a DELETE. ``None`` (or <= 0) disables reaping; it is forced
to ``None`` in stateless mode, which has no sessions to reap.
"""
try:
import contextlib
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.routing import Route
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.server.transport_security import TransportSecuritySettings
except ImportError as e:
raise ImportError(
'HTTP transport needs the mcp extra (mcp + starlette + uvicorn). '
'Run: pip install "graphifyy[mcp]"'
) from e
# A blank key (e.g. --api-key "" or an empty GRAPHIFY_API_KEY) must not be
# mistaken for "auth on" — normalize it to None so the gate is unambiguous.
api_key = (api_key or "").strip() or None
server = _build_server(graph_path)
# DNS-rebinding protection. When the operator binds a wildcard address they
# are intentionally exposing the server, so accept any Host header; for a
# loopback/specific bind, restrict Host to that address (with and without
# the port) plus the localhost aliases.
if host in ("0.0.0.0", "::", ""):
security = TransportSecuritySettings(enable_dns_rebinding_protection=False)
else:
allowed = {host, "localhost", "127.0.0.1"}
allowed |= {f"{h}:{port}" for h in list(allowed)}
security = TransportSecuritySettings(allowed_hosts=sorted(allowed))
# The SDK rejects a non-positive timeout and forbids one in stateless mode.
idle_timeout = None if (stateless or not session_timeout or session_timeout <= 0) else session_timeout
manager = StreamableHTTPSessionManager(
app=server,
json_response=json_response,
stateless=stateless,
security_settings=security,
session_idle_timeout=idle_timeout,
)
@contextlib.asynccontextmanager
async def lifespan(_app):
# The session manager owns an anyio task group that must wrap the whole
# server lifetime, so enter it here rather than per-request.
async with manager.run():
yield
middleware = []
if api_key:
middleware.append(Middleware(_ApiKeyMiddleware, api_key=api_key))
return Starlette(
routes=[Route(path, endpoint=_MCPASGIApp(manager))],
middleware=middleware,
lifespan=lifespan,
)
def serve_http(
graph_path: str = "graphify-out/graph.json",
*,
host: str = "127.0.0.1",
port: int = 8080,
api_key: str | None = None,
path: str = "/mcp",
json_response: bool = False,
stateless: bool = False,
session_timeout: float | None = 3600.0,
) -> None:
"""Start the MCP server over Streamable HTTP (MCP spec 2025-03-26).
Serves the same tools/resources as the stdio transport, so a single shared
process can host the graph for a whole team. Clients point their IDE MCP
config at ``http://<host>:<port><path>`` (default ``/mcp``).
``api_key`` (or the ``GRAPHIFY_API_KEY`` env var) enables a simple header
check (``Authorization: Bearer <key>`` or ``X-API-Key: <key>``). OAuth is a
deliberate follow-up. Binding ``0.0.0.0`` exposes the server beyond
localhost — set an api_key when you do.
"""
try:
import uvicorn
except ImportError as e:
raise ImportError(
'HTTP transport needs the mcp extra (mcp + starlette + uvicorn). '
'Run: pip install "graphifyy[mcp]"'
) from e
api_key = (api_key or "").strip() or None
app = _build_http_app(
graph_path,
host=host,
port=port,
api_key=api_key,
path=path,
json_response=json_response,
stateless=stateless,
session_timeout=session_timeout,
)
auth_note = "api-key required" if api_key else "no auth (set --api-key to require one)"
print(
f"graphify MCP server (streamable-http) on http://{host}:{port}{path} - {auth_note}",
file=sys.stderr,
)
if host in ("0.0.0.0", "::", "") and not api_key:
print(
f"WARNING: binding {host or '0.0.0.0'} with no api-key exposes the graph "
"unauthenticated on the network. Set --api-key (or GRAPHIFY_API_KEY).",
file=sys.stderr,
)
uvicorn.run(app, host=host, port=port)
def _main(argv: list[str] | None = None) -> None:
import argparse
import os
parser = argparse.ArgumentParser(
prog="python -m graphify.serve",
description="Serve a graphify knowledge graph over MCP (stdio or Streamable HTTP).",
)
parser.add_argument(
"graph_path",
nargs="?",
default=None,
help="Path to graph.json (default: graphify-out/graph.json)",
)
parser.add_argument(
"--graph",
dest="graph_flag",
default=None,
metavar="PATH",
help="Path to graph.json — alias for the positional argument",
)
parser.add_argument(
"--transport",
choices=["stdio", "http"],
default="stdio",
help="Transport to serve on (default: stdio)",
)
parser.add_argument("--host", default="127.0.0.1", help="HTTP bind host (default: 127.0.0.1)")
parser.add_argument("--port", type=int, default=8080, help="HTTP bind port (default: 8080)")
parser.add_argument(
"--api-key",
default=os.environ.get("GRAPHIFY_API_KEY"),
help="Require this key on the HTTP transport (env: GRAPHIFY_API_KEY)",
)
parser.add_argument("--path", default="/mcp", help="HTTP mount path (default: /mcp)")
parser.add_argument(
"--json-response",
action="store_true",
help="Return plain JSON responses instead of SSE streams",
)
parser.add_argument(
"--stateless",
action="store_true",
help="Run without per-session state (for load-balanced / CI deployments)",
)
parser.add_argument(
"--session-timeout",
type=float,
default=3600.0,
help="Reap stateful sessions idle this many seconds (default: 3600; 0 disables)",
)
args = parser.parse_args(argv)
graph_path = args.graph_flag or args.graph_path or "graphify-out/graph.json"
if args.transport == "http":
serve_http(
graph_path,
host=args.host,
port=args.port,
api_key=args.api_key,
path=args.path,
json_response=args.json_response,
stateless=args.stateless,
session_timeout=args.session_timeout,
)
else:
serve(graph_path)
if __name__ == "__main__":
graph_path = sys.argv[1] if len(sys.argv) > 1 else "graphify-out/graph.json"
serve(graph_path)
_main()
+85 -50
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
@@ -60,30 +59,47 @@ Follow these steps in order. Do not skip steps.
### Step 1 - Ensure graphify is installed
```bash
# Detect the correct Python interpreter (handles pipx, venv, system installs)
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
PYTHON=""
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$PYTHON" in
*[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;;
esac
else
PYTHON="python3"
# 1. uv tool installs — most reliable on modern Mac/Linux
if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
fi
"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
# 2. Read shebang from graphify binary (pipx and direct pip installs)
if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$_SHEBANG" in
*[!a-zA-Z0-9/_.-]*) ;;
*) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
esac
fi
# 3. Fall back to python3
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
if command -v uv >/dev/null 2>&1; then
uv tool install --upgrade graphifyy -q 2>&1 | tail -3
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
else
"$PYTHON" -m pip install graphifyy -q 2>/dev/null \
|| "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
fi
fi
# Write interpreter path for all subsequent steps (persists across invocations)
mkdir -p graphify-out
# Write interpreter path for all subsequent steps
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
@@ -170,7 +186,7 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
@@ -204,7 +220,7 @@ Print: `"Semantic extraction: N files (sequential — Aider)"`
Before dispatching any subagents, check which files already have cached extraction results:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
@@ -237,7 +253,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. 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.
- 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) and `file_type:"concept"` for named concepts. `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `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.
@@ -246,7 +262,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|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}
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|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|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`.
@@ -282,7 +298,7 @@ print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens'
Save new results to cache:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
@@ -295,7 +311,7 @@ print(f'Cached {saved} files')
Merge cached + new results into `.graphify_semantic.json`:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
@@ -328,7 +344,7 @@ Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphi
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from pathlib import Path
@@ -363,7 +379,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
```bash
mkdir -p graphify-out
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
@@ -416,7 +432,7 @@ Read `.graphify_analysis.json`. For each community key, look at its node labels
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
@@ -456,7 +472,7 @@ Replace INPUT_PATH with the actual path.
If `--obsidian` was given:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_obsidian, to_canvas
@@ -487,7 +503,7 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
Generate the HTML graph (always, unless `--no-viz`):
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_html
@@ -514,7 +530,7 @@ else:
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_cypher
@@ -529,7 +545,7 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster
@@ -551,7 +567,7 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
### Step 7b - SVG export (only if --svg flag)
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_svg
@@ -573,7 +589,7 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
### Step 7c - GraphML export (only if --graphml flag)
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.export import to_graphml
@@ -615,7 +631,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
@@ -633,7 +649,7 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
@@ -667,7 +683,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_chunk_*.json
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json; find . -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -707,7 +723,7 @@ The graph is the map. Your job after the pipeline is to be the guide.
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
@@ -716,17 +732,21 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
if new_total == 0:
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
print(f'{new_total} new/changed file(s) to re-extract.')
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
If new files exist, first check whether all changed files are code files:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
@@ -743,10 +763,25 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
@@ -773,7 +808,7 @@ Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
@@ -807,7 +842,7 @@ Clean up after: `rm -f .graphify_old.json`
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
@@ -860,7 +895,7 @@ Two traversal modes - choose based on the question:
First check the graph exists:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -878,7 +913,7 @@ Load `graphify-out/graph.json`, then:
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
@@ -969,7 +1004,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
After writing the answer, save it back into the graph so it improves future queries:
```bash
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
@@ -982,7 +1017,7 @@ Find the shortest path between two named concepts in the graph.
First check the graph exists:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -992,7 +1027,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1044,7 +1079,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
After writing the explanation, save it back:
```bash
$(cat .graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
---
@@ -1055,7 +1090,7 @@ Give a plain-language explanation of a single node - everything connected to it.
First check the graph exists:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -1065,7 +1100,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1110,7 +1145,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
After writing the explanation, save it back:
```bash
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```
---
@@ -1120,7 +1155,7 @@ $(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" -
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
+617
View File
@@ -0,0 +1,617 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory → 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)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
```
## What graphify is for
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 the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
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 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
```bash
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
PYTHON=""
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
# 1. uv tool installs — most reliable on modern Mac/Linux
if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
fi
# 2. Read shebang from graphify binary (pipx and direct pip installs)
if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$_SHEBANG" in
*[!a-zA-Z0-9/_.-]*) ;;
*) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
esac
fi
# 3. Fall back to python3
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
if command -v uv >/dev/null 2>&1; then
uv tool install --upgrade graphifyy -q 2>&1 | tail -3
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
else
"$PYTHON" -m pip install graphifyy -q 2>/dev/null \
|| "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
fi
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', encoding='utf-8').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.
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result, ensure_ascii=False))
" > graphify-out/.graphify_detect.json
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
**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** (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.
> **No other API keys are read.** If `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, fall straight through to Claude Code subagent dispatch (Part B below) — the host session itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key from the environment. If a host agent prompts the user for `ANTHROPIC_API_KEY` to run extraction, that prompt is a misread of this skill — ignore it and dispatch subagents as written.
**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.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files, cache_root=Path('.'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
print('No code files - skipping AST extraction')
"
```
#### Part B - Semantic extraction (parallel subagents)
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding=\"utf-8\")
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding=\"utf-8\")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
**Step B1 - Split into chunks**
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
**Step B2 - Dispatch ALL subagents in a single message**
> Uses the `Task` tool for parallel subagent dispatch.
> Call `Task` once per chunk — ALL in the same response so they run in parallel.
Pass the extraction prompt as the task description:
```
Task(description="Your task is to perform the following. Follow the instructions below exactly.\n\n<agent-instructions>\n[extraction prompt, with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]\n</agent-instructions>\n\nExecute this now. Output ONLY the structured JSON response.")
```
Each subagent writes its result to its own `graphify-out/.graphify_chunk_NN.json`. Collect results as each `Task` completes and parse each as JSON.
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
```bash
PROJECT_ROOT=$(cat graphify-out/.graphify_root)
# Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json"
```
Subagent prompt template:
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed 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(encoding=\"utf-8\"))
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, ensure_ascii=False), encoding=\"utf-8\")
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 "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
"
```
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`.
```bash
mkdir -p graphify-out
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
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,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
"
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
print('Report updated with community labels')
"
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```bash
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```bash
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
save_manifest(detect.get('all_files') or detect['files'])
# Update cumulative cost tracker
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text(encoding=\"utf-8\"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\")
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
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## Interpreter guard for subcommands
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
```bash
if [ ! -f graphify-out/.graphify_python ]; then
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$PYTHON" in *[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;; esac
else
PYTHON="python3"
fi
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
fi
```
## For --update and --cluster-only
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```bash
graphify query "<question>"
```
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify add and --watch
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For the commit hook and native AGENTS.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's AGENTS.md, see `references/hooks.md`.
---
## Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
+190 -780
View File
File diff suppressed because it is too large. Load diff
+164 -816
View File
File diff suppressed because it is too large. Load diff
+135 -813
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+168 -817
View File
File diff suppressed because it is too large. Load diff
+629
View File
@@ -0,0 +1,629 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory → 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)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
```
## What graphify is for
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 the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
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 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
```bash
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
PYTHON=""
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
# 1. uv tool installs — most reliable on modern Mac/Linux
if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
fi
# 2. Read shebang from graphify binary (pipx and direct pip installs)
if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$_SHEBANG" in
*[!a-zA-Z0-9/_.-]*) ;;
*) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
esac
fi
# 3. Fall back to python3
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
if command -v uv >/dev/null 2>&1; then
uv tool install --upgrade graphifyy -q 2>&1 | tail -3
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
else
"$PYTHON" -m pip install graphifyy -q 2>/dev/null \
|| "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
fi
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', encoding='utf-8').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.
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result, ensure_ascii=False))
" > graphify-out/.graphify_detect.json
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
**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** (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.
> **No other API keys are read.** If `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, fall straight through to Claude Code subagent dispatch (Part B below) — the host session itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key from the environment. If a host agent prompts the user for `ANTHROPIC_API_KEY` to run extraction, that prompt is a misread of this skill — ignore it and dispatch subagents as written.
**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.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files, cache_root=Path('.'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
print('No code files - skipping AST extraction')
"
```
#### Part B - Semantic extraction (parallel subagents)
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding=\"utf-8\")
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding=\"utf-8\")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
**Step B1 - Split into chunks**
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
**Step B2 - Dispatch ALL subagents in a single message**
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
Concrete example for 3 chunks:
```
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
```
All three in one message. Not three separate messages.
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
```bash
PROJECT_ROOT=$(cat graphify-out/.graphify_root)
# Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json"
```
Subagent prompt template:
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed 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(encoding=\"utf-8\"))
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, ensure_ascii=False), encoding=\"utf-8\")
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 "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
"
```
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`.
```bash
mkdir -p graphify-out
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
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,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
"
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
print('Report updated with community labels')
"
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```bash
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```bash
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
save_manifest(detect.get('all_files') or detect['files'])
# Update cumulative cost tracker
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text(encoding=\"utf-8\"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\")
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
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## Interpreter guard for subcommands
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
```bash
if [ ! -f graphify-out/.graphify_python ]; then
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$PYTHON" in *[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;; esac
else
PYTHON="python3"
fi
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
fi
```
## For --update and --cluster-only
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```bash
graphify query "<question>"
```
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify add and --watch
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For the commit hook and native CLAUDE.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
---
## Kilo-specific rules
- Use the native `Task` tool for semantic extraction fan-out.
- Launch all chunk tasks in the same response so they run in parallel.
- Always use `subagent_type="general"` for extraction chunks.
- After modifying code files during the session, run `graphify update .`.
---
## Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
+190 -779
View File
File diff suppressed because it is too large. Load diff
+144 -851
View File
File diff suppressed because it is too large. Load diff
+190 -779
View File
File diff suppressed because it is too large. Load diff
+179 -796
View File
File diff suppressed because it is too large. Load diff
+502 -144
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
@@ -11,248 +10,607 @@ Turn any folder of files into a navigable knowledge graph with community detecti
## Usage
```
/graphify # full pipeline on current directory
/graphify <path> # full pipeline on specific path
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --wiki # build agent-crawlable wiki
/graphify query "<question>" # BFS traversal - broad context
/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)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
```
## What graphify is for
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 the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
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.
**All commands use `python -c "..."` syntax — no bash heredocs, no shell redirects, no `&&`/`||`. This runs correctly on Windows PowerShell and macOS/Linux alike.**
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
```python
python -c "import graphify; import sys; from pathlib import Path; Path('graphify-out').mkdir(exist_ok=True); Path('graphify-out/.graphify_python').write_text(sys.executable)"
```bash
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
PYTHON=""
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
# 1. uv tool installs — most reliable on modern Mac/Linux
if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
fi
# 2. Read shebang from graphify binary (pipx and direct pip installs)
if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$_SHEBANG" in
*[!a-zA-Z0-9/_.-]*) ;;
*) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
esac
fi
# 3. Fall back to python3
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
if command -v uv >/dev/null 2>&1; then
uv tool install --upgrade graphifyy -q 2>&1 | tail -3
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
else
"$PYTHON" -m pip install graphifyy -q 2>/dev/null \
|| "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
fi
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', encoding='utf-8').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 fails, install first:
If the import succeeds, print nothing and move straight to Step 2.
```python
python -m pip install graphifyy -q
```
Then re-run the Step 1 command.
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```python
python -c "
import json, sys
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, indent=2))
total = result.get('total_files', 0)
words = result.get('total_words', 0)
print(f'Corpus: {total} files, ~{words} words')
for ftype, files in result.get('files', {}).items():
if files:
print(f' {ftype}: {len(files)} files')
"
print(json.dumps(result, ensure_ascii=False))
" > graphify-out/.graphify_detect.json
```
Replace `INPUT_PATH` with the actual path. Present a clean summary — do not dump the raw JSON.
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `total_words` > 2,000,000 OR `total_files` > 200: warn the user and ask which subfolder to run on.
- Otherwise: proceed to Step 3.
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
#### Part A - Structural extraction (AST, free, no API cost)
**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.
```python
python -c "
import json
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.
> **No other API keys are read.** If `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, fall straight through to Claude Code subagent dispatch (Part B below) — the host session itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key from the environment. If a host agent prompts the user for `ANTHROPIC_API_KEY` to run extraction, that prompt is a misread of this skill — ignore it and dispatch subagents as written.
**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.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
for f in detect.get('files', {}).get('code', []):
p = Path(f)
code_files.extend(collect_files(p) if p.is_dir() else [p])
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files)
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
result = extract(code_files, cache_root=Path('.'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
print('No code files - skipping AST extraction')
"
```
#### Part B - Semantic extraction (AI, costs tokens)
#### Part B - Semantic extraction (parallel subagents)
Skip if corpus is code-only (no docs, papers, or images).
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.
Check cache first:
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
```python
python -c "
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached))
print(f'Cache: {len(all_files)-len(uncached)} hit, {len(uncached)} need extraction')
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding=\"utf-8\")
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding=\"utf-8\")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
For each chunk of uncached files (20-25 files per chunk), dispatch a subagent with this prompt:
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON: {"nodes": [...], "edges": [...], "hyperedges": [...]}
**Step B1 - Split into chunks**
Each node: {"id": "unique_id", "label": "Human Name", "file_type": "code|document|paper|image"}
Each edge: {"source": "id", "target": "id", "relation": "verb_phrase", "confidence": "EXTRACTED|INFERRED|AMBIGUOUS"}
hyperedges: [] unless you find a genuine group relationship
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
Files:
FILE_LIST
**Step B2 - Dispatch subagents and paste their responses**
> **No automated subagent tool:** this host has no parallel Agent/Task API, so
> extraction is driven by hand. Dispatch a subagent per chunk however the host
> allows (a fresh conversation, a parallel pane), then paste each response back.
For each chunk of uncached files (20-25 per chunk), give a subagent the extraction prompt below. When it returns, paste its JSON response and write it to that chunk's file so Step B3 can collect it:
```bash
# After pasting a subagent's JSON for chunk N, save it (replace N and PASTED_JSON):
PROJECT_ROOT=$(cat graphify-out/.graphify_root)
cat > "${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json" <<'CHUNK_JSON'
PASTED_JSON
CHUNK_JSON
```
Collect all subagent responses and merge them:
Repeat for every chunk. Each chunk's JSON must land in its own `graphify-out/.graphify_chunk_NN.json` before Step B3 runs.
```python
python -c "
import json
Subagent prompt template:
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE substituted, and write its response to that chunk's file.
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed 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
# Merge: combine AST + cached + all semantic chunk results
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
all_nodes.extend(ast.get('nodes', []))
all_edges.extend(ast.get('edges', []))
cached_path = Path('graphify-out/.graphify_cached.json')
if cached_path.exists():
cached = json.loads(cached_path.read_text())
all_nodes.extend(cached.get('nodes', []))
all_edges.extend(cached.get('edges', []))
all_hyperedges.extend(cached.get('hyperedges', []))
# PASTE each subagent response here as chunk_1, chunk_2, etc.
total_in, total_out = 0, 0
for chunk_json in []: # replace [] with your chunk results
chunk = json.loads(chunk_json) if isinstance(chunk_json, str) else chunk_json
all_nodes.extend(chunk.get('nodes', []))
all_edges.extend(chunk.get('edges', []))
all_hyperedges.extend(chunk.get('hyperedges', []))
total_in += chunk.get('input_tokens', 0)
total_out += chunk.get('output_tokens', 0)
merged = {'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, 'input_tokens': total_in, 'output_tokens': total_out}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
print(f'Merged: {len(all_nodes)} nodes, {len(all_edges)} edges')
for c in chunks:
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
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, ensure_ascii=False), encoding=\"utf-8\")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
### Step 4 - Build graph and cluster
```python
python -c "
Save new results to cache:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.analyze import god_nodes, surprising_connections
from graphify.cache import save_semantic_cache
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
G = build_from_json(extraction)
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
"
```
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`.
```bash
mkdir -p graphify-out
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
import networkx as nx
from networkx.readwrite import json_graph
graph_data = json_graph.node_link_data(G)
Path('graphify-out/graph.json').write_text(json.dumps(graph_data, indent=2))
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps({
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
to_json(G, communities, 'graphify-out/graph.json')
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {},
'god_nodes': gods,
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
}, indent=2))
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
print(f'God nodes: {[g[\"label\"] for g in gods[:5]]}')
"
```
### Step 5 - Generate report and visualization
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
```python
python -c "
import json
Replace INPUT_PATH with the actual path.
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.analyze import god_nodes, surprising_connections
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
report = generate(G, communities, {}, {}, gods, surprises, extraction)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
print('GRAPH_REPORT.md written')
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
print('Report updated with community labels')
"
```
```python
python -c "
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```bash
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```bash
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.export import to_html
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
G = build_from_json(extraction)
communities = cluster(G)
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
save_manifest(detect.get('all_files') or detect['files'])
try:
to_html(G, communities, 'graphify-out/graph.html')
print('graph.html written')
except ValueError as e:
print(f'Visualization skipped: {e}')
# Update cumulative cost tracker
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text(encoding=\"utf-8\"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\")
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
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
### After completing all steps
Print this summary:
Tell the user (omit the obsidian line unless --obsidian was given):
```
graphify complete
graph.json — GraphRAG-ready, queryable by MCP or CLI
graph.html — interactive visualization (open in browser)
GRAPH_REPORT.md — plain-language architecture summary
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
Read `graphify-out/GRAPH_REPORT.md` and share the **God Nodes** and **Surprising Connections** sections directly in the chat — do not ask the user to open the file themselves.
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## Interpreter guard for subcommands
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
```bash
if [ ! -f graphify-out/.graphify_python ]; then
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$PYTHON" in *[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;; esac
else
PYTHON="python3"
fi
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
fi
```
## For --update and --cluster-only
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```bash
graphify query "<question>"
```
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify add and --watch
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For the commit hook and native CLAUDE.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
---
## Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
+219 -943
View File
File diff suppressed because it is too large. Load diff
+37 -484
View File
@@ -1,7 +1,6 @@
---
name: graphify
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
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
@@ -27,6 +26,8 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
@@ -49,34 +50,17 @@ Drop any folder of code, docs, papers, images, or video into graphify and get a
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
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)
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
**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.
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
@@ -148,53 +132,18 @@ Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `WHISPER_PROMPT` to use in the next command.
**Step 2 - Transcribe:**
```bash
GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths, ensure_ascii=False))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
@@ -303,70 +252,7 @@ PROJECT_ROOT=$(cat graphify-out/.graphify_root)
Subagent prompt template:
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. 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). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
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.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
- Two functions that both validate user input but never call each other
- A class in code and a concept in a paper that describe the same algorithm
- Two error types that handle the same failure mode differently
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
- All classes that implement a common protocol or interface
- All functions in an authentication flow (even if they don't all call each other)
- All concepts from a paper section that form one coherent idea
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- 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 `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. 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.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|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|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}
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
```
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
**Step B3 - Collect, cache, and merge**
@@ -499,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -509,7 +397,7 @@ labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
to_json(G, communities, 'graphify-out/graph.json')
@@ -552,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -563,7 +452,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, '.', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
print('Report updated with community labels')
@@ -593,73 +482,9 @@ 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)
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
graphify export wiki
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
graphify export neo4j
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
```
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
graphify export svg
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
graphify export graphml
```
### Step 7d - MCP server (only if --mcp flag)
```bash
python3 -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
To configure in Claude Desktop, add to `claude_desktop_config.json`:
```json
{
"mcpServers": {
"graphify": {
"command": "python3",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
}
```
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
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.
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
@@ -702,7 +527,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
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_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
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -755,306 +581,33 @@ if [ ! -f graphify-out/.graphify_python ]; then
fi
```
## For --update (incremental re-extraction)
## For --update and --cluster-only
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
'files': r.get('new_files', {}),
'all_files': r.get('files', {}),
'total_files': r.get('new_total', 0),
'total_words': r.get('total_words', 0),
'skipped_sensitive': r.get('skipped_sensitive', []),
'needs_graph': True,
}, ensure_ascii=False), encoding=\"utf-8\")
"
```
If new files exist, first check whether all changed files are code files:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').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','.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)
print('code_only:', code_only)
"
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
Then:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from graphify.build import build_merge
from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
deleted = list(incremental.get('deleted_files', []))
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=deleted or None,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
merged_out = {
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
'edges': [
# Explicit source/target last so they win over any stale attrs in d.
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
for u, v, d in G.edges(data=True)
],
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
# and new_extraction (build_merge combines them). Falling back to
# new_extraction only would silently drop prior-run hyperedges (#801).
'hyperedges': list(G.graph.get('hyperedges', [])),
'input_tokens': new_extraction.get('input_tokens', 0),
'output_tokens': new_extraction.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
# Save manifest so next --update diffs against today's state, not the
# prior run's baseline (prevents ghost-node reports on subsequent updates).
save_manifest(incremental['files'])
print('[graphify update] Manifest saved.')
"
```
Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
G_new = build_from_json(new_extract)
if old_data:
G_old = json_graph.node_link_graph(old_data, edges='links')
diff = graph_diff(G_old, G_new)
print(diff['summary'])
if diff['new_nodes']:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
Clean up after: `rm -f graphify-out/.graphify_old.json`
---
## For --cluster-only
Skip Steps 1–3. Re-run clustering on the existing graph:
```bash
graphify cluster-only .
```
Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
Two traversal modes - choose based on the question:
| Mode | Flag | Best for |
|------|------|----------|
| 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 |
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```bash
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
graphify query "<question>"
```
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:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify path
## For /graphify add and --watch
Find the shortest path between two named concepts in the graph.
```bash
graphify path "NODE_A" "NODE_B"
```
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:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For /graphify explain
## For the commit hook and native CLAUDE.md integration
Give a plain-language explanation of a single node - everything connected to it.
```bash
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.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```
---
## For /graphify add
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
try:
out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
print(f'Saved to {out}')
except ValueError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
"
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
Supported URL types (auto-detected):
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Any webpage → converted to markdown via html2text
---
## For --watch
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```bash
python3 -m graphify.watch INPUT_PATH --debounce 3
```
Replace INPUT_PATH with the folder to watch. Behavior depends on what changed:
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
Press Ctrl+C to stop.
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.
---
## For git commit hook
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
```bash
graphify hook install # install
graphify hook uninstall # remove
graphify hook status # check
```
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
If a post-commit hook already exists, graphify appends to it rather than replacing it.
---
## For native CLAUDE.md integration
Run once per project to make graphify always-on in Claude Code sessions:
```bash
graphify claude install
```
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
```bash
graphify claude uninstall # remove the section
```
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
---
@@ -0,0 +1,56 @@
# graphify reference: add a URL and watch a folder
Load this when the user ran `/graphify add <url>` or passed `--watch`. Neither is part of the default build.
## For /graphify add
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
try:
out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
print(f'Saved to {out}')
except ValueError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
"
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
Supported URL types (auto-detected):
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Any webpage → converted to markdown via html2text
---
## For --watch
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```bash
python3 -m graphify.watch INPUT_PATH --debounce 3
```
Replace INPUT_PATH with the folder to watch. Behavior depends on what changed:
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
Press Ctrl+C to stop.
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.
+87
View File
@@ -0,0 +1,87 @@
# graphify reference: extra exports and benchmark
Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag.
### Step 6b - Wiki (only if --wiki flag)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
graphify export wiki
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
graphify export neo4j
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
```
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag)
**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact:
```bash
graphify export falkordb
```
**If `--falkordb-push <uri>`** - push directly to a running FalkorDB instance. Credentials are optional; ask the user only if the instance requires auth:
```bash
graphify export falkordb --push falkordb://localhost:6379
```
Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7b - SVG export (only if --svg flag)
```bash
graphify export svg
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
graphify export graphml
```
### Step 7d - MCP server (only if --mcp flag)
```bash
python3 -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
To configure in Claude Desktop, add to `claude_desktop_config.json`:
```json
{
"mcpServers": {
"graphify": {
"command": "python3",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
}
```
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
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.
@@ -0,0 +1,70 @@
# graphify reference: extraction subagent prompt
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. 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). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
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. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
- Two functions that both validate user input but never call each other
- A class in code and a concept in a paper that describe the same algorithm
- Two error types that handle the same failure mode differently
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
- All classes that implement a common protocol or interface
- All functions in an authentication flow (even if they don't all call each other)
- All concepts from a paper section that form one coherent idea
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- 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 `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. 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.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","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":"<FILE_LIST path verbatim>","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":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
```
@@ -0,0 +1,46 @@
# graphify reference: GitHub clone and cross-repo merge
Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph.
### 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.
**Multiple local subfolders (monorepo or multi-service layout):**
The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path:
```bash
graphify extract ./core/ # → ./core/graphify-out/graph.json
graphify extract ./service/ # → ./service/graphify-out/graph.json
graphify extract ./platform/ # → ./platform/graphify-out/graph.json
# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set
# Then merge at the project root:
graphify merge-graphs \
./core/graphify-out/graph.json \
./service/graphify-out/graph.json \
./platform/graphify-out/graph.json \
--out graphify-out/graph.json
```
Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate.
+33
View File
@@ -0,0 +1,33 @@
# graphify reference: commit hook and native AGENTS.md integration
Load this when the user asked to install the post-commit hook or wire graphify into a project's AGENTS.md.
## For git commit hook
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
```bash
graphify hook install # install
graphify hook uninstall # remove
graphify hook status # check
```
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
If a post-commit hook already exists, graphify appends to it rather than replacing it.
---
## For native AGENTS.md integration
Run once per project to make graphify always-on in Amp sessions:
```bash
graphify amp install
```
This writes a `## graphify` section to the local `AGENTS.md` that instructs Amp to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
```bash
graphify amp uninstall # remove the section
```
Loaded 100 of 485 files, more files were not shown because too many files have changed in this diff. Show more