Compare commits

...
Author SHA1 Message Date
Safi 8d3457130a Merge origin/v8 into pr-1136 — resolve codex .codex path + version bump 2026-06-07 14:32:01 +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
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
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
DevinZeng 5d24fef4bf fix: align codebuddy install with claude install logic
codebuddy_install now uses _always_on('claude-md') instead of hardcoded
_CODEBUDDY_MD_SECTION, so CODEBUDDY.md content matches CLAUDE.md.
2026-06-06 12:11:12 +08:00
DevinZeng 2c32a4ef3c Address PR feedback: Add PreToolUse hook, uninstall handler, idempotency, and tests 2026-06-06 10:19:50 +08:00
DevinZeng 2a102bc75b Merge official v8 (v0.8.32) with CodeBuddy support 2026-06-06 09:58:11 +08: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
DevinZeng c299f31032 Add CodeBuddy platform support
CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as
Claude Code. Installs skill to ~/.codebuddy/skills/, writes CODEBUDDY.md
section, and registers a Glob|Grep PreToolUse hook in
.codebuddy/settings.json.
2026-06-05 19:15:09 +08: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
SafiandClaude Sonnet 4.6 7c561e6f82 Skip coverage/visual-test/snapshot/storybook-static noise dirs in detect (#869, #870)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:51:39 +01:00
SafiandClaude Sonnet 4.6 4e7648b4e2 fix #865: use git rev-parse --git-path hooks so hook install works in linked worktrees
In a linked worktree .git is a file not a directory, so root/.git/hooks
fails with NotADirectoryError. Fall back to git rev-parse --path-format=absolute
--git-path hooks which resolves the correct hooks dir from any worktree.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:37:05 +01:00
SafiandClaude Sonnet 4.6 972fdc1b87 fix #862 #861 #857: skill-windows.md path prefix, sidecar graphifyignore bypass, manifest ast/semantic split
- skill-windows.md: add graphify-out/ prefix to 5 paths in Step B3 that
  were being read/written without prefix (lines 244,245,373,387,388,407,413)
  causing semantic cache to always appear empty on Windows (#862)
- detect.py: gate converted office/Google Workspace sidecar paths through
  _is_ignored() before appending to files list so .graphifyignore rules
  apply to graphify-out/converted/ sidecars (#861)
- detect.py: split manifest entries from {mtime,hash} to
  {mtime,ast_hash,semantic_hash}; save_manifest() accepts kind="ast"|
  "semantic"|"both"; detect_incremental() accepts kind= and checks the
  right hash field so graphify update (kind=ast) no longer prevents
  graphify extract from re-running semantic extraction (#857)
- watch.py: all three save_manifest() calls use kind="ast" (AST-only rebuild)
- __main__.py: both extract save_manifest() calls use kind="both"
- backwards compatible: legacy {mtime,hash} entries treated as ast_hash only

775 tests passing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:31:14 +01:00
Safi a9b0ddbb86 add .astro to supported extensions in README 2026-05-14 11:48:59 +01:00
Safi 3baedc5bdb bump version to 0.7.19 2026-05-14 11:43:28 +01:00
Safiandvoidborne-d cfe18ea947 fix(watch): unlink .rebuild.lock on release, rewrite single PID line (PR #859, voidborne-d)
Co-Authored-By: voidborne-d <voidborne-d@users.noreply.github.com>
2026-05-14 10:49:10 +01:00
Safiandspindle79 fcafec7081 feat(extract): add .astro support (#850, PR #852, spindle79)
Co-Authored-By: spindle79 <spindle79@users.noreply.github.com>
2026-05-14 10:49:02 +01:00
SafiandJstottlemyer 6c78a74776 docs(skill): clarify no provider API key is read for semantic extraction (PR #864, Jstottlemyer)
Co-Authored-By: Jstottlemyer <Jstottlemyer@users.noreply.github.com>
2026-05-14 10:48:57 +01:00
Justin Stottlemyer a08f0de53b docs(skill): clarify that no provider API key is read for semantic extraction
Several host agents (Claude Code in particular) misread the current
phrasing and prompt the user for `ANTHROPIC_API_KEY` when no Gemini
key is set, instead of falling through to subagent dispatch. The
Gemini tip stays as-is; this just adds an explicit one-line callout
that no other provider keys are consulted, with `ANTHROPIC_API_KEY`
called out by name since that is the specific misread we hit in the
wild.

No behavior change — pure documentation.
2026-05-13 23:29:02 -07:00
voidborne-dandClaude Opus 4.7 2c975ee9fb fix(watch): unlink .rebuild.lock on release and rewrite single PID line (#858)
The rebuild lock file accumulated concatenated PIDs across post-commit
rebuilds without a separator, and was never removed when the rebuild
finished. Two practical consequences for users:

1. Downstream tooling that polls for `.rebuild.lock` to disappear before
   doing post-rebuild work (publish scripts copying graph.html to a web
   root, etc.) blocked forever / until its own timeout.
2. The accumulated digit string could not be parsed by humans or tooling
   to find the owning PID.

The `_rebuild_lock` context manager now:

- Opens the lock file with `a+` so a non-acquiring caller does not
  truncate the existing holder's PID.
- After flock acquisition, truncates and writes a single `<pid>\n` line
  so external readers can `kill -0 $(cat .rebuild.lock)` to check
  liveness.
- Unlinks the lock file in the finally block (only when *we* held the
  lock), restoring the "signal-by-absence" convention users rely on.

Four regression tests added under `tests/test_watch.py` covering the
PID-with-newline payload, post-release unlink, no-accumulation across
sequential acquisitions, and the non-blocking-caller-does-not-clobber
invariant.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 08:05:55 +08:00
Safi 77bb10c682 document --force for extract and ghost-duplicate cleanup in README 2026-05-14 00:59:58 +01:00
Safi b7e7ae5ad6 bump version to 0.7.18 2026-05-14 00:57:47 +01:00
Safi 7c68c84fac update README and CHANGELOG for v0.7.18 2026-05-14 00:37:47 +01:00
Safi f7c9a9ad82 fix watch.py labels churn, edges/links schema, shrink-check duplication, and skill.md ID edge cases 2026-05-14 00:29:54 +01:00
Safi 7d1c1096bc fix node ID format in skill.md: parent_dir+stem, not filename-only (fixes ghost-duplicate root cause from #807) 2026-05-14 00:12:04 +01:00
SafiandFatahChan 1b8b76816e fix: deterministic clustering, topology short-circuit on unchanged graph, --no-cluster for update (PR #824, FatahChan)
Co-Authored-By: FatahChan <FatahChan@users.noreply.github.com>
2026-05-14 00:11:41 +01:00
Safiandsachinampity ddb98226df docs: add prerequisites, extras table, env vars, troubleshooting, dev setup (PR #833, sachinampity)
Co-Authored-By: sachinampity <sachinampity@users.noreply.github.com>
2026-05-14 00:11:15 +01:00
Safi 76833f0281 document --backend claude-cli in README 2026-05-14 00:04:50 +01:00
258d2600cd feat: add --backend claude-cli (routes through Claude Code, no API key needed) (#855)
Co-Authored-By: spindle79 <spindle79@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:53:00 +01:00
SafiandClaude Sonnet 4.6 c4c2205658 bump version to 0.7.17
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:45:33 +01:00
53da14333e rename sample.F90 → sample_preprocessed.F90 to fix macOS case-collision
Co-Authored-By: FatahChan <FatahChan@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:39:01 +01:00
SafiandClaude Sonnet 4.6 822abd6e69 fix --update manifest shrink and align file_type enum (#837, #840)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:22:37 +01:00
Safi 7bb0919c72 fix path/explain arrow direction and bedrock CLI guard (#846, #849, #853) 2026-05-13 23:19:15 +01:00
SafiandClaude Sonnet 4.6 d0e09aa89d fix MCP tool arrow direction and hub-transit BFS (#830, #849, #853)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:18:52 +01:00
Adam Harris c0048d0a61 feat(extract): add .astro support (#850)
Astro files have a `---...---` TypeScript frontmatter block at the top
containing nearly all imports, followed by an HTML-with-expressions
template body, and optionally `<script>` blocks for client-side JS.
Feeding the whole file to the JS tree-sitter parser produces a top-level
ERROR node because the template isn't valid JS, so `import_statement`
nodes are never reached.

Mirrors `extract_svelte` (#713) — same regex-rescue strategy:

- Dynamic `import('...')` pass over the full source.
- Static `import X from '...'` pass over the frontmatter block plus any
  `<script>` blocks.

Both static and dynamic imports honor tsconfig.json path aliases and
resolve relative paths through `_resolve_js_module_path` so node ids
match the targets that `_extract_generic` produces for sibling files.

Wired in:
- `detect.py:27` — `.astro` added to `CODE_EXTENSIONS`.
- `extract.py:5492` — `".astro": extract_astro` in the dispatch table.

Tests in `tests/test_astro_extraction.py` cover: extension registration,
frontmatter static imports, dynamic import in frontmatter, client-side
`<script>` block imports, frontmatter-less pages (must not crash), and
tsconfig.json path-alias resolution.
2026-05-13 10:07:50 -07:00
SafiandClaude Sonnet 4.6 5f9ea2b80e document graphify --version in CLI reference
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 14:53:22 +01:00
SafiandClaude Sonnet 4.6 ab32098063 bump version to 0.7.16
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 14:44:23 +01:00
SafiandClaude Sonnet 4.6 994b17be46 fix #832 #831 #828 #826 #827: encoding, uv fallback, path scoring, cache, OpenCode trigger
- skill.md + skill-windows.md: add encoding="utf-8" to all read_text()/write_text()
  calls and ensure_ascii=False to json.dumps — bare calls defaulted to system
  codepage on Chinese-locale Windows, mojibaking non-ASCII content (#832)
- skill.md + skill-windows.md: prefer uv tool install --upgrade graphifyy over
  pip in the Step 1 install fallback — pip installs to the wrong env when
  graphify was installed via uv tool (#831)
- serve.py + __main__.py: replace flat substring scoring in _score_nodes with
  three-tier precedence (exact 1000 / prefix 100 / substring 1); _find_node
  returns results ordered exact→prefix→substring; both path CLI and MCP now
  emit a clear error when src and tgt resolve to the same node (#828)
- cache.py: normalize path key via .as_posix().lower() in file_hash so Windows
  junction/case variants hash identically; mirror abs-path normalization from
  save_semantic_cache into check_semantic_cache so relative source_file paths
  resolve the same way on both sides (#826)
- __main__.py: add /graphify skill trigger line to _AGENTS_MD_SECTION — affects
  all 7 AGENTS.md platforms (OpenCode, Codex, Aider, Trae, Hermes, Claw, Droid)
  so typing /graphify actually invokes the skill tool (#827)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 12:11:03 +01:00
sachinampityandClaude Sonnet 4.6 2db5d966f2 docs: comprehensive README overhaul with prerequisites, extras, env vars, troubleshooting, dev setup
Added sections:
- Prerequisites — Python 3.10+ requirement with per-OS install commands (Homebrew, winget, apt)
- Optional extras table — all graphifyy[...] extras with what each adds and install command
- Environment variables — consolidated reference for all GRAPHIFY_* vars and API keys
  needed for headless/CI extraction (ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY,
  MOONSHOT_API_KEY, OLLAMA_BASE_URL/MODEL, GRAPHIFY_MAX_WORKERS, etc.)
- Troubleshooting — 8 common issues with exact fix commands (PATH, PowerShell slash,
  Ollama VRAM, graph.json merge conflicts, empty extraction, version mismatch)
- Development setup (inside Contributing) — editable install steps, venv creation,
  pytest instructions, git workflow, macOS case-sensitive fixture note

Preserved all existing content unchanged: logo, badges, star chart, translations,
platform install tables, full command reference, privacy section, Penpax section.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 14:25:52 +05:30
Ahmad FathallahandCursor 28fc71eddc skip reclustering when topology is unchanged
Add a pre-cluster topology comparison fast path in update rebuilds so unchanged graphs short-circuit before clustering and report generation, preventing residual run-to-run community-count drift.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 03:36:26 +03:00
Ahmad FathallahandCursor ef0e6ee681 harden community serialization fallbacks
Use safe JSON serialization fallbacks for deterministic sort keys in clustering and graph canonicalization, and skip invalid community IDs with a stderr warning instead of raising during update rebuilds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 02:37:38 +03:00
Ahmad FathallahandCursor 8e4c803f31 reduce graph update churn and stabilize community IDs
Make `graphify update` idempotent by skipping output rewrites when graph/report content is unchanged, add `update --no-cluster`, and preserve community IDs across runs via overlap-based remapping with deterministic partition inputs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 02:23:51 +03:00
SafiandClaude Sonnet 4.6 094d8ba731 fix #821 #818 #820: universal help guard, --version flag, Ollama num_ctx fallback
- Universal -h/--help/-? guard after cmd dispatch: any help flag anywhere in
  argv stops execution and prints "Run 'graphify --help'" instead of triggering
  the subcommand — cursor/kiro/gemini install --help no longer silently installs;
  benchmark --help no longer crashes with FileNotFoundError (#821)
- --version / -v / version subcommand: print graphify {__version__} and exit (#818)
- GRAPHIFY_OLLAMA_NUM_CTX=<invalid> now falls through to auto-derived num_ctx
  instead of hardcoding 131072 (the cap that causes OOM on constrained VRAM);
  pinned num_ctx < estimated input now triggers an explicit truncation warning
  with a suggested --token-budget correction (#820)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:18:48 +01:00
SafiandClaude Sonnet 4.6 dd465afd2c bump version to 0.7.14
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 18:49:16 +01:00
SafiandClaude Sonnet 4.6 95e2c5eb32 fix #811 #803 #801 #808: Unicode IDs, dedup edge keys, direction flip, chunk paths
- extract/_make_id + build/_normalize_id: use NFKC normalization and casefold
  so composed/decomposed Unicode forms produce the same ID; collapse consecutive
  underscores; both functions are now byte-for-byte equivalent (#811)
- dedup: use explicit key-presence check instead of `or` for source/from
  fallback; pop stale from/to keys so they don't leak into graph.json attrs (#803)
- skill --update: use build_merge() to avoid NetworkX round-trip direction flip;
  fix dict merge ordering so explicit source/target win; pull hyperedges from
  G.graph (merged) not new_extraction only (#801)
- skill subagents: inject absolute CHUNK_PATH so Write tool doesn't lose chunk
  files to undefined cwd (#808)
- __main__: skip skill version check during hook-check (runs on every editor
  tool use, must be silent); move warning to stderr

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 18:46:12 +01:00
Safi 4cec58e072 document GRAPHIFY_OLLAMA_NUM_CTX and GRAPHIFY_OLLAMA_KEEP_ALIVE env vars 2026-05-09 23:48:27 +01:00
Safi 9caaa17f7f bump version to 0.7.13 2026-05-09 23:45:43 +01:00
Safi 8c4c67f3ad fix Ollama num_ctx: derive from actual chunk size instead of hardcoding 131072 (#798) 2026-05-09 23:42:44 +01:00
Safi 5ead190891 wire callflow HTML into watch/hook rebuild: regenerates automatically if file exists 2026-05-09 23:29:43 +01:00
Porun db66b8727b feat: add callflow HTML export with Mermaid architecture diagrams 2026-05-09 23:26:01 +01:00
Safi 8c00287e84 fix Ollama context saturation: set num_ctx=131072, keep_alive=30m, serial by default (#798) 2026-05-09 22:51:36 +01:00
SafiandClaude Sonnet 4.6 e926079c0a bump version to 0.7.12, update README with new languages and extract flags
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 21:41:44 +01:00
SafiandClaude Sonnet 4.6 23f598f3a0 fix MultiGraph crash, hollow LLM response retry, and skill --help (#796, #795, #792)
#796: add edge_data()/edge_datas() helpers in build.py that tolerate
MultiGraph/MultiDiGraph; replace all G.edges[u,v] 2-tuple call sites in
__main__.py, serve.py, wiki.py, export.py, analyze.py, benchmark.py;
fix same pattern in 10 skill file inline heredocs

#795: all 12 skill files now short-circuit on /graphify --help or -h
and print the Usage block without running any pipeline steps

#792 (hollow response): add _response_is_hollow() predicate in llm.py;
when Ollama (or any backend) returns empty/null/whitespace content or a
parsed result with no nodes/edges, rewrite finish_reason="length" so
_extract_with_adaptive_retry bisects the chunk instead of silently
dropping it; applied to _call_openai_compat, _call_claude, _call_bedrock

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 21:17:25 +01:00
SafiandClaude Sonnet 4.6 dc50979a68 fix hook OOM, lift worker cap, fix antigravity .agents path and frontmatter
#791: per-repo fcntl flock in _rebuild_code prevents concurrent hook rebuilds
from exhausting memory; changed_paths wired through so only modified files are
re-extracted; stale nodes evicted on deletion; SIGALRM watchdog with
GRAPHIFY_REBUILD_TIMEOUT; Darwin-aware RLIMIT_DATA memory cap

#792: remove hard 8-worker cap (GRAPHIFY_MAX_WORKERS env var); add
--max-workers, --token-budget, --max-concurrency, --api-timeout CLI flags
to graphify extract; fix ollama API key gate for loopback URLs; explicit
timeout on OpenAI client (GRAPHIFY_API_TIMEOUT, default 600s); per-chunk
progress prints during extraction

#453 + #785: rename .agent -> .agents throughout antigravity install/uninstall;
add trigger:always_on YAML frontmatter to _ANTIGRAVITY_RULES so Antigravity
recognises the rules file

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 16:57:05 +01:00
SafiandClaude Sonnet 4.6 8e6483511d add Pascal regex fallback - extraction works without tree-sitter-pascal
tree-sitter-pascal is not on PyPI so extract_pascal() fell back to an
empty error result for all users. _extract_pascal_regex() now handles
unit/program/library headers, uses clauses, class/interface declarations
with inheritance, forward method decls, qualified impl headers, balanced
begin/end body extraction, and intra-file calls edges. All 15 previously
skipped pascal_required tests now run unconditionally and pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 15:52:17 +01:00
32bf8b4a37 feat(extract): add Pascal/Delphi and Lazarus IDE support (#781)
* feat(extract): add Pascal/Delphi language support

Adds full AST extraction for Pascal and Delphi source files using
tree-sitter-pascal (https://github.com/Isopod/tree-sitter-pascal).

Supported file extensions: .pas, .pp, .dpr, .dpk, .inc

Extracted nodes:
- File node (the .pas file itself)
- unit / program / library declarations
- class, interface, and helper type declarations
- procedure and function implementations

Extracted edges:
- file --contains--> module
- module --imports--> dependency (via uses clause, resolved to path-based IDs)
- class --inherits--> base class / interface
- class/module --contains/method--> procedure or function
- procedure --calls--> procedure (in-file call resolution)

Key design: uses clause targets are resolved to path-based node IDs by
scanning all Pascal files under the project root (_pascal_project_root +
_pascal_resolve_unit helpers). This avoids dangling import edges that
result from resolving bare unit names like "SysUtils" to IDs that never
match any file node.

Bare procedure calls (e.g. `Reset;` without parentheses) are detected
by inspecting statement nodes whose sole named child is an identifier,
in addition to the standard exprCall nodes used for calls with arguments.

Requires: pip install tree-sitter-pascal
(https://github.com/Isopod/tree-sitter-pascal)
If not installed, extract_pascal returns {"nodes":[], "edges":[], "error": ...}
so the rest of the pipeline is unaffected.

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

* feat(extract): add Lazarus .lfm and .lpk file support

Adds two new extractors for Lazarus IDE-specific file formats:

extract_lazarus_form() — .lfm (Lazarus Form files)
  .lfm files are text-based UI component trees. The extractor parses
  `object Name: TClassName ... end` blocks to build a containment graph
  of form components, and captures `OnXxx = HandlerName` event bindings
  as `references` edges (context: "event") linking each component to
  its handler procedure.

extract_lazarus_package() — .lpk (Lazarus Package files)
  .lpk files are XML package definitions. The extractor reads the
  package name, required package dependencies (→ imports edges), and
  listed unit files (→ contains edges). Unit names are resolved to
  path-based node IDs via _pascal_resolve_unit so they connect to the
  same nodes produced by extract_pascal on .pas files.

Both extensions added to CODE_EXTENSIONS in detect.py and to _DISPATCH.
13 new tests in test_pascal.py cover both extractors.

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

* fix(pascal): fix dangling inherits-edge targets and capture all base classes

The declType/typeref handler built inherits edge targets with
_make_id(_read(child)) — just the bare class name. But class nodes
use _make_id(stem, type_name), so targets never matched, making the
entire class hierarchy invisible in the graph.

Add _pascal_class_stem_cache and _pascal_resolve_class(): strips the
conventional T/I prefix, locates the defining file by stem lookup
(same cache mechanism as _pascal_resolve_unit), and returns the
correct _make_id(file_stem, class_name) ID. RTL/unresolvable bases
(e.g. TObject) fall back to _make_id(bare_name) with an explicit
stub node, following the same pattern as the Python extractor.

Also remove the `break` that stopped after the first typeref, so
all parents are captured (e.g. class(TBase, IInterface)).

Extend test_pascal_no_dangling_edges to also assert that within-file
edge targets (contains, method, inherits, calls) resolve to real nodes.

* feat(extract): add Delphi .dfm form file support

Adds extract_delphi_form() for Delphi Form files (.dfm), which use the
same `object Name: TClassName ... end` text syntax as Lazarus .lfm files.

Binary .dfm files (FF 0A magic header) are skipped gracefully with an
informative error message so the pipeline is unaffected.  Text .dfm files
are parsed identically to .lfm: component containment (`contains` edges)
and event handler references (`references`, context "event").

Adds .dfm to _DISPATCH and CODE_EXTENSIONS.
10 new tests in test_pascal.py, including a regression test for the
binary-format detection.

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

* Add .lpr extension and fix removesuffix in Pascal extractor

Address review feedback from @safishamsi:
- Add .lpr (Lazarus program file, identical syntax to .dpr) to _DISPATCH
  in extract.py and CODE_EXTENSIONS in detect.py so Lazarus project entry
  points are indexed. Completes the promised Lazarus IDE support.
- Replace rstrip("()") with removesuffix("()") in the call-resolution
  dict comprehension for precise suffix removal (rstrip strips individual
  characters, not the literal string "()").
- Add .lpr assertions to test_pascal_dispatch_registered and
  test_pascal_detect_extensions_registered.

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

---------

Co-authored-by: Simeon Bodurov <simeon.bodurov@speedy.bg>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 14:44:58 +01:00
SafiandClaude Sonnet 4.6 adf96da283 bump version to 0.7.11
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 13:10:42 +01:00
nauman73andNauman Hameed e5f263ba98 fix(windows): unblock pipeline on Windows consoles + missing __main__ guards (#788)
Three independent Windows compatibility fixes shipped together because they
all surface during the same first /graphify run on Windows.

graphify/benchmark.py
  print_benchmark() unconditionally printed U+2500 (box-drawing) and U+2192
  (rightwards arrow), which UnicodeEncodeError'd on stdouts that can't encode
  them — most notably the legacy Windows console at cp1252. New _safe()
  helper falls back to ASCII when the active stdout encoding can't carry the
  glyph; _hr() uses it. Two regression tests cover both paths and prove
  print_benchmark survives a cp1252-strict stream.

graphify/extract.py
  ProcessPoolExecutor on Windows uses spawn, so worker subprocesses
  re-import the calling __main__. When the caller is `python -c "..."` or a
  script without an `if __name__ == "__main__":` guard, the workers
  recursively spawn themselves and the pool dies. The user-visible failure
  was a 290-line traceback ending in BrokenProcessPool, hiding the actual
  cause. _extract_parallel now catches BrokenProcessPool, prints a one-line
  warning that names the __main__-guard idiom, and returns False so the
  public extract() routes to the existing _extract_sequential fallback. Two
  tests cover the parallel-returns-False contract and the sequential
  fallback wiring.

graphify/skill-windows.md
  Every `python -c "..."` block (30 in total) is replaced with a
  Write+run+delete pattern using PowerShell's literal here-string @'...'@.
  The old form was a quote-escaping minefield: any double-quote inside the
  Python source had to be backslash-escaped for the shell, and PowerShell's
  parser ate them inconsistently — failing on f-strings like
  `f'AST: {len(result["nodes"])} nodes'`. The new form passes Python source
  to disk literally, so what the model writes is what Python sees. The AST
  step's script template now includes an explicit `if __name__ == "__main__":`
  guard so multi-core extraction works even before the runtime fallback above
  kicks in. All 31 resulting heredoc blocks parse cleanly under
  `ast.parse`.

Co-authored-by: Nauman Hameed <Nauman.Hameed@enghouse.com>
2026-05-09 12:59:38 +01:00
tmaeder f88567b114 Recover from context-window-exceeded API errors in adaptive retry (#789)
Adaptive retry only recovered from `finish_reason="length"` (output
truncation). It did not handle the other shape of overflow: the API
rejecting the prompt outright with a 400 because the input plus
`max_completion_tokens` doesn't fit in the model's context window.

This shows up immediately on local OpenAI-compatible servers (LM
Studio, llama.cpp, vLLM) where the default context is small (4K-32K)
and a 60K-token chunk packed for cloud Kimi/Claude blows past it.
Without retry the whole chunk fails with no output, even though the
two halves would each fit cleanly.

Catch a heuristic set of context-overflow exception messages,
classify them as the same kind of recoverable failure as
`finish_reason="length"`, and split-recurse on the same path. Single-
file overflow returns an empty fragment so the rest of the corpus
keeps running. Unrelated errors (rate limit, auth, etc.) still
propagate.

Tested with qwen3.5-9b on LM Studio (32K ctx) against a 215-file
corpus where chunks 4-12 of 12 previously failed; with this change
the overflowing chunks self-heal by splitting in half.
2026-05-09 12:59:35 +01:00
SafiandClaude Sonnet 4.6 0c29b2cb88 fix reversed call edges after --update and missing SKILL.md on install (#760, #725)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 22:00:57 +01:00
SafiandClaude Sonnet 4.6 c8dcd03b08 document graphify uninstall command in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 20:40:07 +01:00
SafiandClaude Sonnet 4.6 480eaea2a8 add graphify uninstall command - removes all platforms in one shot
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 20:38:08 +01:00
zuyeyang 5d0392524a fix(extract): add ALTER TABLE FK extraction + schema-qualified name support for SQL (#779)
The SQL parser (`extract_sql`) previously only extracted foreign key
relationships defined inline within CREATE TABLE column definitions.
FK constraints added via ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY
... REFERENCES were silently ignored.

Additionally, `_obj_name()` only read the first identifier child of
object_reference nodes, so schema-qualified names like `Sales.Customer`
were truncated to just `Sales`.

Changes:
- Add `alter_table` handler to `walk()` that extracts FK edges from
  ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY ... REFERENCES
- Fix `_obj_name()` to read the full object_reference text, preserving
  schema-qualified names (e.g. `Sales.Customer`)
- Fix inline FK resolution in create_table and _walk_from_refs to use
  full object_reference text instead of first identifier only
2026-05-08 20:31:25 +01:00
SafiandClaude Sonnet 4.6 ef1050b0e4 bump version to 0.7.10
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 20:17:02 +01:00
Chris S ca1b774dd9 Harden Google Workspace gws exports (#772) 2026-05-07 20:07:57 +01:00
Arjun Pramanik e16ea149aa refactor(__main__): strengthen agent instructions sections with forceful graph-first directives (#775)
Rewrote _CLAUDE_MD_SECTION, _AGENTS_MD_SECTION, and _GEMINI_MD_SECTION to use forceful ALWAYS/NEVER directives instead of soft suggestions.
Agents must now consult the knowledge graph before file operations.

Context:
- Updated AGENTS.md template injected via _agents_install()
- Updated CLAUDE.md template injected via claude install
- Updated GEMINI.md template injected via gemini_install()
2026-05-07 20:07:53 +01:00
Arjun Pramanik a15cb36dfc fix(skills): rewrite YAML descriptions from pipeline-only to trigger-oriented (#774)
10 skill-*.md files had descriptions that only described what graphify does (input->pipeline->output), not when agents should use it. This meant skills never loaded proactively on codebase questions.

Changed to hybrid descriptions that retain the pipeline summary but add trigger conditions: 'Use when user asks any question about a codebase, project content, architecture, or file relationships'.
2026-05-07 20:07:49 +01:00
SerkanGeziciandSerkan Gezici 8489b26d06 fix(extract): use language_tsx for .tsx files to enable JSX-aware parsing (#766)
tree-sitter-typescript ships two grammars:
- language_typescript: pure TypeScript, no JSX support
- language_tsx:        JSX-aware variant for .tsx files

Currently both .ts and .tsx are parsed with language_typescript, which
treats JSX syntax as parse errors. Every function declaration, arrow
function, and call_expression nested inside a JSX tree is silently
dropped from the extracted graph.

Repro on a representative React+TypeScript codebase (a 13-file Tauri app):
parsing each .tsx with language_typescript produces ~276 ERROR nodes per
file. Only declarations that happen to live before the first JSX block
survive.

Fix: add _TSX_CONFIG that mirrors _TS_CONFIG but selects language_tsx,
and route .tsx files to it in extract_js().

Effect on the same repo (graphify update --force):
  Nodes:        303 → 618  (+104%)
  Edges:        482 → 779  (+62%)
  Communities:   28 → 45   (+61%)
  Parse errors  276 → 0    per .tsx file

Tests added:
- tsx fixture with helpers + JSX-returning component
- helpers and component are captured
- JSX expression calls ({fmtDate(now)}) resolve to call edges
- wiring check: .tsx uses language_tsx, .ts uses language_typescript

Note: this fixes the parsing layer. Calls inside deeply nested arrow
function callbacks (e.g. items.map(x => <T>{f(x)}</T>)) are still
missed by the call extraction logic — separate enhancement.

Co-authored-by: Serkan Gezici <serkan@quadroaipilot.com>
2026-05-07 20:07:36 +01:00
Safi 3e1c257dde add X link to README badges 2026-05-07 18:26:08 +01:00
Safi 853f4baad4 add PowerShell usage note to README 2026-05-07 16:37:35 +01:00
Safi 0656ec62a4 security hardening: F-002/F-005/F-007/F-008/F-009/F-010/F-016/F-031/F-035/F-038/PR747-NEW-2 2026-05-07 16:32:26 +01:00
Safi cf46be439a document AWS Bedrock backend in README privacy section and command reference 2026-05-07 14:51:41 +01:00
Safi aa2bd138b7 fix edges/links key mismatch in query, path, explain, and MCP loader (#768) 2026-05-07 14:48:51 +01:00
Safi 7c6c5242dc shrink star history chart width to 370px in README 2026-05-07 13:58:40 +01:00
Safi c8da4a7082 add Kimi Code CLI platform support (graphify install --platform kimi) 2026-05-07 13:16:15 +01:00
Safi 13947c3a05 add MCP resources: report, stats, god-nodes, surprises, audit, questions 2026-05-07 13:13:54 +01:00
SafiandClaude Sonnet 4.6 96c1d04889 bump version to 0.7.9, update README and CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 12:09:46 +01:00
SafiandClaude Sonnet 4.6 3529d46fd2 add PR numbers to 0.7.9 CHANGELOG entries
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 11:19:12 +01:00
Safi fe76612d90 Merge PR #708: TypeScript interface/enum/type-alias/const/new_expression extraction 2026-05-07 11:07:24 +01:00
Safi 30860b61fb changelog: 0.7.9 -- add .qmd Quarto support entry 2026-05-07 11:05:24 +01:00
Safi 62bcf754d3 Merge PR #761: add .qmd (Quarto) file extension support 2026-05-07 11:03:57 +01:00
Safi b1ea93586b add .qmd to to_obsidian_canvas safe_name regex 2026-05-07 11:03:42 +01:00
Safi 9bc79ef6e3 trim noisy scalar const types from js_extra_walk, collapse docstring 2026-05-07 11:02:15 +01:00
Safi 2d44788931 add .qmd to to_obsidian_canvas safe_name regex 2026-05-07 11:02:11 +01:00
SafiandClaude Sonnet 4.6 027fd7a1c1 remove spurious base_url from bedrock BACKENDS entry
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:53:53 +01:00
Safi 61e27fb1a5 add AWS Bedrock backend via boto3 Converse API 2026-05-07 10:51:45 +01:00
SafiandClaude Sonnet 4.6 669bc32e0d Merge PR #752: Google Workspace shortcut export (.gdoc/.gsheet/.gslides)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:42:23 +01:00
SafiandClaude Sonnet 4.6 6f15e5b102 pseudonymize Google account email with SHA256 hash in sidecar frontmatter
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:39:26 +01:00
SafiandClaude Sonnet 4.6 9bbd14a7dd Merge PR #753: CommonJS require() imports as EXTRACTED edges
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:28:44 +01:00
Safi 09e69745bc Merge PR #759: Positional install platform names 2026-05-07 10:25:56 +01:00
Safi c986e28a70 Merge PR #758: Fix GRAPHIFY_OUT for query/path/explain 2026-05-07 10:25:50 +01:00
Safi 78a16c3733 Merge PR #672: Silence file_type None warning 2026-05-07 10:25:40 +01:00
Safi 935312c227 Merge PR #671: tree-sitter version mismatch hint 2026-05-07 10:25:35 +01:00
shym 1026695da7 feat: add .qmd file extension support
Adds support for Quarto markdown (.qmd) files by:
- Adding '.qmd' to document file extensions in detection
- Updating export logic to handle .qmd in filename sanitization
- Adding .qmd extractor dispatch using the existing markdown extractor
- Updating watch comments to include .qmd files
2026-05-07 11:13:14 +09:00
Chris Stephens 68804f7f70 Handle positional install platforms 2026-05-06 17:10:45 -04:00
Chris Stephens 81bc2f9298 Fix GRAPHIFY_OUT defaults for graph query commands 2026-05-06 17:04:57 -04:00
Mani Saint-Victor, MD 2dd6ee6a9c fix: promote cross-file call edges to EXTRACTED when import evidence exists
The cross-file call resolver in `extract()` unconditionally marked every
resolved call edge as INFERRED with confidence_score 0.8 — even when the
caller's file had an explicit `imports` (symbol) or `imports_from`
(module) edge to the callee. The new CJS require handler made this gap
visible: imports were correctly EXTRACTED but the call edges that those
imports backed remained INFERRED, so downstream consumers couldn't tell
high-evidence calls apart from name-match guesses.

This pass runs after the file-id remap (line 4736), so we relativize
node `source_file` paths before computing file_nids — otherwise the
caller's computed file_nid (absolute-path-derived) wouldn't match the
imports_from edge source (already remapped to relative form).

Promotion rule:
  - Symbol-level `imports` edge from caller's file -> callee node id
    => EXTRACTED, confidence_score 1.0
  - Module-level `imports_from` edge from caller's file -> callee's file
    => EXTRACTED, confidence_score 1.0
  - Otherwise => INFERRED, confidence_score 0.8 (existing behavior)

Validated on a 92-file CJS orchestrator: 5 previously-INFERRED edges
from runExecute() now resolve to EXTRACTED, and 88% of cross-file calls
in the corpus (104 of 118) promote, leaving INFERRED only for genuine
heuristic guesses with no import backing.

Adds two tests:
  - test_cross_file_call_promoted_to_extracted_with_import_evidence
  - test_cross_file_call_remains_inferred_without_import_evidence
2026-05-06 13:13:30 -04:00
Chris Stephens f704972b3e Add optional Google Workspace shortcut export 2026-05-06 11:37:11 -04:00
Mani Saint-Victor, MD c902ae952b fix: extract CommonJS require() imports as EXTRACTED edges
The JS/TS extractor only handled ES `import` statements; CommonJS
`require()` calls produced no import edges. Downstream, the call-graph
pass could not resolve which symbols belonged to which file, so every
cross-file call in CJS Node.js codebases was downgraded to INFERRED
even when the binding was a top-of-file destructured require.

Adds three patterns to `_js_extra_walk` via a new `_require_imports_js`
helper:

  const { foo, bar: alias } = require('./mod')   -> imports_from + per-symbol imports
  const mod = require('./mod')                   -> imports_from
  const x = require('./mod').y                   -> imports_from + symbol edge for y

Refactors path-resolution out of `_import_js` into
`_resolve_js_import_target` so ES imports and CJS requires share the
relative / tsconfig-alias / bare-module logic.

Tested in a 92-file CJS Node.js orchestrator codebase: confirmed all
five previously INFERRED `runExecute -> {loadFoundation,
validateDispatchConfig, fetchSymphonyIssues, listSymphonyWorktrees,
workspacePathForIssue}` edges resolve to real top-of-file destructured
requires, so downstream calls would now be EXTRACTED instead of
INFERRED.
2026-05-06 09:41:56 -04:00
SafiandClaude Sonnet 4.6 441ac9fc38 bump to 0.7.8: update README extensions table and changelog for PR merges
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 12:28:02 +01:00
Safi 25c1ea9212 Merge PR #735: Add Gemini and OpenAI semantic extraction backends (preserve Ollama priority) 2026-05-06 12:13:39 +01:00
Safi 0010d38337 Merge PR #717: fix(extract): TS bare-path / .svelte.ts / .svelte.js / multi-dot import resolution 2026-05-06 12:06:27 +01:00
Safi 06df2066a8 Merge PR #732: feat: add Groovy and Spock support 2026-05-06 12:04:51 +01:00
Safi 12a706b595 Merge PR #711: feat(extract): add Markdown structural extraction + sync collect_files extensions with _DISPATCH 2026-05-06 12:02:43 +01:00
Safi 189cdd92c9 Merge PR #747: fix: sanitize subprocess call in hooks.py (replace git subprocess with configparser + path validation) 2026-05-06 12:00:18 +01:00
Safi 519564b742 Merge PR #745: add .luau extension support (Roblox Luau) 2026-05-06 11:59:40 +01:00
Safi 660b605e18 Merge PR #736: fix(detect): forward follow_symlinks from detect_incremental to detect 2026-05-06 11:58:59 +01:00
SafiandClaude Sonnet 4.6 e22a189df1 fix cluster-only label persistence, wiki data-loss guard, ollama error message (#744 #746 #750)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 11:56:04 +01:00
orbisai0security 6fa2ba2318 fix: V-003 security vulnerability
Automated security fix generated by Orbis Security AI
2026-05-06 06:51:11 +00:00
daleardiandClaude Opus 4.7 3457b9cd80 add .luau extension support (Roblox Luau)
Add `.luau` to CODE_EXTENSIONS and route it through extract_lua
(tree-sitter-lua). Roblox first-party code uses .luau; without this,
graphify silently skipped 379/479 files on a real Roblox codebase
and the resulting graph was dominated by vendored .lua dependencies.

tree-sitter-lua doesn't parse Luau type annotations, but it
successfully extracts function declarations and call edges from
Luau source — verified on a 379-file Roblox codebase (1265 nodes,
1471 edges, 236 communities).

A dedicated tree-sitter-luau grammar would be a richer long-term
fix; this is the minimal change to make Luau projects work today.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 23:56:51 -04:00
SafiandClaude Sonnet 4.6 48888a7c26 add Ollama backend and cross-project global graph (#729)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 18:36:59 +01:00
Safi 69d2cc84e2 fix merge-graphs to accept both edges and links key in graph.json (#738) 2026-05-05 17:14:12 +01:00
Safi 21e096fd88 update README with --graph for cluster-only and GRAPHIFY_MAX_OUTPUT_TOKENS 2026-05-05 16:04:59 +01:00
Safi 2415576ab0 bump version to 0.7.6 2026-05-05 16:02:09 +01:00
SafiandClaude Sonnet 4.6 005a36608a fix 7 bugs: cluster-only --graph, _is_sensitive boundaries, max_tokens 16384, prune message clarity, svelte stub source_file, svelte static imports, manifest on full rebuild + pi skill YAML fix
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 16:00:08 +01:00
Daniel Graham cc63a1711b Make Gemini extraction model configurable
The initial Gemini backend defaulted to 2.5 Flash, but large semantic extraction chunks can benefit from newer models and more output headroom. Move the default to Gemini 3 Flash Preview, add CLI and environment model overrides, and increase the Gemini completion budget while keeping low reasoning effort for cost control.

Constraint: Google exposes Gemini through an OpenAI-compatible chat-completions endpoint

Rejected: Hardcode Gemini 3.1 Pro as the default | higher cost for routine repository indexing

Confidence: medium

Scope-risk: narrow

Directive: Keep --model and GRAPHIFY_GEMINI_MODEL working before changing Gemini defaults again

Tested: uv run --directory vendor/graphify pytest tests/test_llm_backends.py tests/test_chunking.py -q

Not-tested: Live Gemini 3 extraction on the full cloud-edge repo before this commit
2026-05-05 10:11:12 -04:00
Alpha Nury 64585cf889 fix(detect): forward follow_symlinks from detect_incremental to detect
`detect_incremental(root)` always called `detect(root)` without forwarding
the `follow_symlinks` kwarg. As a result, corpora that include symlinked
sub-trees pointing to directories outside the scan root (e.g. a
`state_of_truth/` symlink pointing at `~/.hermes/state_of_truth/`) were
visible to a full `detect()` run with `follow_symlinks=True` but invisible
to any subsequent `--update` run. The incremental scan would then either
report no changes (silently dropping legitimate new files) or repeatedly
re-extract a phantom subset, depending on what was reachable without
crossing symlinks.

Add a keyword-only `follow_symlinks` parameter to `detect_incremental()`
and forward it. Default stays `False` for backwards compatibility — only
callers that already opt in to symlink following on `detect()` pick up
the new behaviour for incremental runs too.

Test: a corpus with a symlinked directory is invisible with
`follow_symlinks=False`, fully indexed with `follow_symlinks=True`, and
correctly reports zero new files on a second incremental scan after the
manifest is saved.
2026-05-05 15:25:08 +02:00
Daniel Graham a9cb692961 Prefer accessible semantic extraction backends
Gemini is often the cheaper available quota for low-stakes semantic graph extraction, while OpenAI is a useful fallback. Extend the direct extraction backend registry, CLI validation, docs, and tests so headless extraction can use GEMINI_API_KEY, GOOGLE_API_KEY, or OPENAI_API_KEY without changing the existing Claude and Kimi paths.

Constraint: Gemini supports OpenAI-compatible chat completions at the Google generative-language endpoint

Rejected: Native google-genai integration | higher dependency and response-shape churn for the same chat-completions path

Confidence: medium

Scope-risk: moderate

Directive: Keep backend detection explicit and test every accepted API-key environment variable before adding new providers

Tested: uv run --directory vendor/graphify pytest tests/test_llm_backends.py tests/test_chunking.py -q

Not-tested: Live Gemini/OpenAI API calls; no GEMINI_API_KEY or OPENAI_API_KEY present in this environment
2026-05-05 08:59:37 -04:00
Mikołaj Cekut 9a8346d39a chore: remove version pin from tree-sitter-groovy dependency 2026-05-05 12:23:46 +02:00
Mikołaj Cekut 6aecfcf0fe chore: replace pl.allegro with com.nicklastrange in Groovy fixtures 2026-05-05 12:22:38 +02:00
Mikołaj Cekut dc69020a47 feat: add Groovy and Spock support
- Register .groovy and .gradle in CODE_EXTENSIONS, _DISPATCH, and collect_files
- Add _GROOVY_CONFIG (reuses Java import handler)
- Add regex-based _extract_spock_fallback for Spock spec files where
  tree-sitter-groovy wraps the body in ERROR nodes due to def-string methods
- _is_spock_file detects via regex scan (def "...") instead of node-label
  heuristic, avoiding false negatives on classes whose name differs from stem
- Fallback retains only file node + import edges from tree-sitter pass to
  prevent orphaned constructor/method nodes
- Add tree-sitter-groovy>=0.1.2 dependency
- Add 11 tests covering plain Groovy and Spock paths, including apostrophe
  in feature method names
2026-05-05 12:15:15 +02:00
Christian Winther b68ec63494 fix(extract): apply resolver fixups to JS/TS dynamic_import handler
Third call site that re-implemented the same .js→.ts rewrite in
isolation. Previously only handled the explicit .js→.ts case; bare
paths, multi-dot helper files, and alias-resolved dynamic imports
all dropped silently.

Now uses _resolve_js_module_path on both branches (relative and
alias) — same shape as the static-import and Svelte regex paths.

Real-world impact: TS files using `await import('./foo')` patterns
for code splitting (e.g. lazy-loading a profanity check) now produce
edges to the resolved target.
2026-05-05 00:07:50 +02:00
Christian Winther 0dfc26e57f fix: prefer file matches over directory matches in resolver
When both a file (foo.ts) and a directory (foo/) exist at the same path,
both TypeScript and Vite prefer the file. The previous ordering checked
directory first and fell through unchanged when the directory had no
index, silently dropping every import like 'from ./auth' when an
auth/ subdirectory existed alongside auth.ts.
2026-05-04 23:44:32 +02:00
Christian Winther 5f5b59309c test(extract): cover .svelte.js + hybrid TS/JS Svelte 5 rune files
The generalized resolver already handles .svelte.js because the append
loop iterates _JS_RESOLVE_EXTS = (.ts, .tsx, .svelte, .js, .jsx, .mjs).
Adds three explicit tests to pin the behaviour and document the priority
choice:

  - test_resolve_svelte_to_svelte_js_for_javascript_rune_files
      JS-only Svelte 5 project: .svelte → .svelte.js works the same
      way as .svelte.ts in TS projects. No special-casing needed —
      the generalized append loop covers both.

  - test_resolve_svelte_prefers_svelte_ts_over_svelte_js
      Hybrid case (both files exist, e.g. .svelte.ts source plus
      .svelte.js build artifact): .ts wins. Documents the deliberate
      source-first priority — graphify is a source-code tool, not a
      runtime resolver, so we differ from Vite's default JS-first order.

  - test_resolve_real_svelte_file_wins_over_svelte_ts_sibling
      Existence check short-circuits before any extension append, so a
      real .svelte file always wins over a .svelte.ts sibling.
2026-05-04 22:47:29 +02:00
Christian Winther 49c3b50b5f fix(extract): generalize resolver to multi-dot filenames + rename
Two changes that landed together because they share the same code path:

1. Generalize the bare-path append to handle multi-dot filenames

   The previous resolver only appended extensions when path.suffix == ""
   (truly bare paths). Real codebases use a lot of multi-dot patterns:

     foo.shared.ts        ← imported as './foo.shared'
     foo.config.ts        ← imported as './foo.config'
     foo.compile.ts       ← imported as './foo.compile'
     foo.integration.ts   ← imported as './foo.integration' (test helper)
     foo.triggers.ts      ← imported as './foo.triggers'  (test helper)
     foo.svelte.ts        ← imported as './foo.svelte'    (Svelte 5 rune)
     foo.d.ts             ← imported as './foo.d'         (ambient types)

   For all of these, .suffix is the meaningful middle segment (.shared,
   .config, .integration, etc.) — not in the .js/.jsx/.svelte handled
   list, so the resolver fell through and the import dropped to a phantom.

   The fix unifies the bare-path and .svelte→.svelte.ts cases into a
   single rule: append each candidate extension to the FULL filename, not
   to the stripped stem. This subsumes:

     bare path:           foo           → foo.ts
     Svelte rune file:    foo.svelte    → foo.svelte.ts
     multi-dot helper:    foo.shared    → foo.shared.ts
     ambient declaration: foo.d         → foo.d.ts

   No behaviour change for paths that DO exist (.is_file() short-circuit)
   or for the .js→.ts / .jsx→.tsx convention (handled before the append
   loop so we don't accidentally match foo.js → foo.js.ts when foo.ts
   is the real file).

2. Rename _resolve_with_extensions → _resolve_js_module_path

   The function is JS/TS/Svelte-specific (Vite resolver order, mirrors the
   convention used by _import_js, _JS_CONFIG, _TS_CONFIG). The original
   name suggested it was a generic path utility. Renamed to make scope
   explicit and align with the existing _import_js / _JS_CONFIG naming
   pattern. Constants renamed to match: _JS_RESOLVE_EXTS, _JS_INDEX_FILES.

Tests
-----
4 new tests in tests/test_import_extension_resolution.py:

  - test_resolve_multi_dot_helper_file: foo.shared → foo.shared.ts
  - test_resolve_multi_dot_with_explicit_extension_still_works:
    foo.shared.ts (explicit) still wins
  - test_resolve_ambient_d_ts_via_bare_path: foo.d → foo.d.ts
  - test_end_to_end_multi_dot_import_resolves: tree-sitter pipeline
    sanity check via extract_js

Existing 28 tests updated for the rename. 32/32 pass; 7 pre-existing
unrelated failures elsewhere in the suite.

Validation
----------
On a 1,873-file SvelteKit codebase, applying both rules over the v0.7.5
baseline:

  baseline:                 12,096 edges
  with the resolver fix:    20,151 edges  (+8,055 = +67%)

The +2,652 over the previous version of this branch is attributable
entirely to multi-dot filename recovery, primarily test helper imports
('*.integration.ts', '*.triggers.ts'), domain-shared modules
('*.shared.ts'), and config files.
2026-05-04 22:41:50 +02:00
Christian Winther 0267cd789f test(extract): exhaustive coverage for extension resolution edge cases
Adds 8 tests covering import shapes that came up during real-codebase
validation against a 1,873-file SvelteKit project:

  - test_type_only_import_with_bare_path_resolves
      `import type { X } from './foo'` — type-only imports must go
      through the same resolver. Common pattern in TS codebases.

  - test_named_imports_emit_symbol_edges_after_resolution
      `import { foo, bar } from './module'` — verifies the per-symbol
      `imports` edges (file → module.foo, file → module.bar) target the
      correct stem after resolution. The symbol target_stem comes from
      _file_stem(resolved), so resolution must happen first.

  - test_alias_directory_import_resolves_to_index_ts
      `from '$lib/queue'` — alias + directory composes correctly.

  - test_resolve_does_not_match_partial_directory_name
      Regression guard: `from './foo'` where only `foo-extra.ts` exists
      must NOT accidentally resolve to it.

  - test_resolve_directory_without_index_returns_unchanged
      A directory with no index.* must fall through, not pick a random
      .ts inside.

  - test_resolve_handles_subpath_into_directory_with_index
      `./foo/sub` where `./foo/sub/index.ts` exists.

  - test_resolve_does_not_treat_dotfile_as_extension
      Path('.env-types.ts').suffix is '.ts' (correct), but worth pinning.

  - test_resolve_chain_alias_and_extension_compose
      Two-layer resolution: alias → bare path → .svelte.ts. Verifies
      the full chain works end-to-end for the Svelte 5 rune-file case.

Also expanded test_named_imports_emit_symbol_edges_after_resolution to
catch a subtle regression class: per-symbol import edges (line 319-340
in _import_js) build their target id from _file_stem(resolved). If
resolution fails or returns the wrong path, the symbol edges silently
target a different stem and downstream "where is X used?" queries miss
real callers.
2026-05-04 22:33:29 +02:00
Christian Winther 2b1efe8f08 fix(extract): TS bare-path / .svelte.ts / index.ts import resolution
_import_js previously only rewrote .js→.ts and .jsx→.tsx, leaving every
other common TypeScript / SvelteKit / Vite import shape unresolved. The
resulting node id wouldn't match the target file's own _make_id, so
build_from_json dropped the edge as external.

Three missed shapes:

  1. Bare paths (no extension) — TS convention:
     `import { foo } from './foo'`            → real file is foo.ts
  2. .svelte → .svelte.ts (Svelte 5 rune-only files):
     `import { x } from './x.svelte'`         → real file is x.svelte.ts
  3. Directory imports / barrel index files:
     `import { x } from './queue'`            → real file is queue/index.ts

Fix
---
New helper _resolve_with_extensions(p: Path) -> Path mirrors Vite/TS
resolver order:

  1. exact path (file)
  2. .js→.ts, .jsx→.tsx (existing TS-ESM convention)
  3. bare path → .ts/.tsx/.svelte/.js/.jsx/.mjs
  4. bare path → directory's index.{ts,tsx,js,jsx}
  5. .svelte → .svelte.ts (Svelte 5 rune file)

Falls back to the original path on no match — preserves pre-fix behaviour
for genuinely external modules (build_from_json drops them as phantoms).

Wired into _import_js (relative + alias branches) and extract_svelte's
regex pass for dynamic_import so static and dynamic imports both benefit.

Subtle: uses .is_file() / .is_dir() rather than .exists(). When the
import is a directory, .exists() returns True and would short-circuit
before the index.ts lookup ever ran.

Tests
-----
20 new tests in tests/test_import_extension_resolution.py:

  Resolver unit tests (12):
    - existing path returned unchanged
    - bare path → .ts / .tsx / .svelte
    - .ts wins over .svelte for ambiguous bare paths (Vite order)
    - directory → index.ts
    - directory prefers index.ts over index.js
    - .svelte → .svelte.ts (Svelte 5 rune file)
    - .js → .ts (TS ESM convention)
    - .jsx → .tsx
    - real .js stays .js when .ts doesn't exist
    - unresolvable returns input unchanged

  End-to-end (8):
    - bare-path import resolves in TS file
    - directory import resolves to index.ts
    - .svelte import resolves to .svelte.ts rune file
    - explicit .ts/.svelte imports still work (regression guard)
    - external module specifiers unchanged
    - alias + bare path resolves
    - dynamic_import bare path resolves
2026-05-04 22:26:48 +02:00
Safi ee85bbfbfd fix antigravity install paths .agents → .agent 2026-05-04 19:00:35 +01:00
Safi 5b33e6d2e6 remove dedup architecture diagram 2026-05-04 18:51:59 +01:00
SafiandClaude Sonnet 4.6 579e1cc744 wire --dedup-llm through build pipeline and fix fresh-extract dedup bypass
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 18:51:14 +01:00
ibrahimyuecel eca3277fb9 feat(ts): extract interface, enum, type_alias, const literal, new_expression
Bring TypeScript AST extraction to parity with Java and C# by adding the
declaration types upstream graphify currently skips:

- interface_declaration (parity with Java/C# class_types)
- enum_declaration + members
- type_alias_declaration
- module-level const literals (object/array/string/call/new/template/number)
  via _js_extra_walk extension
- new_expression as call type for both _JS_CONFIG and _TS_CONFIG

Tested against tests/fixtures/typescript_advanced.ts: 8 expected node
types extracted (IUserRepository, UserStatus, UserId, USER_REPOSITORY,
DEFAULT_ROLES, USER_CONFIG, UserService, UserModule).

Validated on a 3,800-file TypeScript monorepo (NestJS + Next.js): yields
~1,885 interfaces, ~147 enums, ~405 type aliases, ~2,236 const literal
nodes, and ~1,935 instantiates edges that were previously invisible.
2026-05-04 20:46:36 +03:00
Safi 913feca6a6 CI: add v5-v7 branches, workflow_dispatch trigger, sql extra 2026-05-04 18:27:33 +01:00
Safi 4f08e23807 Update README: add graphify extract to command reference, fix CI badge branch 2026-05-04 18:26:17 +01:00
Safi b3c99ec0ed Fix hook rebuild losing community labels; fix gemini platform install (#705, #706) 2026-05-04 18:20:16 +01:00
Safi 682d124618 bump version to 0.7.5 2026-05-04 18:07:48 +01:00
Safi 239000d2c9 Add incremental updates to graphify extract: semantic cache + build_merge + manifest 2026-05-04 18:07:02 +01:00
Safi ec413d5233 Wire deduplicate_entities into build() and build_merge() 2026-05-04 18:02:38 +01:00
Safi 34380434c4 Add graphify/dedup.py: entropy gate + MinHash/LSH + Jaro-Winkler entity deduplication 2026-05-04 18:01:11 +01:00
Safi b26467a8eb Add datasketch and rapidfuzz as base dependencies 2026-05-04 17:51:46 +01:00
Safi b5e7cf3f55 Add implementation plan: incremental updates + entity deduplication 2026-05-04 16:30:36 +01:00
Safi 5ee4b01406 Add design spec: incremental updates + entity deduplication 2026-05-04 16:25:58 +01:00
imfarhanm cddf9cf9bf docs: add fork install instructions and feature comparison to README 2026-05-04 20:04:23 +05:30
imfarhanm 09b33b795b fix: include .md/.mdx document files in graphify update rebuild path 2026-05-04 20:01:20 +05:30
Farhan M 68081c1c89 feat(extract): add Markdown structural extraction + sync collect_files extensions
1. NEW: extract_markdown() — structurally indexes .md/.mdx files into the
   knowledge graph. Headings become nodes, code blocks become nodes with
   language tags, and nesting produces 'contains' edges. Zero new deps
   (pure regex/line-by-line parsing, no tree-sitter needed).

2. FIX: collect_files() _EXTENSIONS was hardcoded and missing 18 extensions
   that _DISPATCH already supported (.jsx, .mjs, .ex, .exs, .jl, .vue,
   .svelte, .dart, .v, .sv, .sql, .f, .F, .f90, etc). Now uses
   set(_DISPATCH.keys()) to stay automatically in sync.

3. Added deploy_guide.md test fixture and 6 new test cases.
4. Updated test_collect_files_from_dir to use dynamic extension set.
2026-05-04 19:08:50 +05:30
Safi 6c3ccdc77b Fix #703: unify community counts in GRAPH_REPORT.md header and body 2026-05-04 13:59:27 +01:00
Safi 26a5a35200 bump version to 0.7.4 2026-05-04 12:40:43 +01:00
SafiandClaude Opus 4.7 741ac3655b Fix #700 #701: JSONC tsconfig parsing + Svelte dynamic import edge IDs
#700: _read_tsconfig_aliases() now handles // comments, /* */ block comments,
and trailing commas via a regex-based _strip_jsonc() helper. Tries plain
json.loads first, falls back to stripped parse, warns to stderr on failure
instead of silently returning {}.

#701 Bug A: removed startswith('.') filter from Svelte regex fallback so
aliased imports ($lib/, $partials/, @/) are no longer skipped.
#701 Bug B: fixed synthetic node IDs — source uses _make_id(str(path)),
target uses _make_id(str(normpath(parent/raw))) matching _extract_generic
and _import_js conventions so build_from_json no longer drops every edge.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 12:39:07 +01:00
Safi c1a7e250b6 bump version to 0.7.3 2026-05-04 11:46:39 +01:00
Safi c121fc4e42 README: clarify semantic extraction uses IDE model via skill, or Anthropic/Kimi for headless extract 2026-05-04 11:42:58 +01:00
Safi 6e84b42320 Clarify README: semantic extraction supports Anthropic and Kimi only (not OpenAI) 2026-05-04 11:41:40 +01:00
SafiandClaude Opus 4.7 d40e27463d Add graphify extract subcommand for headless semantic extraction (#698)
Enables docs-only corpora to run full LLM extraction in CI without Claude Code.
Handles code-only, docs-only, and mixed corpora; --no-cluster for raw dumps.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 11:31:54 +01:00
SafiandClaude Sonnet 4.6 b6ffdbb8dd v0.7.2: Fortran support + export CLI subcommands + skill.md size reduction
- Add Fortran support (26th language): .f/.F/.f90/.F90/.f95/.F95/.f03/.F03/.f08/.F08
  via tree-sitter-fortran; capital-F files preprocessed with cpp -w -P
- Add graphify export {html,obsidian,wiki,svg,graphml,neo4j} CLI subcommands
- Add graphify query/path/explain CLI subcommands
- Reduce skill.md from 63KB to 47KB by replacing Python heredocs with CLI calls
- Extend to_html() with node_limit param for auto-aggregation on large graphs
- Add integration tests for all export/query/path/explain subcommands

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 11:17:06 +01:00
Safi f81e3bc215 bump version to 0.6.9 2026-05-03 17:41:56 +01:00
SafiandClaude Sonnet 4.6 8e81720bc8 Fix #686 #652: GRAPHIFY_OUT env var for worktrees, Antigravity install auto-updates rules/workflow
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:36:17 +01:00
SafiandClaude Sonnet 4.6 6df69dce6c Fix #683: normalize source_file path separators + two-phase cohesion re-clustering
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:26:13 +01:00
SafiandClaude Sonnet 4.6 f61bb27d9c Fix #688: stricter VS Code Copilot instructions to enforce GRAPH_REPORT.md first
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:23:31 +01:00
Safi de268a067c fix Penpax waitlist link to graphifylabs.ai 2026-05-03 14:09:16 +01:00
SafiandClaude Sonnet 4.6 b11a8a7813 simplify README, move technical details to docs/how-it-works.md
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:31:28 +01:00
SafiandClaude Sonnet 4.6 d753413409 bump version to 0.6.8
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:25:44 +01:00
SafiandClaude Sonnet 4.6 f065933391 Fix #676 #678 #681: graphifyignore negation, Antigravity slash command, Gemini hook Windows
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:22:17 +01:00
azizur100389 f87d0649c5 fix: silence "invalid file_type 'None'" warning on legacy graphs (#660)
Users running `graphify update .` against a graph that contains nodes
preserved from older graphify versions see the warning:

  [graphify] Extraction warning (31 issues): Node 1661 (id='telepathy_app')
  has invalid file_type 'None' - must be one of [...]

The cause: `_rebuild_code` in watch.py preserves nodes from the existing
graph.json that aren't in the new AST output. Some of those nodes
(stubs, semantic concepts created before file_type was always
populated) have file_type=null in the on-disk JSON, which becomes
Python None on load. The validator in validate.py:33 then flags every
such node.

Add a normalization step in `build_from_json` next to the existing
`source` -> `source_file` legacy canonicalization: if a node's
file_type is None or empty, default it to "concept" before validation.
This silences the false positive while keeping the validator strict for
genuinely invalid values like "weird_type".
2026-05-03 00:46:46 +01:00
azizur100389 189847eb47 fix: surface tree-sitter version-mismatch hint instead of bare TypeError
When a user has an older tree-sitter installed against a newer language
binding (or vice versa), Language() raises TypeError with messages like
"missing 1 required positional argument: 'name'". The previous catch-all
Exception handler stored that bare message in the per-file error field,
giving users no actionable signal.

Add a dedicated TypeError branch in _extract_generic() that returns a
clearer error with the upgrade command:

  tree-sitter version mismatch for tree_sitter_python: ... .
  Try: pip install --upgrade tree-sitter tree-sitter-languages

Behavior is unchanged for all non-version-mismatch errors - the broader
Exception handler still runs as before.
2026-05-03 00:27:10 +01:00
SafiandClaude Sonnet 4.6 893acb19df Fix #664: filter thin communities from GRAPH_REPORT.md by default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 18:09:32 +01:00
SafiandClaude Sonnet 4.6 96267ad0a8 fix #651: resolve absolute graphify path at codex install time for VS Code extension on Windows
shutil.which() first; falls back to sys.executable sibling Scripts/graphify.exe
so the hook works even when venv/Scripts is not on Codex's PATH.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:38:24 +01:00
SafiandClaude Sonnet 4.6 cf7ce3a450 fix #651: hook-check exits silently instead of emitting unsupported additionalContext
Codex Desktop rejects hookSpecificOutput.additionalContext on PreToolUse.
hook-check is now a no-op — graph guidance reaches the agent via AGENTS.md/skill.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:29:40 +01:00
ba41258635 merge PR #663: parallel AST extraction with ProcessPoolExecutor (1.66x speedup on 84 files)
Co-Authored-By: hanzala-sohrab <hanzala-sohrab@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:24:57 +01:00
Safi e48428296c bump version to 0.6.7 2026-05-02 17:13:08 +01:00
SafiandClaude Sonnet 4.6 d819827ea2 fix #655 #656 #657 #658: cache dir crash, sanitize_label None, rationale file_type, token counting
#655 and #656 already fixed in cache.py and security.py.
#657: add rationale to file_type schema in all 12 skill variants; warn against inventing concept.
#658: add explicit chunk-merge step with token summation before save_semantic_cache.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:10:20 +01:00
Safi bd92ab67d6 docs: remove VB.NET from README language count and file type table 2026-05-02 17:06:00 +01:00
Hanzala Sohrab 0a99a46bfc chore: update project dependencies and metadata in pyproject.toml 2026-05-02 21:34:20 +05:30
SafiandClaude Sonnet 4.6 1e848458f9 remove VB.NET support: tree-sitter-vbnet only has Windows wheels, no Linux/macOS
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:02:24 +01:00
SafiandClaude Sonnet 4.6 2ca3a5994b merge PR #579: dynamic import() extraction for JS/TS
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:52:19 +01:00
SafiandClaude Sonnet 4.6 bfe18f0c83 fix: add context=import to JS/TS named-import edges (caught by PR #573 test)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:50:33 +01:00
SafiandClaude Sonnet 4.6 28047b502f merge PR #573: cross-language edge context filters in MCP query tool
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:49:22 +01:00
SafiandClaude Sonnet 4.6 9881d7ca30 merge PR #557: graphify tree — D3 v7 collapsible-tree HTML view of graph.json
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:48:09 +01:00
24808ef8e6 merge PR #625: token-aware chunking with split-and-retry on truncation
Co-Authored-By: Jason Matthew <jasonm4130@gmail.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:46:37 +01:00
Safi 66e61c76b1 docs: add Docker MCP Toolkit + SQLite MCP runbook (#620) 2026-05-02 16:42:08 +01:00
Safi 7237cd3290 feat: add VB.NET (.vb) language support via tree-sitter (#648) 2026-05-02 16:41:55 +01:00
Hanzala Sohrab d04e487877 Merge branch 'safishamsi:v6' into feat/parallel-ast-extraction 2026-05-02 21:11:02 +05:30
Safi 996e82b3d9 test: add regression test for ambiguous cross-file call resolution (#632) 2026-05-02 16:39:53 +01:00
Safi 9ab4f39020 Merge pull request #662 from RubenAAA/fix/ts-named-import-symbol-edges
fix(extract): emit symbol-level edges for TS/JS named imports
2026-05-02 16:37:17 +01:00
Safi 58271fb5af docs: add Pi to pyproject.toml description and keywords 2026-05-02 15:33:17 +01:00
Safi 893219d66f docs: add Pi coding agent to README platform table and install docs 2026-05-02 15:33:17 +01:00
SafiandClaude Sonnet 4.6 763a9359f5 Add Pi coding agent support and tighten wheel packaging
- Add skill-pi.md, graphify pi install/uninstall, --platform pi support (#661)
- Fix pyproject.toml: packages = ["graphify"] + include-package-data = false
  (wheel drops from 1.7MB to 285KB)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 15:33:12 +01:00
RubenAAA 5a342e385c fix(extract): emit symbol-level edges for TS/JS named imports
_import_js only created a file→file imports_from edge, leaving named
imported symbols (classes, error types, constants) as degree-1 orphans
with no connection to their consumers.

Track resolved_path when the import target resolves to a local file
(relative path or tsconfig alias). After emitting the file-level edge,
walk import_clause → named_imports → import_specifier to emit a
file → symbol EXTRACTED edge for each named specifier, using the same
_make_id(target_stem, name) key that _extract_generic uses when defining
the symbol.

On a 1696-file TypeScript monorepo this raised edge count from 8530 to
11267 (+2737 edges) and reduced isolated communities from 878 to 604.
2026-05-02 15:45:02 +02:00
Safi 47ca9228c3 security: add usedforsecurity=False to MD5/SHA1 hashes used for file diffing and filename generation 2026-05-02 14:32:16 +01:00
SafiandClaude Sonnet 4.6 36e894aa62 v0.6.6: Windows skill bash rewrite, wiki fixes, rationale-node fix, hidden allowlist, --no-viz cluster-only
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 14:25:26 +01:00
SafiandClaude Sonnet 4.6 d40e1c0cef Bump version to 0.6.5
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 14:00:32 +01:00
SafiandClaude Sonnet 4.6 e02c7cc60c Fix Codex PreToolUse hook on Windows by delegating to graphify hook-check
The python3 -c "..." approach still failed on Windows Conda (no python3
shim) and PowerShell (JSON curly brace/quote parsing). Replace the inline
command with 'graphify hook-check' — a new shell-agnostic subcommand that
prints the hookSpecificOutput JSON if graph.json exists and exits 0 silently
if not. Works on PowerShell, cmd.exe, macOS, and Linux with no quoting or
interpreter-name issues.

Users must re-run 'graphify codex install' to regenerate the hook.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 13:57:19 +01:00
SafiandClaude Sonnet 4.6 ca48092413 Add --force flag and GRAPHIFY_FORCE env var to graphify update
Bypasses the node-count safety check in to_json for refactors that
legitimately shrink the graph (renames, package deletions). Also
honored by post-commit and post-checkout hooks via GRAPHIFY_FORCE=1.

Implements the approach from #639 (targeted at v5) adapted for v6.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 13:52:09 +01:00
Hanzala Sohrab 8e01d686f7 feat: replace show/hide buttons with checkbox-based multi-select controls (#647) 2026-05-02 13:49:45 +01:00
Michal HarakalandClaude Opus 4.7 71423a1efb Kotlin call-walker: accept both simple_identifier and identifier (#659)
`extract_kotlin` previously emitted zero `calls` edges (and zero
`raw_calls` entries) on the current PyPI grammar. The Kotlin branch
of `walk_calls` only matched node type `simple_identifier`, but
PyPI's `tree_sitter_kotlin` produces `identifier` for the equivalent
plain-identifier node. The `simple_identifier` ↔ `identifier` rename
is a generation gap between tree-sitter-kotlin grammar versions —
older forks (and the JVM `io.github.bonede:tree-sitter-kotlin`
binding) still use `simple_identifier`.

Accept both names so the extractor works across grammar generations.
Also widens `_KOTLIN_CONFIG.name_fallback_child_types` for the same
reason (defensive — currently the `name` field path covers
class/function name resolution, but if that field is dropped in a
future grammar update the fallback would face the same rename).

Tested against `tests/fixtures/sample.kt`: edges go from 6
(file-contains + class-method only) to 10 (adds 4 in-file `calls`
edges resolved by the walker:
  - .get() → .buildRequest() @ L8
  - .post() → .buildRequest() @ L12
  - createClient() → Config @ L21
  - createClient() → HttpClient @ L22).

A new regression test `test_kotlin_emits_in_file_calls` asserts the
four edges so this exact bug can't recur.

Found via graphify-kmp (Kotlin Multiplatform port of graphify) —
its `PythonParityTest` flagged 4 KMP-only edges that Python missed.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 13:49:42 +01:00
SafiandClaude Sonnet 4.6 c3ddace690 Update README git hooks description to reflect detached background rebuild
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 09:37:46 +01:00
SafiandClaude Sonnet 4.6 a61b25ce5f Bump version to 0.6.4
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 09:36:20 +01:00
SafiandClaude Sonnet 4.6 8c9ee1818b Fix Codex PreToolUse hook failing on Windows
Replace bash-only [ -f ] file check with a cross-platform Python one-liner
so the hook works on Windows where cmd.exe has no [ builtin.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 09:35:28 +01:00
SafiandClaude Sonnet 4.6 a4149dffcd Bump version to 0.6.3
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 08:57:57 +01:00
SafiandClaude Sonnet 4.6 028f585356 Fix ambiguous cross-file call resolution inflating god_nodes and guard cluster-only to_html
extract.py: build name -> all candidates map instead of last-write-wins dict.
Skip cross-file INFERRED calls where the callee name resolves to 2+ nodes
(common names like log/execute/find with no import evidence to pick the right
target) — prevents spurious edges from polluting god_nodes degree ranking.

__main__.py: wrap cluster-only to_html in try/except ValueError so large
graphs (>5000 nodes) don't crash the cluster command.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 08:56:20 +01:00
SafiandClaude Sonnet 4.6 c8969edd3c Fix semantic node preservation on incremental rebuild and detach git hooks
watch.py: filter preserved nodes by ID membership in new AST output instead
of file_type — INFERRED/AMBIGUOUS nodes on code files also carry file_type=code
and were being wrongly dropped, triggering the to_json safety check refusal.

hooks.py: detach post-commit and post-checkout rebuilds with nohup + disown
so git commit returns immediately instead of blocking for the full rebuild
duration. Rebuild log written to ~/.cache/graphify-rebuild.log.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 08:53:17 +01:00
Hanzala Sohrab 0fc2dc6ad3 feat: implement parallel AST extraction using ProcessPoolExecutor with benchmarking support 2026-05-02 12:54:08 +05:30
Rangarajan Ramaswamy af15e33f57 feat: add extraction support for VB.NET files 2026-05-02 03:22:58 +03:00
Safi be83a8cc55 bump to v0.6.2 2026-05-01 22:18:18 +01:00
SafiandClaude Sonnet 4.6 3fdae8f334 fix #623 #621 #605 #638 #589 #586 #593: kimi thinking, manifest, inline comments, query boost, cache race, markdownify, content hash
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 22:15:24 +01:00
SafiandClaude Sonnet 4.6 e73b6060b1 fix #590 #628 #629 #630 #619 #617: directed graph, negation patterns, Windows paths, cross-lang noise, shebang, R
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 21:56:17 +01:00
Rangarajan Ramaswamy 5dbbcf7dad feat: add VB.NET (.vb) language support via tree-sitter
This commit adds full VB.NET language support to graphify, raising the
supported language count from 25 to 26. The implementation follows the
established LanguageConfig pattern used by all other tree-sitter-backed
extractors.

New dependency:
- Adds optional extra [vbnet] backed by tree-sitter-vbnet (published
  to PyPI at https://pypi.org/project/tree-sitter-vbnet/0.1.0/).
  Install with: pip install graphifyy[vbnet]

graphify/detect.py:
- Added .vb to CODE_EXTENSIONS so VB.NET files are discovered during
  corpus ingestion and file-system watching.

graphify/extract.py:
- _import_vbnet(): import handler for imports_statement nodes; emits
  imports edges using the namespace_name child text.
- _vbnet_extra_walk(): extra-walk hook that intercepts namespace_block
  nodes, emits a namespace node, and recurses.
- _VBNET_CONFIG: full LanguageConfig covering class_block / module_block /
  structure_block / interface_block as class types; method_declaration /
  constructor_declaration / property_declaration as function types;
  invocation call nodes with target/member_access fields.
- VB.NET-specific branches in _extract_generic:
  * Class body: VB.NET has no wrapper body node; inherits and implements
    are named fields directly on the class_block. Emits separate inherits
    and implements edges for each base type, stripping generic arguments.
  * Constructor name: constructor_declaration carries no name field in
    the grammar; always resolves to New.
  * Function body: uses the declaration node itself as body sentinel so
    the call-graph pass can find invocations inside methods.
- extract_vbnet(path): public wrapper that delegates to _extract_generic.
- _DISPATCH['.vb']: routes .vb files to extract_vbnet.

pyproject.toml:
- Added vbnet = ['tree-sitter-vbnet'] optional dependency group.
- Added 'tree-sitter-vbnet' to the all extra.

tests/fixtures/sample.vb:
- New fixture file exercising: Imports statements, Namespace block,
  Interface, Class with Inherits + Implements, Module, Structure,
  Sub/Function/Property methods, and method calls.

tests/test_languages.py:
- Added 13 tests covering: no-error, class/interface/module/structure
  detection, method detection, imports relation, inherits edge,
  implements edge, and no-dangling-edges invariant.

README.md:
- Updated language count 25 to 26.
- Added VB.NET to language list and file-extension table.
2026-05-01 21:20:36 +03:00
Safi 2dc759a951 bump to v0.6.1 2026-05-01 18:50:12 +01:00
Safi 14fd14a284 combine what+when in skill description 2026-05-01 18:47:40 +01:00
SafiandClaude Sonnet 4.6 7f336acfd9 fix .graphifyignore: correct gitignore semantics + hermetic non-VCS scan + skill auto-invoke
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 18:45:12 +01:00
SafiandClaude Sonnet 4.6 8a6306f769 make .graphifyignore hermetic: stop at VCS root, not project boundaries (closes #643)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 15:28:33 +01:00
Safi 6b68de140c stop .graphifyignore walk at any VCS root or home dir, not just .git (fixes #643) 2026-05-01 14:54:04 +01:00
Safi 17fb524a91 bump to v0.6.0 2026-05-01 10:18:37 +01:00
Safi ad1e11a035 update README: add SQL support to file type table and feature description 2026-05-01 10:16:20 +01:00
SafiandClaude Sonnet 4.6 7d604e8141 v6: SQL AST extractor + xlsx structural extraction utility (fixes #349)
- extract_sql(): deterministic tree-sitter extraction of tables, views,
  functions, foreign key references, and FROM/JOIN reads_from edges
- .sql added to CODE_EXTENSIONS and dispatch table
- tree-sitter-sql added as optional dep under [sql] extra
- xlsx_extract_structure(): extracts sheet/table/column nodes from .xlsx
  (utility — pipeline wiring in follow-up)
- 6 new SQL tests, 447 total passing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 10:15:06 +01:00
Safi 0999822364 update README: add yaml/yml to file type table and feature description 2026-04-30 22:36:24 +01:00
Safi 47a994ad5b bump to v0.5.7 2026-04-30 22:34:08 +01:00
SafiandClaude Sonnet 4.6 5aaa268650 add yaml/yml to DOC_EXTENSIONS so k8s/kustomize corpora are indexed (fixes #633)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 22:32:22 +01:00
Jason Matthew 2d13a17c3b feat(llm): split and retry chunks that hit max_completion_tokens truncation
Token-budget chunking cuts the truncation rate but doesn't eliminate
it. Output token cost scales with extractable concept density rather
than input tokens — a chunk that lands on a directory of dense design
docs can pack under the input budget while needing more than
`max_completion_tokens=8192` to express every named concept, so the
response is truncated mid-string and `_parse_llm_json` returns an
empty fragment.

Pre-tuning chunk size to be conservative enough that this never
happens leaves throughput on the table for the common case. Adding a
hard `max_files_per_chunk` cap on top of `token_budget` reintroduces
the "tune a static constant" problem the previous commit set out to
fix.

The fix uses the API's own truncation signal:

1. `_call_openai_compat` and `_call_claude` now expose `finish_reason`
   on the result dict (Anthropic's `stop_reason == "max_tokens"` is
   normalised to `"length"`).
2. `_extract_with_adaptive_retry` checks it: when truncated, splits
   the chunk in half and recurses on each half. Recursion is bounded
   by `max_retry_depth` (default 3 → at most 8x fanout per top-level
   chunk).
3. Single-file chunks that truncate can't recover and surface a
   warning rather than infinite-loop.
4. `extract_corpus_parallel` routes every chunk through the retry
   wrapper. The `on_chunk_done` callback fires once per top-level
   chunk with the merged result — recursive splits are invisible to
   callers.
2026-04-30 22:08:28 +10:00
Jason Matthew cc5c54574d feat(llm): pack chunks by token budget, parallelise, accept tiktoken
Three independent improvements to extract_corpus_parallel:

1. Token-aware chunking. Replaces `chunk_size=20` static packing with
   a greedy packer keyed on `token_budget` (default 60_000), grouped
   by parent directory so related artefacts share a chunk. Pass
   `token_budget=None` to fall back to fixed-count packing.

2. Optional tiktoken (added to the [kimi] extra). When available,
   `_estimate_file_tokens` uses cl100k_base for accurate counts;
   without it, the existing chars/4 heuristic kicks in. Kimi-K2 ships
   a tiktoken-based tokenizer so estimates against Moonshot are very
   close to truth.

3. True parallelism. The function name said "parallel" but the body
   was a sequential for-loop. Now uses ThreadPoolExecutor capped at
   `max_concurrency` (default 4 — conservative against provider rate
   limits). `on_chunk_done(idx, total, result)` still fires once per
   chunk with the original submission idx so progress UIs work
   unchanged. `max_concurrency=1` skips the pool to preserve
   sequential semantics.

Plus failure tolerance: a chunk raising is now caught, logged to
stderr, and the run continues. Other chunks' results merge as normal.

On a 162-file repo (~125k words), the same work that took ~36 min
sequential under the old code finishes in ~7 min.
2026-04-30 22:08:28 +10:00
Safi 3755fdc885 swap downloads badge back to pepy.tech 2026-04-30 09:48:37 +01:00
Safi 4e871ad36c swap downloads badge to shields.io for cache refresh 2026-04-30 09:47:55 +01:00
SafiandClaude Sonnet 4.6 97099edc38 bump to v0.5.6
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 09:01:35 +01:00
chronicgiardiaandOz abb1450b24 docs: add Docker MCP Toolkit + SQLite MCP runbook
Adds docs/docker-mcp-sqlite.md, a reproducible recipe for installing the
SQLite MCP server into Docker MCP Toolkit so any connected MCP client
(Claude Code, Cursor, VS Code, etc.) gains six SQLite tools alongside
graphify's knowledge-graph tools.

Notes the catalog has two SQLite images at time of writing: `mcp/sqlite`
(marked Archived but works) and `mcp/sqlite-mcp-server` (broken
entrypoint). Recommends the working one.

Linked from README.md under a new 'Optional integrations' section.

This is unrelated to the upstream graphify pipeline; it lives as an
optional companion runbook for users who want a lightweight persistent
SQL workspace exposed to their MCP-aware AI clients.

Co-Authored-By: Oz <oz-agent@warp.dev>
2026-04-29 16:50:57 -07:00
SafiandClaude Sonnet 4.6 4360f9644b move changelog out of README into CHANGELOG.md, add yt-dlp legal notice
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 22:44:12 +01:00
SafiandClaude Sonnet 4.6 f755aca58f fix kimi temperature 400 error and community label deletion on cleanup (fixes #610, #608)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 17:03:44 +01:00
Danil Tarasov a9946fb7a0 Merge remote-tracking branch 'upstream/v5' into v5
# Conflicts:
#	graphify/extract.py
2026-04-29 17:55:21 +03:00
SafiandClaude Sonnet 4.6 28b17d37f1 remove Python upper bound to support 3.14+ (fixes #607)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 13:33:41 +01:00
SafiandClaude Sonnet 4.6 326c03e132 remove product-site from graphify repo
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 12:28:30 +01:00
SafiandClaude Sonnet 4.6 44fc32e3e2 add product-site as part of graphify repo (was separate submodule)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 12:27:56 +01:00
SafiandClaude Sonnet 4.6 744827166e update product site: fix pip install package name to graphifyy, update stats to 38k stars / 400k+ downloads / 1900+ waitlist
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 12:26:00 +01:00
SafiandClaude Sonnet 4.6 c750582db4 fix SyntaxWarning: use raw string for shell glob pattern with backslash escapes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 10:02:56 +01:00
SafiandClaude Sonnet 4.6 71d1b394e9 fix NameError in Kimi tip: use module-level os import instead of _os
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 09:58:54 +01:00
Safi a4ad901284 Update v0.5.5 release notes in README 2026-04-29 09:48:55 +01:00
SafiandClaude Sonnet 4.6 f9c344b546 Remember scan root so graphify update works without a path arg
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 09:43:51 +01:00
SafiandClaude Sonnet 4.6 59cbad3937 Fix Go package-call false-negative and llm.py robustness
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 08:57:16 +01:00
SafiandClaude Sonnet 4.6 5904081d7a Add Kimi K2.6 backend, fix phantom god nodes (#598), fix concept file_type (#601)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 08:51:53 +01:00
Safi eceaaad61e Add v0.5.4 release notes to README 2026-04-28 15:06:26 +01:00
SafiandClaude Sonnet 4.6 dd86271312 Fix SSRF DNS rebinding TOCTOU and yt-dlp URL bypass (#591, #592)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 15:04:52 +01:00
Yalkowni 563ee80494 fix(extract): skip dynamic template literals in import() args
import(`./handlers/${name}`) previously produced a garbage edge to a
path containing the unresolved ${name} expression. Now detects
template_substitution child nodes and breaks without emitting an edge.
Static template literals (no interpolation) still resolve correctly.

Adds 2 new tests: one asserting dynamic templates produce no edge,
one asserting static templates resolve like plain strings.
2026-04-27 16:41:19 -07:00
Yalkowni 88e2b832f7 fix: drop Python <3.14 upper bound 2026-04-27 16:27:28 -07:00
Yalkowni a1dc610079 feat(extract): add dynamic import() extraction for JS/TS
Adds _dynamic_import_js() helper (65 lines) that detects import() call
expressions in JS/TS, resolves the module path (same logic as static
imports including .js→.ts mapping and tsconfig aliases), and emits
imports_from edges from the enclosing function. Hooked into walk_calls
for JS/TS configs.

Also adds tests/fixtures/dynamic_import.ts fixture and 5 new tests
in tests/test_languages.py (all passing alongside 110 existing tests).
2026-04-27 16:23:38 -07:00
dsremo a52350940a fix(tree): escape title, header, and JSON blob in emit_html
html.escape() the values that land in <title> and <h1>, and replace </
with <\/ in the JSON embedded inside <script> so crafted graph labels
or --label values cannot break out. Mirrors the _js_safe() pattern in
export.py.

Reported by Qodo on PR #557.
2026-04-27 11:55:21 +05:30
dsremo c3ba79f5aa feat(tree): graphify tree — D3 v7 collapsible-tree HTML emitter
Adds a new `graphify tree` subcommand that emits a self-contained D3
v7 collapsible-tree HTML view of an existing graph.json.

Why
---
The existing `graph.html` (force-directed) is great for finding hubs
and unexpected connections.  But for code review and onboarding, a
hierarchical tree-of-modules view is much faster: you can collapse
everything and expand only the package you care about, the depth-
based colour palette gives instant orientation, and the layout
mirrors the on-disk structure.

UX choices include expand-all / collapse-all / reset-view buttons,
multi-line `wrapText` labels with separately-coloured name and count,
a depth-based palette, click-to-toggle subtrees, and a hover-inspector
that surfaces the top-K outbound edges per symbol.

Implementation
--------------
- `graphify/tree_html.py` (575 LOC, single file, no new runtime
  dependencies).  D3 v7 is loaded from cdn.jsdelivr.net at view time.
- Hierarchy is built from `source_file` longest-common-prefix;
  symbols are grouped by containing module so the tree mirrors the
  on-disk layout exactly.
- Inspector pre-computes top-K outbound edges per symbol so the page
  works fully offline once loaded.
- `__main__.py` adds the subcommand + help text after the
  `check-update` block.

Configuration
-------------
- `--graph PATH`     path to graph.json (default: graphify-out/graph.json)
- `--output HTML`    output path (default: graphify-out/GRAPH_TREE.html)
- `--root PATH`      filesystem root (default: LCP of source_files)
- `--max-children N` cap visible children per node (default: 200)
- `--top-k-edges N`  per-symbol outbound edges in inspector (default: 12)
- `--label NAME`     project label shown in the page header

Tested locally on a 17 641-node graph — emits a 4.9 MB HTML file
that renders smoothly in Firefox / Chromium.
2026-04-26 10:24:36 +05:30
Danil Tarasov 3ff7188fbf feat: add cross-language edge contexts and context-aware queries 2026-04-24 02:59:04 +03:00
499 changed files with 157748 additions and 9068 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
+55 -12
View File
@@ -2,11 +2,50 @@ name: CI
on:
push:
branches: ["v1", "v2", "v3", "v4", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "main"]
pull_request:
branches: ["v1", "v2", "v3", "v4", "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:
@@ -14,23 +53,27 @@ 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]"
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
+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"]
+1
View File
@@ -21,6 +21,7 @@ Each stage is a single function in its own module. They communicate through plai
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
| `callflow_html.py` | `write_callflow_html(...)` | graphify-out files → Mermaid architecture/call-flow HTML |
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
| `security.py` | validation helpers | URL / path / label → validated or raises |
+606
View File
@@ -2,6 +2,612 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 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: 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)
- Fix: `.rebuild.lock` no longer accumulates PIDs across rebuilds — now contains a single owning PID while running and is unlinked on release so downstream tooling polling for its absence unblocks promptly (#858, PR #859)
- Docs: skill.md now clarifies that graphify does not read `ANTHROPIC_API_KEY` or other provider keys during `/graphify` skill runs — the host IDE session provides the LLM (PR #864)
## 0.7.18 (2026-05-14)
- Fix: `graphify update` is now idempotent — graph.json and GRAPH_REPORT.md are only rewritten when content actually changes; topology comparison short-circuits clustering entirely on unchanged graphs, eliminating residual community-count drift (#824)
- Fix: community IDs are now stable across rebuilds — Leiden/Louvain receive deterministically sorted input and a fixed random seed; greedy overlap remapper preserves existing IDs so hand-edited `.graphify_labels.json` labels don't drift onto wrong communities (#824)
- Fix: `--no-cluster` flag added to `graphify update` — writes raw AST graph without clustering, consistent with `graphify extract --no-cluster` (#824)
- Fix: `graphify update --no-cluster` now writes `"links"` key matching the schema of the full clustered path; previously wrote `"edges"`, causing schema toggle on every mode switch
- Fix: `.graphify_labels.json` was rewritten on every rebuild even when nothing changed; now only written when outputs actually change
- Fix: shrink-check (refuse overwrite when new graph has fewer nodes) was duplicated across two code paths; unified into a single `_check_shrink()` helper
- Fix: node ID format in skill.md corrected to `{parent_dir}_{filename_stem}_{entity}` — the old filename-only format caused ghost-duplicate nodes when AST and semantic extractors disagreed on the stem; top-level files use just the filename stem; existing graphs with ghost duplicates can be cleaned up with `graphify extract --force`
- Fix: safer JSON serialization in clustering sort keys (`default=str`) prevents crashes when edge attributes contain non-serializable values
- Docs: added Prerequisites, optional extras table, environment variables reference, troubleshooting, and dev setup to README (#833)
## 0.7.17 (2026-05-13)
- Fix: `graphify path` and `graphify explain` now render arrow direction correctly — `-->` for caller→callee, `<--` for callee←caller; previously the graph was loaded undirected so every hop printed `-->` regardless of stored direction (#849, #853)
- Fix: MCP `shortest_path` and `get_neighbors` tools had the same reversed-arrow bug; now fixed in `serve.py` alongside the CLI commands (#849, #853)
- Fix: `graphify extract --backend bedrock` was rejected by the CLI guard even when `AWS_PROFILE`/`AWS_REGION`/`AWS_DEFAULT_REGION`/`AWS_ACCESS_KEY_ID` were set — boto3 session auth was never reached (#846)
- Fix: BFS/DFS query traversal now skips expanding high-degree hub nodes (threshold: `max(50, p99_degree)`) as transit — hubs can still be destinations but no longer produce semantically meaningless 2-hop paths like `ClassA → View → ClassB` in Android/Spring corpora (#830)
- Fix: `--update` manifest shrink — after an incremental run, `manifest.json` was overwritten with only the changed-file subset, causing the next `--update` to re-flag the entire unchanged corpus as new; Step 9 now persists the full corpus via `all_files` fallback (#837)
- Fix: `file_type` enum aligned across `skill.md` and `llm.py` (both now enumerate all six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`); synonym mapper in `build.py` silently coerces known LLM-emitted synonyms (`pattern→concept`, `markdown→document`, `tool→code`, etc.) before validation (#840)
- Fix: Fortran test fixture renamed `sample.F90` → `sample_preprocessed.F90` to avoid case-collision with `sample.f90` on macOS case-insensitive filesystems (credit: @FatahChan, #823)
## 0.7.16 (2026-05-12)
- Fix: all `read_text()`/`write_text()` calls in `skill.md` and `skill-windows.md` now specify `encoding="utf-8"` — bare calls defaulted to the system codepage on Chinese-locale Windows, silently mojibaking node labels and Markdown content on `--update` (#832)
- Fix: `json.dumps` in skill pipeline now uses `ensure_ascii=False` so Chinese/CJK characters are stored as-is rather than `\uXXXX` escaped (#832)
- Fix: Step 1 install fallback in skill now prefers `uv tool install --upgrade graphifyy` over `pip` when uv is on PATH — pip was installing to the wrong environment when graphify was originally installed via `uv tool` (#831)
- Fix: `_score_nodes` in `serve.py` now uses three-tier precedence (exact 1000 / prefix 100 / substring 1) instead of flat substring scoring — `graphify path "Foo" "FooBar"` no longer returns 0 hops when both labels substring-match the same node (#828)
- Fix: `graphify path` and MCP `_tool_shortest_path` now emit a clear error when source and target resolve to the same node, instead of silently returning 0 hops (#828)
- Fix: `file_hash` in `cache.py` now normalises path keys via `.as_posix().lower()` — Windows junction/case variants of the same file now hash identically, fixing `save_semantic_cache` always reporting "Cached 0 files" on subsequent `--update` runs (#826)
- Fix: `check_semantic_cache` now applies the same absolute-path normalization as `save_semantic_cache` so relative `source_file` paths resolve consistently on both sides (#826)
- Fix: `_AGENTS_MD_SECTION` now includes the `/graphify` skill trigger instruction — all 7 AGENTS.md platforms (OpenCode, Codex, Aider, Trae, Hermes, OpenClaw, Factory Droid) now correctly invoke the skill tool when the user types `/graphify` (#827)
## 0.7.15 (2026-05-11)
- Fix: `-h`/`--help`/`-?` in any position now stops execution — previously `graphify cursor install --help` silently installed into Cursor; `graphify benchmark --help` crashed with FileNotFoundError (#821)
- Fix: `--version`, `-v`, and `graphify version` now print the installed version and exit (#818)
- Fix: `GRAPHIFY_OLLAMA_NUM_CTX=<invalid>` no longer falls back to hardcoded 131072 (which exhausted VRAM) — it now falls through to the auto-derived value and prints a warning (#820)
- Fix: when `GRAPHIFY_OLLAMA_NUM_CTX` is set smaller than the estimated chunk size, graphify now warns explicitly that Ollama will silently truncate the prompt and suggests a corrected `--token-budget` (#820)
## 0.7.14 (2026-05-11)
- Fix: `_make_id` and `_normalize_id` now apply NFKC Unicode normalization before ID generation -- composed/decomposed forms of the same character (e.g. `é` typed vs pasted from a PDF) now produce the same node ID; switched from `.lower()` to `.casefold()` for correct Turkish/German/Greek case folding; both functions are now byte-for-byte equivalent (#811)
- Fix: non-ASCII identifiers (CJK, Cyrillic, Arabic, accented Latin) are no longer collapsed to a bare file stem -- `[^\w]+` with `re.UNICODE` replaces the old `[^a-zA-Z0-9]+` so Unicode word chars are preserved as part of the ID (#811)
- Fix: dedup edge remap uses explicit key-presence check instead of `or` so empty-string `source` is not silently swapped for `from`; stale `from`/`to` keys are now popped before the edge is emitted so they can't leak into `graph.json` edge attributes (#803)
- Fix: `--update` merge now calls `build_merge()` directly instead of an inline NetworkX round-trip that re-introduced the direction-flip bug from #760; dict merge ordering fixed so explicit `source`/`target` always win over stale attrs; hyperedges pulled from `G.graph` (merged) rather than just the new extraction (#801)
- Fix: subagent chunk files are now written to an absolute path (`CHUNK_PATH` injected at dispatch time from `graphify-out/.graphify_root`) so the Write tool doesn't lose chunks to an undefined working directory (#808)
- Fix: skill version mismatch warning is now suppressed during `hook-check` (runs on every editor tool use and must be silent) and routed to stderr for all other commands
## 0.7.13 (2026-05-09)
- Fix: Ollama `num_ctx` now derived from actual chunk size instead of hardcoded 131072 -- over-allocating 128k KV-cache slots for small chunks exhausted VRAM by chunk 4 on large models; formula is `min(input_tokens + output_cap + 2000, 131072)` so `--token-budget 8192` gets ~26k instead of 131072 (#798)
- Fix: hollow-response warning now mentions VRAM pressure and `GRAPHIFY_OLLAMA_NUM_CTX` / `GRAPHIFY_OLLAMA_KEEP_ALIVE` env vars as tuning knobs (#798)
- Feat: `graphify export callflow-html` -- generates a self-contained Mermaid architecture/call-flow HTML page from `graphify-out/graph.json`, grouped by community with interactive zoom/pan diagrams, call detail tables, and graph report highlights (#797)
- Feat: callflow HTML auto-regenerates on every `--watch` rebuild and post-commit hook if the file already exists -- opt-in by existence, zero config (#800)
## 0.7.12 (2026-05-09)
- Fix: `graphify explain` and `graphify path` no longer crash on `MultiGraph` inputs -- new `edge_data()`/`edge_datas()` helpers in `build.py` handle both simple and multi-graphs; all 8 production call sites and 30 skill-file inline heredocs updated (#796)
- Fix: hollow Ollama responses (0 tokens / empty string) now trigger adaptive retry bisection instead of silently dropping the chunk -- `_response_is_hollow()` detects empty/null/whitespace content and parsed results with no nodes/edges, then rewrites `finish_reason="length"` to route into the existing bisection path (#792)
- Fix: post-commit hook no longer spawns unbounded parallel rebuilds -- per-repo `fcntl.flock` non-blocking lock in `_rebuild_code`; `changed_paths` wired from hook through to AST extractor; stale nodes evicted on deletion; `GRAPHIFY_REBUILD_TIMEOUT` watchdog; Darwin-aware memory cap (#791)
- Fix: Antigravity install now writes to `.agents/` (plural) -- corrected in platform config, paths, workflow body, and help text (#453)
- Fix: Antigravity rules file now includes `trigger: always_on` YAML frontmatter so Antigravity recognises it (#785)
- Feat: `graphify extract` gains `--max-workers`, `--token-budget`, `--max-concurrency`, `--api-timeout` flags; hard 8-worker AST cap removed; explicit HTTP timeout on OpenAI client (default 600s, `GRAPHIFY_API_TIMEOUT`); ollama API key gate skipped for loopback URLs (#792)
- Feat: Pascal/Delphi extraction now works without `tree-sitter-pascal` -- regex fallback covers unit/program/library headers, uses clauses, class/interface inheritance, method declarations, and intra-file calls (#781)
- Feat: `/graphify --help` now prints the Usage block and stops without running pipeline steps (all 12 skill files) (#795)
## 0.7.11 (2026-05-09)
- Fix: context-window-exceeded API errors now trigger automatic retry with bisected file chunks -- exponential bisection up to 6 levels deep; covers `"context_length_exceeded"`, `"maximum context length"`, and `"too_large"` across OpenAI-compat backends (#789)
- Fix: Windows pipeline unblocked -- `print_benchmark()` falls back to ASCII box-drawing on cp1252 consoles; `ProcessPoolExecutor` `BrokenProcessPool` caught and falls back to sequential extraction when caller lacks `if __name__ == "__main__":` guard; Windows skill file (`skill-windows.md`) rewrites all `python -c "..."` blocks as PowerShell heredocs to fix quote-escaping failures (#788)
- Fix: reversed `calls` edges after `--update` -- `build_merge()` now reads the saved JSON directly instead of round-tripping through NetworkX `node_link_graph()`, which was silently reversing edge direction on reload (#760)
- Fix: atomic SKILL.md install -- temp-file + `os.replace()` pattern prevents half-installed empty skill directories that looked valid but contained no file; version-stamp guard and warning added for missing installs (#725)
- Feat: `graphify uninstall` top-level command -- removes graphify skill files from all platforms in one shot; `--purge` flag also deletes `graphify-out/`
- Feat: SQL `ALTER TABLE` FK extraction -- `ADD CONSTRAINT ... FOREIGN KEY` and `ADD FOREIGN KEY` DDL statements now emit `references` edges; schema-qualified table names (`schema.table`) correctly resolved (#779)
## 0.7.10 (2026-05-07)
- Fix: `.tsx` files now use `language_tsx` grammar for JSX-aware parsing -- previously `language_typescript` was used, silently dropping all JSX-specific nodes (#766)
- Fix: `edges` key in saved graph JSON now normalised to `links` before loading -- prevents `KeyError: 'links'` on graphs written by older NetworkX versions in `query`, `path`, `explain`, and serve (#768)
- Fix: Google Workspace `gws export` drops unsupported `resourceKey` query param -- Drive API requires it as an HTTP header; sending it as a query param was a silent no-op (#772)
- Security: eleven hardening fixes -- Cypher escape strips C0 control chars and `\n`/`\r`; YAML frontmatter escapes U+2028, U+2029, tabs, and C0; MCP `sanitize_label` applied to all LLM-derived fields; C preprocessor blocked from `#include` exfiltration via `-nostdinc -I /dev/null`; merge-driver 50 MB file size cap and 100k node cap; `detect_backend()` places Ollama last so paid API keys take precedence over ambient `OLLAMA_BASE_URL`; Neo4j `--password` reads from `NEO4J_PASSWORD` env var by default; hooks exception handling narrowed to `(configparser.Error, OSError)`
- Refactor: skill YAML descriptions rewritten to be trigger-oriented (#774)
- Refactor: generated `CLAUDE.md` / `AGENTS.md` / `GEMINI.md` templates strengthened with `ALWAYS`/`NEVER`/`IF ... EXISTS` graph-first directives (#775)
## 0.7.9 (2026-05-07)
- Feat: TypeScript extraction parity -- interface, enum, type alias, and module-level const nodes extracted; new_expression emits calls edges; parity with Java/C# class_types (#708)
- Feat: Quarto (`.qmd`) file support -- routed through existing Markdown extractor; Quarto executable code blocks (` ```{python} `) extracted as code nodes (#761)
- Feat: optional Google Workspace shortcut export for headless extraction -- `graphify extract ./docs --google-workspace` converts `.gdoc`, `.gsheet`, and `.gslides` files into Markdown sidecars with the `gws` CLI before semantic extraction; account email pseudonymized via SHA256 hash; `[google]` extra adds Sheets table rendering support (#752)
- Fix: Google Workspace exports now run `gws` from the sidecar output directory with a relative `-o` path, matching `gws` path validation and avoiding failures when extracting a corpus outside the current working directory.
- Feat: AWS Bedrock backend -- `graphify extract ./docs --backend bedrock`; credentials via standard AWS provider chain (AWS_PROFILE, AWS_REGION, IAM roles, SSO); model via GRAPHIFY_BEDROCK_MODEL (default anthropic.claude-3-5-sonnet-20241022-v2:0); `[bedrock]` extra adds boto3 (#757)
## 0.7.8 (2026-05-06)
- Fix: CommonJS `require()` imports now extracted from JS/TS -- `const { foo } = require('./mod')`, `const m = require('./mod')`, and `const x = require('./mod').y` all emit EXTRACTED `imports_from` (and per-symbol `imports`) edges. Previously CJS-only Node.js codebases produced AST graphs missing every import edge, which downgraded all cross-file calls to INFERRED.
- Fix: cross-file `calls` edges are now promoted from INFERRED to EXTRACTED when the caller's file has an explicit `imports` or `imports_from` edge to the callee. Previously every cross-file call was unconditionally INFERRED, even when a top-of-file `import` / `require` proved the binding. On a 92-file CJS Node.js corpus this promoted 88% of cross-file calls (104 of 118) to EXTRACTED.
- Feat: Gemini and OpenAI backends -- `graphify extract ./docs --backend gemini` (GEMINI_API_KEY / GOOGLE_API_KEY) or `--backend openai` (OPENAI_API_KEY); `[gemini]` and `[openai]` extras added (#735)
- Feat: Groovy and Spock support -- `.groovy` and `.gradle` extracted via tree-sitter-groovy; Spock spec files (`def "feature"()` syntax) handled via regex fallback (#732)
- Feat: Luau support -- `.luau` (Roblox Luau) added to code extraction using the Lua tree-sitter parser (#745)
- Feat: Markdown structural extraction -- headings, fenced code blocks, and nesting hierarchy extracted as graph nodes from `.md` and `.mdx` files with zero new dependencies (#711)
- Fix: `collect_files()` extension set now auto-syncs with `_DISPATCH` -- previously 18 extensions (`.sql`, `.vue`, `.svelte`, `.jsx`, `.ex`, `.jl`, etc.) were silently skipped in skill-mode extraction (#711)
- Fix: `detect_incremental` now forwards `follow_symlinks` to `detect()` -- symlinked subtrees no longer vanish on `--update` runs (#736)
- Fix: TS bare-path / `.svelte.ts` / `.svelte.js` / `index.ts` directory / multi-dot imports now resolve correctly -- previously these produced phantom edges dropped at merge time (#717, #716)
- Fix: `cluster-only` now loads and saves `.graphify_labels.json` -- human-readable community labels survive re-clustering instead of resetting to "Community N" (#744)
- Fix: `graphify export wiki` now fails fast with exit 1 if `.graphify_analysis.json` is missing -- prevents silent deletion of existing wiki articles (#746)
- Fix: `to_wiki()` now raises before the cleanup loop when `communities` is empty -- second safety layer against wiki data loss (#746)
- Fix: Ollama import error message now says "Ollama" not "Kimi" and points to `pip install openai`; `[ollama]` extras group added (#750)
- Security: hooks.py path execution now validates scripts are within the repo root -- closes supply-chain attack vector where a malicious commit could redirect hook execution (#747)
## 0.7.7 (2026-05-05)
- Feat: Ollama backend for headless extraction -- `graphify extract ./docs --backend ollama`; auto-detected when `OLLAMA_BASE_URL` is set; defaults to `qwen2.5-coder:7b`; zero cost ($0.00); sentinel API key handles OpenAI client auth requirement (#729)
- Feat: Cross-project global graph at `~/.graphify/global.json` -- `graphify global add/remove/list/path` to register multiple project graphs with `<repo>::<id>` prefixed node IDs, preventing silent collisions; hash-based skip avoids re-ingesting unchanged graphs (#729)
- Feat: `graphify extract --global --as <tag>` flag -- after building a project graph, auto-registers it into the global graph in one step (#729)
- Feat: `merge-graphs` now prefix-relabels each input graph before composing, preventing silent node ID collisions when two projects share entity names (#729)
- Fix: `deduplicate_entities` raises `ValueError` if called with nodes spanning multiple repos (cross-project dedup disabled by design -- per-project graphs are deduplicated in isolation) (#729)
- Fix: `detect_incremental()` now accepts and forwards `follow_symlinks` to `detect()`. Without this, `--update` runs silently miss any files reached through a symlinked sub-tree (e.g. `state_of_truth/` symlinking to a directory outside the corpus root), even when the original full run had detected them. Previously the flag was on `detect()` and `collect_files()` only. (#736)
## 0.7.6 (2026-05-05)
- Fix: `cluster-only` now accepts `--graph <path>` to specify a non-default graph.json location; positional path and flags can appear in any order (#724)
- Fix: `_is_sensitive()` no longer drops legitimate source files — word boundaries on the keyword pattern prevent false positives like `tokenizer.py`, `password_verification.py`, `SecretManager.java` (#718)
- Fix: `graphify extract --backend claude/kimi` raises default `max_tokens` from 8192 → 16384, eliminating the truncation-then-recursive-split cascade on dense doc corpora; respects `GRAPHIFY_MAX_OUTPUT_TOKENS` env var (#730)
- Fix: `--update` prune message now clearly distinguishes "N nodes pruned from M deleted files" from "M deletions detected but graph already clean — no drift" (#539)
- Fix: `extract_svelte()` stub nodes now carry the resolved import path as `source_file` instead of the importer's path, preventing metadata corruption after merge (#712)
- Fix: `extract_svelte()` now catches static `import X from './foo.svelte'` via a dedicated regex pass over `<script>` block content — previously tree-sitter's JS parser silently dropped all static imports in `.svelte` files (#713)
- Fix: `graphify extract` (full rebuild path) now saves `manifest.json` on every successful run, not only on `--update`; prevents stale-manifest drift on subsequent incremental runs (#538)
- Fix: `graphify antigravity install` now writes to `.agent/` (no trailing s) matching Antigravity's actual config paths (#704)
- Fix: Pi skill YAML frontmatter description simplified to avoid "nested mappings" parse error on Pi startup (#737)
- Fix: `--dedup-llm` flag now correctly threads LLM backend through to `deduplicate_entities` in both fresh and incremental extract paths; fresh extract path now also runs dedup (previously called `build_from_json` directly, bypassing dedup entirely)
## 0.7.5 (2026-05-04)
- Feat: `graphify extract` now runs incrementally - auto-detects prior `manifest.json` and re-extracts only changed/new files; semantic results cached by content hash so unchanged docs cost zero LLM tokens on repeat runs (#698)
- Feat: Entity deduplication pipeline runs on every build - entropy gate + MinHash/LSH blocking + Jaro-Winkler verification + same-community boost collapses near-duplicate entities (typos, spacing, plurals) before clustering
- Feat: `--dedup-llm` flag for `graphify extract` - optional LLM tiebreaker for ambiguous entity pairs (~$0.01 for 10k-node graphs), off by default
- Fix: `graphify hook install` rebuild now preserves human-readable community labels from `.graphify_labels.json` instead of resetting to generic "Community N" names on every commit (#705)
- Fix: `graphify install --platform gemini` now works correctly (#706)
- Deps: `datasketch` and `rapidfuzz` added as base dependencies
## 0.7.4 (2026-05-04)
- Fix: `_read_tsconfig_aliases()` now parses JSONC — handles `//` line comments, `/* */` block comments, and trailing commas that every TypeScript framework starter generates; warns to stderr on parse failure instead of silently returning `{}` (#700)
- Fix: `extract_svelte()` regex fallback now captures aliased dynamic imports (`$lib/...`, `$partials/...`, `@/...`) and uses correct `_make_id(str(path))` scheme so edges survive into `graph.json` instead of being dropped as phantom nodes (#701)
## 0.7.3 (2026-05-04)
- Feat: `graphify extract <path>` — headless full-pipeline extraction for CI; runs AST extraction on code files and semantic LLM extraction on docs/papers/images without Claude Code in the loop; supports `--backend kimi|claude`, `--out DIR`, `--no-cluster`; auto-detects backend from `MOONSHOT_API_KEY` / `ANTHROPIC_API_KEY`; docs-only corpora (issue #698) work cleanly
- Fix: export/query/path/explain CLI subcommands added in 0.7.2 now ship with integration tests
- Fix: skill.md reduced from 63KB to 47KB by replacing Python heredocs with CLI calls (#696)
## 0.7.2 (2026-05-04)
- Feat: Fortran support - extracts modules, subroutines, functions, programs, `use` imports, and `call` edges from `.f`, `.F`, `.f90`, `.F90`, `.f95`, `.F95`, `.f03`, `.F03`, `.f08`, `.F08` files; names are lowercased for case-insensitive matching (#694)
## 0.7.1 (2026-05-04)
- Fix: Obsidian export - community labels with `.`, `&`, `(`, `)` now produce valid Obsidian tags; only `[a-zA-Z0-9_\-/]` characters survive, preventing broken Dataview queries (#690)
- Fix: `_load_tsconfig_aliases()` now follows tsconfig `extends` chains - SvelteKit, Nuxt, and NestJS path aliases defined in extended configs are no longer silently dropped (#691)
- Fix: `.svelte` files now get a regex pass over the template layer after JS AST extraction - `{#await import('./X.svelte')}` markup-level dynamic imports are captured as edges (#692)
- Fix: recursion limit raised to 10,000 at extract entry points (main process + each worker) with a `_safe_extract` wrapper that skips pathological files with a clear warning instead of crashing the whole run (#695)
## 0.7.0 (2026-05-03)
Multi-dev busy-repo support: four gaps that caused merge conflicts, stale graphs, and silent cache misses in team workflows.
- Feat: `graphify hook install` now also configures a git merge driver for `graphify-out/graph.json` — union-merges two graph.json files so git never produces conflict markers in the knowledge graph; writes `.gitattributes` and registers `graphify merge-driver` in `.git/config`
- Feat: `graphify merge-driver <base> <current> <other>` subcommand — takes two graph.json variants and writes their node/edge union back to `<current>`; always exits 0 so merge never blocks
- Feat: Leiden community detection now seeded (`seed=42` when supported) for deterministic community IDs across parallel rebuilds — reduces JSON diff churn in multi-dev repos
- Feat: `graph.json` now embeds `built_at_commit` (git HEAD) at write time; `GRAPH_REPORT.md` surfaces the commit hash and a freshness check hint
- Fix: `file_hash` is now content-only (path removed from hash) — renamed files reuse their cache entry instead of re-extracting; cached `source_file` fields are updated to the new path on load
- Fix: watch mode mixed-batch handling — commits with both code and non-code files now rebuild code immediately AND write `needs_update` flag; previously code changes were silently dropped in mixed batches
## 0.6.9 (2026-05-03)
- Fix: `source_file` path separators normalized to forward slashes at graph ingestion — same physical file emitted with backslashes (Windows AST extractor) and forward slashes (semantic subagents) now merges into one node instead of splitting into two disconnected components (#683)
- Fix: two-phase cohesion re-clustering — communities with cohesion < 0.05 and ≥ 50 nodes are re-split, preventing doc-hub nodes (e.g. `CLAUDE.md`) from merging unrelated subsystems into one giant community (#683)
- Fix: VS Code Copilot instructions rewritten to be prescriptive — agent's first tool call must read `GRAPH_REPORT.md`, explicit trigger list, narrow allowlist for raw source reads (#688)
- Feat: `GRAPHIFY_OUT` env var overrides the output directory — accepts a relative name or absolute path, wires through `cache.py`, `watch.py`, and the CLI; useful for sharing one graph across multiple git worktrees (#686)
- Fix: `graphify antigravity install` now auto-updates stale rules and workflow files on re-run instead of silently skipping them (#652)
- Docs: README simplified — less dense, plain language; technical pipeline details moved to `docs/how-it-works.md`
## 0.6.8 (2026-05-03)
- Fix: `.graphifyignore` negation patterns (`!src/**`) now work correctly — when any `!` pattern is present, directory pruning is deferred to per-file checks so negated files inside ignored directories are reached (#676)
- Fix: Antigravity slash command `/graphify` now appears in the command dropdown — workflow file now includes YAML frontmatter with `name: graphify` required for Antigravity discovery (#678)
- Fix: Gemini CLI BeforeTool hook replaced `[ -f ... ] && echo` (bash-only) with cross-platform `python -c` using `json.dumps` — fixes hook failure on Windows CMD and Git Bash (#681)
- Fix: Codex hook-check exits silently — resolves `additionalContext` rejection on Codex Desktop PreToolUse (#651)
- Fix: `graphify install --platform codex` now writes absolute path to `graphify` executable — fixes PATH resolution in VS Code extension on Windows (#651)
- Fix: thin communities (fewer than 3 concept nodes) are now omitted from the Communities section in `GRAPH_REPORT.md` by default; report header shows `(N total, M thin omitted)` and Knowledge Gaps collapses thin communities to one summary line (#664)
## 0.6.7 (2026-05-02)
- Feat: `graphify tree` — self-contained D3 v7 collapsible-tree HTML view of `graph.json`; expand/collapse controls, depth-based colours, hover inspector; XSS-safe (#557)
- Feat: token-aware chunking with split-and-retry on truncation (#625)
- Feat: cross-language edge context filters in MCP `query_graph` tool (#573)
- Feat: dynamic `import()` extraction for JS/TS (#579)
- Fix: `save_semantic_cache` crashed with `IsADirectoryError` when a node's `source_file` was a directory path — `p.exists()` → `p.is_file()` (#655)
- Fix: `sanitize_label(None)` raised `TypeError` crashing `to_html` on graphs with null `source_file` rationale nodes — return `""` early (#656)
- Fix: chunk-extraction prompt omitted `rationale` from valid `file_type` values — model hallucinated `concept` on every doc/paper run; explicit merge step added to all skill variants (#657)
- Fix: `cost.json` always reported 0 tokens — chunk JSONs have placeholder zeros; orchestrator now globs and sums real token counts before merging (#658)
## 0.6.6 (2026-05-02)
- Fix: `skill-windows.md` rewritten from PowerShell to bash — Claude Code on Windows uses git-bash so PowerShell syntax (`$null`, `$LASTEXITCODE`, `Select-Object`, `& (Get-Content ...)`, `Remove-Item`) caused exit code 49 failures; now mirrors `skill.md` structure with `python` added as fallback after `python3` for Windows Conda (#39)
- Fix: wiki `to_wiki()` now clears stale articles before regenerating, preventing orphan .md accumulation (#558)
- Fix: `_safe_filename()` in wiki.py now strips Windows-reserved characters (`< > : " / \ | ? *`) and caps length at 200 chars (#594)
- Fix: rationale-node leakage in cross-file INFERRED call resolution — rationale nodes now excluded from name lookup; edge direction (`calls`, `rationale_for`) preserved correctly at JSON export (#576)
- Feat: `.graphifyinclude` hidden path allowlist — opt specific hidden dirs into traversal (e.g. `.hermes/plans/**/*.md`) (#583)
- Feat: `--no-viz` flag wired in `cluster-only`; `GRAPHIFY_VIZ_NODE_LIMIT` env var overrides 5000-node HTML threshold (#565)
- Fix: stray colon SyntaxError in `skill-trae.md` `--cluster-only` block (#603)
- Docs: skill INFERRED confidence score guidance changed to discrete rubric (0.55/0.65/0.75/0.85/0.95) backed by calibration data (#546)
- Docs: skill `--update` prune output clarified — splits no-drift vs drift cases (#544)
- Docs: skill `--update` merge step now calls `save_manifest` to prevent deleted files reappearing (#545)
- Feat: `graphify tree` — self-contained D3 v7 collapsible-tree HTML view of `graph.json`; expand/collapse controls, depth-based colours, hover inspector; XSS-safe via `html.escape()` and `_js_safe()` (#557)
## 0.6.5 (2026-05-02)
- Fix: Kotlin call-walker now accepts both `simple_identifier` and `identifier` node types — PyPI's `tree_sitter_kotlin` grammar uses `identifier` while older forks use `simple_identifier`, causing zero `calls` edges to be emitted (#659)
- Feat: community sidebar now uses checkbox-based multi-select instead of show/hide buttons — supports indeterminate "select all" state (#647)
- Feat: `graphify update --force` and `GRAPHIFY_FORCE=1` env var — bypass the node-count safety check after refactors that legitimately shrink the graph (#639)
- Fix: Codex PreToolUse hook on Windows — replaced `python3 -c "..."` inline command (fails on Conda where only `python` exists, and breaks PowerShell JSON parsing) with `graphify hook-check`, a new shell-agnostic subcommand. Re-run `graphify codex install` to regenerate the hook (#651, #522)
## 0.6.4 (2026-05-02)
- Fix: Codex PreToolUse hook failed on Windows — `[ -f ]` is bash-only and crashes on `cmd.exe`; replaced with a cross-platform Python one-liner (`pathlib.Path.exists()`) (#651)
## 0.6.3 (2026-05-02)
- Fix: incremental rebuild (`graphify update`, post-commit hook) dropped INFERRED/AMBIGUOUS semantic nodes extracted from code files — node preservation now filters by ID membership in the new AST output instead of `file_type`, so LLM-extracted call/data-flow edges survive code-only rebuilds (#653)
- Fix: post-commit and post-checkout hooks blocked `git commit` for the full rebuild duration (hours on large repos) — rebuilds now detach via `nohup & disown`, git returns in ~100ms, log written to `~/.cache/graphify-rebuild.log` (#650)
- Fix: cross-file INFERRED `calls` resolution used a last-write-wins name map, causing common short names (`log`, `execute`, `find`) to accumulate hundreds of spurious edges and dominate god_nodes ranking — resolution now skips any callee name that matches 2+ candidates (ambiguous, no import evidence to pick the right target) (#543)
- Fix: `cluster-only` command crashed on graphs with >5000 nodes due to unguarded `to_html` call — now wrapped in try/except ValueError matching the watch/hook path (#541)
## 0.6.2 (2026-05-01)
- Fix: Kimi K2.6 reasoning mode consumed entire token budget leaving `content` empty — thinking now disabled on Moonshot calls so graphs actually populate (#623)
- Fix: `graphify update` / `graphify watch` never persisted the manifest, so every subsequent `--update` re-extracted all files — manifest now saved after each rebuild (#621)
- Fix: inline comments in `.graphifyignore` (e.g. `vendor/ # legacy`) now stripped correctly — whitespace + `#` suffix is treated as a comment, `path#hash.py` preserved (#605)
- Fix: `graphify query "FunctionName"` now returns the exact matching node first instead of high-degree hub modules hijacking the output — 100-point exact-match bonus + seeds render before BFS expansion (#638)
- Fix: concurrent AST extractors raced on a shared `.tmp` cache file — each writer now gets a unique tempfile via `mkstemp`, eliminating cache corruption under parallel extraction (#589)
- Fix: `_clone_repo` branch names starting with `-` could be interpreted as git flags — validation added, `--` separator inserted before positional args (#589)
- Fix: replaced `html2text` (GPL-3.0) with `markdownify` (MIT) — removes the only copyleft dependency from a MIT project (#586)
- Fix: `--update` re-extracted files whose mtime was bumped by sync tools (Obsidian, Nextcloud) without content changes — manifest now stores content hash alongside mtime; mtime bump triggers an MD5 check before re-extraction (#593)
- Feat: R language support — `.r` files classified as code and processed via LLM semantic extraction (#617)
- Feat: extensionless shell scripts now detected via shebang (`#!/bin/bash`, `#!/usr/bin/env python3`, etc.) and included as code (#619)
- Fix: cross-language INFERRED `calls` edges (e.g. Python→TypeScript name collision) no longer appear as top surprising connections in GRAPH_REPORT.md (#630)
- Fix: `cluster-only` CLI silently flipped directed graphs to undirected — `directed` flag now read from graph.json and preserved through re-clustering (#590)
- Fix: Windows UNC / extended-length paths (`\\?\C:\...`) now normalize to consistent cache keys (#629)
- Fix: `.graphifyignore` negation patterns (`!src/lib/secrets.ts`) now work — full last-match-wins evaluation with `!` un-ignore support (#628)
## 0.6.1 (2026-05-01)
- Fix: `.graphifyignore` discovery now uses correct gitignore semantics — outer rules are loaded first so inner (closer) rules always win via last-match-wins, matching standard gitignore behavior (#643)
- Fix: without a VCS root, `.graphifyignore` discovery is now hermetic to the scan folder — no leakage across sibling projects in a shared workspace (#643)
- Fix: anchored patterns (leading `/`) in a parent `.graphifyignore` now correctly apply only relative to their own directory, not the scan root (#643)
- Fix: trailing spaces in patterns are now handled per gitignore spec — unescaped trailing spaces are stripped, `vendor\ ` (escaped) is preserved (#643)
## 0.6.0 (2026-05-01)
- Feat: SQL AST extractor — `.sql` files now processed deterministically via tree-sitter. Extracts tables, views, functions/procedures, foreign key references, and FROM/JOIN reads_from edges. No LLM needed. Requires `pip install 'graphifyy[sql]'` (#349)
- Feat: `xlsx_extract_structure()` utility — extracts sheet names, named tables, and column headers from .xlsx files as structural nodes
## 0.5.7 (2026-04-30)
- Feat: YAML/YML files now indexed for semantic extraction — Kubernetes, Kustomize, Helm, and any YAML corpus now picked up automatically (#633)
## 0.5.6 (2026-04-30)
- Fix: `NameError: name '_os' is not defined` crash after `graphify update` — this was fixed in v5 branch but not released to PyPI (#618, #612)
## 0.5.5 (2026-04-29)
- Feat: Kimi K2.6 backend — `pip install 'graphifyy[kimi]'` + `MOONSHOT_API_KEY` routes semantic extraction through Kimi K2.6. 3-6x richer relation extraction at ~3x lower cost. Claude remains default; Kimi is opt-in.
- Fix: phantom god nodes (#598) — member-call callees (`this.logger.log()` → `log`) no longer cross-file resolved. Go package-qualified calls (`pkg.Func()`) correctly preserved. Affects JS/TS, Go, Rust, Swift, Kotlin, Scala, PHP, C++, C#, Zig, Elixir.
- Fix: `concept` file_type no longer triggers validation warnings (#601)
- Fix: `graphify update` remembers scan root via `graphify-out/.graphify_root` — no path argument needed on subsequent runs
- Fix: Kimi K2.6 temperature 400 error — temperature param is now skipped for Kimi backends (model enforces its own fixed value) (#610)
- Fix: community labels deleted in Step 9 cleanup — `.graphify_labels.json` is now preserved so wiki/obsidian/HTML retain human-readable names after re-cluster (#608)
- Fix: `NameError: name '_os' is not defined` in `graphify update` Kimi tip (#612)
- Fix: `SyntaxWarning` in `__main__.py` for shell glob pattern with backslash escapes
- Fix: Python upper bound removed — `requires-python = ">=3.10"` now supports Python 3.14+ (#607)
## 0.5.4 (2026-04-28)
- Fix: SSRF DNS rebinding — `safe_fetch` now patches `socket.getaddrinfo` for the full request duration (#591)
- Fix: yt-dlp SSRF bypass — `download_audio` now calls `validate_url` before handing URL to yt-dlp (#592)
## 0.5.3 (2026-04-27)
- Fix: cache namespace — AST and semantic entries now live in `cache/ast/` and `cache/semantic/` subdirectories; flat entries read as migration fallback
## 0.5.2 (2026-04-26)
- Fix: PreToolUse hook now matches on `Bash` instead of `Glob|Grep` for Claude Code v2.1.117+
## 0.5.1 (2026-04-25)
- Fix: node ID collision for same-named files in different directories
- Fix: `source_file` paths relativized before return so `graph.json` is portable
- Fix: desync guard — `to_json()` returns bool; report only written on successful JSON write
- Feat: TypeScript `@/` path aliases resolved via `tsconfig.json`
- Feat: Show All / Hide All buttons in HTML community panel
## 0.5.0 (2026-04-24)
- Feat: `graphify clone <github-url>` — clone and graph any public repo
- Feat: `graphify merge-graphs` — combine multiple `graph.json` outputs into one cross-repo graph
- Feat: `CLAUDE_CONFIG_DIR` support in `graphify install`
- Feat: shrink guard — `to_json()` refuses to overwrite with a smaller graph
- Feat: `build_merge()` for safe incremental updates
- Feat: duplicate node deduplication via `deduplicate_by_label()`
- Fix: `graphify-out/` excluded from source scanning
## 0.4.23 (2026-04-18)
- Fix: stale skill version warning persists after running `graphify install` when multiple platforms were previously installed — `graphify install` now refreshes `.graphify_version` in all other known skill directories so the warning clears across the board (#178)
+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"]
+491 -285
View File
@@ -3,115 +3,134 @@
</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.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=v4" 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://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" 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>
</p>
<p align="center">
<a href="https://star-history.com/#safishamsi/graphify&Date">
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="600"/>
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
</a>
</p>
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, or Google Antigravity - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
Type `/graphify` in your AI coding assistant and it maps your entire project — code, docs, PDFs, images, videos — into a knowledge graph you can query instead of grepping through files.
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
> Andrej Karpathy keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. graphify is the answer to that problem - 71.5x fewer tokens per query vs reading the raw files, persistent across sessions, honest about what it found vs guessed.
Works in Claude Code, Codex, OpenCode, 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 . # works on any folder - your codebase, notes, papers, anything
/graphify .
```
That's it. You get three files:
```
graphify-out/
├── graph.html interactive graph - open in any browser, click nodes, search, filter by community
├── GRAPH_REPORT.md god nodes, surprising connections, suggested questions
├── graph.json persistent graph - query weeks later without re-reading
└── cache/ SHA256 cache - re-runs only process changed files
├── graph.html open in any browser — click nodes, filter, search
├── GRAPH_REPORT.md the highlights: key concepts, surprising connections, suggested questions
└── graph.json the full graph — query it anytime without re-reading your files
```
Add a `.graphifyignore` file to exclude folders you don't want in the graph:
For a readable architecture page with Mermaid call-flow diagrams, run:
```
# .graphifyignore
vendor/
node_modules/
dist/
*.generated.py
```bash
graphify export callflow-html
```
Same syntax as `.gitignore`. You can keep a single `.graphifyignore` at your repo root — patterns work correctly even when graphify is run on a subfolder.
---
## What's new in v0.5.3
## Prerequisites
- **Cache namespace fix** — AST and semantic cache entries now live in separate `cache/ast/` and `cache/semantic/` subdirectories. Previously both used the same flat `cache/` directory, causing semantic results to silently overwrite AST entries for code files on mixed code+docs corpora, which triggered the shrink guard on every subsequent `graphify update`. Existing flat cache entries are read as a migration fallback so no cache is lost on upgrade.
| Requirement | Minimum | Check | Install |
|---|---|---|---|
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
| uv *(recommended)* | any | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| pipx *(alternative)* | any | `pipx --version` | `pip install pipx` |
## What's new in v0.5.2
**macOS quick install (Homebrew):**
```bash
brew install python@3.12 uv
```
- **Hook fix for Claude Code v2.1.117+** — the PreToolUse hook now matches on `Bash` instead of `Glob|Grep`. Claude Code v2.1.117 removed dedicated Grep/Glob tools; searches now go through Bash. The hook inspects the command string and only fires on search-like calls (grep, rg, find, fd etc.), so it does not trigger on every shell command.
**Windows quick install:**
```powershell
winget install astral-sh.uv
```
## What's new in v0.5.1
**Ubuntu/Debian:**
```bash
sudo apt install python3.12 python3-pip pipx
# or install uv:
curl -LsSf https://astral.sh/uv/install.sh | sh
```
- **Node ID collision fix** — files sharing the same name in different directories (e.g. two `utils.py` files) now get unique IDs by prefixing the parent directory name.
- **Portable `source_file` paths** — `extract()` now relativizes all `source_file` fields before returning, so `graph.json` is portable across machines and git worktrees.
- **Desync guard** — `to_json()` returns a boolean; `graphify update` only writes `GRAPH_REPORT.md` and `graph.html` if the JSON write succeeded (shrink guard fired = no stale report).
- **TypeScript path aliases** — `@/` and other `compilerOptions.paths` aliases in `tsconfig.json` are now resolved to real file nodes instead of being dropped as external packages.
- **Show All / Hide All** — community panel in the HTML visualization now has Show All and Hide All buttons.
- **Skill prompt fixes** — rationale is stored as a node attribute (not a spurious fragment node); `calls` edge direction is now explicitly enforced (caller → callee).
- **Hook and tooling fixes** — `~` expansion in `core.hooksPath`, correct `.gitignore` inline comment placement, `# nosec` annotations on file write sinks.
## What's new in v0.5.0
- **`graphify clone <github-url>`** — clone any public GitHub repo and run the full pipeline on it. Clones to `~/.graphify/repos/<owner>/<repo>`, reuses existing clones on repeat runs (`git pull`). Supports `--branch` and `--out`.
- **`graphify merge-graphs`** — combine two or more `graph.json` outputs into one cross-repo graph. Each node is tagged with its source repo. Useful for mapping dependencies across multiple projects.
- **`CLAUDE_CONFIG_DIR` support** — `graphify install` now respects the `CLAUDE_CONFIG_DIR` environment variable when installing the Claude Code skill, instead of always writing to `~/.claude`.
- **Shrink guard** — `to_json()` refuses to overwrite `graph.json` with a smaller graph. Prevents silent data loss when `--update` is called with a partial chunk list.
- **`build_merge()`** — new library function for safe incremental updates: loads existing graph, merges new chunks, optionally prunes deleted-file nodes, never shrinks.
- **Duplicate node deduplication** — `deduplicate_by_label()` collapses nodes that share a normalised label (e.g. from parallel subagents generating `achille_varzi` and `achille_varzi_c4`). Chunk-suffix contamination is also blocked at the prompt level.
- **Bug fixes** — `graphify-out/` is now excluded from source scanning so generated artifacts never trigger false incremental refresh pressure.
## How it works
graphify runs in three passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, video and audio files are transcribed locally with faster-whisper using a domain-aware prompt derived from corpus god nodes — transcripts are cached so re-runs are instant. Third, Claude subagents run in parallel over docs, papers, images, and transcripts to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
**Clustering is graph-topology-based — no embeddings.** Leiden finds communities by edge density. The semantic similarity edges that Claude extracts (`semantically_similar_to`, marked INFERRED) are already in the graph, so they influence community detection directly. The graph structure is the similarity signal — no separate embedding step or vector database needed.
Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED` (reasonable inference, with a confidence score), or `AMBIGUOUS` (flagged for review). You always know what was found vs guessed.
---
## Install
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes, or [Google Antigravity](https://antigravity.google)
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
**Step 1 — install the package:**
```bash
# Recommended — works on Mac and Linux with no PATH setup needed
uv tool install graphifyy && graphify install
# or with pipx
pipx install graphifyy && graphify install
# or plain pip
pip install graphifyy && graphify install
# Recommended (uv puts graphify on PATH automatically):
uv tool install graphifyy
# Alternatives:
pipx install graphifyy
pip install graphifyy # may need PATH setup — see note below
```
> **Official package:** The PyPI package is named `graphifyy` (install with `pip install graphifyy`). Other packages named `graphify*` on PyPI are not affiliated with this project. The only official repository is [safishamsi/graphify](https://github.com/safishamsi/graphify). The CLI and skill command are still `graphify`.
**Step 2 — register the skill with your AI assistant:**
> **`graphify: command not found`?** Use `uv tool install graphifyy` (recommended) or `pipx install graphifyy` — both put the CLI in a managed location that's automatically on PATH. With plain `pip`, you may need to add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify` instead. On Windows, pip scripts land in `%APPDATA%\Python\PythonXY\Scripts`.
```bash
graphify install
```
### Platform support
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` (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` |
@@ -121,29 +140,58 @@ pip install graphifyy && graphify install
| 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` |
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
Codex users also 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.
Then open your AI coding assistant and type:
> Codex uses `$graphify` instead of `/graphify`.
```
/graphify .
```
### Optional extras
Note: Codex uses `$` instead of `/` for skill calling, so type `$graphify .` instead.
Install only what you need:
### Make your assistant always use the graph (recommended)
| Extra | What it adds | Install |
|---|---|---|
| `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]"` |
| `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]"` |
After building a graph, run this once in your project:
---
## Make your assistant always use the graph
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` |
@@ -154,181 +202,336 @@ After building a graph, run this once in your project:
| Cursor | `graphify cursor install` |
| 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` |
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
This writes a small config file that tells your assistant to 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 a **PreToolUse hook** (`.codebuddy/settings.json`) that fires before every Glob and Grep call.
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
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.
**Gemini CLI** copies the skill to `~/.gemini/skills/graphify/SKILL.md`, writes a `GEMINI.md` section, and installs a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls — same always-on mechanism as Claude Code.
## What's in the report
**Aider, OpenClaw, Factory Droid, Trae, and Hermes** write the same rules to `AGENTS.md` in your project root and copy the skill to the platform's global skill directory. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
- **Surprising connections** — links between things that live in different files or modules. Ranked by how unexpected they are.
- **The "why"** — inline comments (`# NOTE:`, `# WHY:`, `# HACK:`), docstrings, and design rationale from docs are extracted as separate nodes linked to the code they explain.
- **Suggested questions** — 4–5 questions the graph is uniquely positioned to answer.
- **Confidence tags** — every inferred relationship is marked `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`. You always know what was found vs guessed.
**Kiro IDE/CLI** writes the skill to `.kiro/skills/graphify/SKILL.md` (invoked via `/graphify`) and a steering file to `.kiro/steering/graphify.md` with `inclusion: always` — Kiro injects this into every conversation automatically, no hook needed.
---
**Google Antigravity** writes `.agents/rules/graphify.md` (always-on rules) and `.agents/workflows/graphify.md` (registers `/graphify` as a slash command). No hook equivalent exists in Antigravity — rules are the always-on mechanism.
## What files it handles
**GitHub Copilot CLI** copies the skill to `~/.copilot/skills/graphify/SKILL.md`. Run `graphify copilot install` to set it up.
| Type | Extensions |
|------|-----------|
| Code (28 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 .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 .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 |
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
| 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 `uv tool install graphifyy[video]`) |
| YouTube / URLs | any video URL (requires `uv tool install graphifyy[video]`) |
**VS Code Copilot Chat** installs a Python-only skill (works on Windows PowerShell and macOS/Linux alike) and writes `.github/copilot-instructions.md` in your project root — VS Code reads this automatically every session, making graph context always-on without any hook mechanism. Run `graphify vscode install`. Note: this configures the chat panel in VS Code, not the Copilot CLI terminal tool.
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
Google Drive for desktop `.gdoc`, `.gsheet`, and `.gslides` files are shortcut
pointers, not document content. To include native Google Docs, Sheets, and Slides
in a headless extraction, install and authenticate the
[`gws` CLI](https://github.com/googleworkspace/cli), then run:
**Always-on vs explicit trigger — what's the difference?**
```bash
uv tool install "graphifyy[google]" # needed for Google Sheets table rendering
gws auth login -s drive
graphify extract ./docs --google-workspace
```
The always-on hook surfaces `GRAPH_REPORT.md` — a one-page summary of god nodes, communities, and surprising connections. Your assistant reads this before searching files, so it navigates by structure instead of keyword matching. That covers most everyday questions.
You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into
`graphify-out/converted/` as Markdown sidecars, then extracts those files.
`/graphify query`, `/graphify path`, and `/graphify explain` go deeper: they traverse the raw `graph.json` hop by hop, trace exact paths between nodes, and surface edge-level detail (relation type, confidence score, source location). Use them when you want a specific question answered from the graph rather than a general orientation.
---
Think of it this way: the always-on hook gives your assistant a map. The `/graphify` commands let it navigate the map precisely.
## Common commands
### Team workflows
```bash
/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 # Mermaid architecture/call-flow HTML (auto-regenerates on every git commit if hook is installed)
`graphify-out/` is designed to be committed to git so every teammate starts with a fresh map.
/graphify query "what connects auth to the database?"
/graphify path "UserService" "DatabasePool"
/graphify explain "RateLimiter"
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper and add it
/graphify add <youtube-url> # transcribe and add a video
graphify hook install # auto-rebuild on git commit
graphify merge-graphs a.json b.json # combine two graphs
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.
---
## Ignoring files
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation.
**`.gitignore` is respected automatically.** If no `.graphifyignore` is present in a directory, graphify falls back to the `.gitignore` in that directory. If both exist, `.graphifyignore` takes priority. Subdirectory scoping works the same way as git — an ignore file only affects its own subtree.
```
# .graphifyignore
node_modules/
dist/
*.generated.py
# only index src/, ignore everything else
*
!src/
!src/**
```
---
## Team setup
`graphify-out/` is meant to be committed to git so everyone on the team starts with a map.
**Recommended `.gitignore` additions:**
```
# keep graph outputs, skip heavy/local-only files
# optional: commit for shared extraction speed, skip to keep repo small
graphify-out/cache/
# mtime-based, invalid after git clone - always gitignore this
graphify-out/manifest.json
# local token tracking, not useful to share
graphify-out/cost.json
graphify-out/cost.json # local only
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
```
**Shared setup:**
1. One person runs `/graphify .` to build the initial graph and commits `graphify-out/`.
2. Everyone else pulls — their assistant reads `GRAPH_REPORT.md` immediately with no extra steps.
3. Install the post-commit hook (`graphify hook install`) so the graph rebuilds automatically after code changes — no LLM calls needed for code-only updates.
4. For doc/paper changes, whoever edits the files runs `/graphify --update` to refresh semantic nodes.
> `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.
**Excluding paths** — create `.graphifyignore` in your project root (same syntax as `.gitignore`). Files matching those patterns are skipped during detection and extraction.
**Workflow:**
1. One person runs `/graphify .` and commits `graphify-out/`.
2. Everyone pulls — their assistant reads the graph immediately.
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost). This also sets up a git merge driver so `graph.json` is never left with conflict markers — two devs committing in parallel get their graphs union-merged automatically.
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
```
# .graphifyignore example
AGENTS.md # graphify install files — don't extract your own instructions as knowledge
CLAUDE.md
GEMINI.md
.gemini/
.opencode/
docs/translations/ # generated content you don't want in the graph
```
---
## Using `graph.json` with an LLM
`graph.json` is not meant to be pasted into a prompt all at once. The useful
workflow is:
1. Start with `graphify-out/GRAPH_REPORT.md` for the high-level overview.
2. Use `graphify query` to pull a smaller subgraph for the specific question
you want to answer.
3. Give that focused output to your assistant instead of dumping the full raw
corpus.
For example, after running graphify on a project:
## Using the graph directly
```bash
graphify query "show the auth flow" --graph graphify-out/graph.json
# query the graph from the terminal
graphify query "show the auth flow"
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
# expose the graph as an MCP server (for repeated tool-call access)
python -m graphify.serve graphify-out/graph.json
# 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 output includes node labels, edge types, confidence tags, source files, and
source locations. That makes it a good intermediate context block for an LLM:
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
```text
Use this graph query output to answer the question. Prefer the graph structure
over guessing, and cite the source files when possible.
```
### Shared HTTP server
If your assistant supports tool calling or MCP, use the graph directly instead
of pasting text. graphify can expose `graph.json` as an MCP server:
`--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
python -m graphify.serve graphify-out/graph.json
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"
```
That gives the assistant structured graph access for repeated queries such as
`query_graph`, `get_node`, `get_neighbors`, and `shortest_path`.
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Install into a project venv to avoid PEP 668 conflicts, and use the full venv path in your `.mcp.json`:
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Use a venv to avoid conflicts:
> ```bash
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
> ```
> ```json
> { "mcpServers": { "graphify": { "type": "stdio", "command": ".venv/bin/python3", "args": ["-m", "graphify.serve", "graphify-out/graph.json"] } } }
> ```
> Also note: the PyPI package is `graphifyy` (double-y) — `pip install graphify` installs an unrelated package.
<details>
<summary>Manual install (curl)</summary>
---
## Environment variables
These are only needed for **headless / CI extraction** (`graphify extract`). When running via the `/graphify` skill inside your IDE, the model API is provided by your IDE session — no extra keys needed.
| Variable | Used for | When required |
|---|---|---|
| `ANTHROPIC_API_KEY` | Claude (Anthropic) backend | `--backend claude` |
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Google Gemini backend | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` |
| `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` | 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 |
---
## Privacy
- **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), `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.
---
## Troubleshooting
**`graphify: command not found` after `pip install graphifyy`**
pip installs scripts to a user bin directory that may not be on your PATH. Fix:
- macOS: add `~/Library/Python/3.x/bin` to your PATH in `~/.zshrc`
- Linux: add `~/.local/bin` to your PATH in `~/.bashrc`
- Or use `uv tool install graphifyy` / `pipx install graphifyy` — both manage PATH automatically.
**`python -m graphify` works but `graphify` command doesn't**
Your shell's PATH doesn't include the Python scripts directory. Use `uv` or `pipx` instead of plain `pip`.
**`/graphify .` causes "path not recognized" in PowerShell**
PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash) on Windows.
**Graph has fewer nodes after `--update` or rebuild**
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)**
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
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v4/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
graphify extract . --force
```
Add to `~/.claude/CLAUDE.md`:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
**Ollama runs out of VRAM / context window exceeded**
The KV-cache window is auto-sized but may be too large for your GPU. Reduce it:
```bash
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
```
</details>
**Graph HTML is too large to open in a browser (>5000 nodes)**
Skip HTML generation and use the JSON directly:
```bash
graphify cluster-only ./my-project --no-viz
graphify query "..."
```
## Usage
**`graph.json` has conflict markers after two devs commit at once**
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, 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
```
**Skill version mismatch warning in your IDE**
Your installed graphify version is different from the skill file. Update:
```bash
uv tool upgrade graphifyy
graphify install # overwrites the skill file
```
---
## Full command reference
```
/graphify # run on current directory
/graphify ./raw # run on a specific folder
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
/graphify ./raw --update # re-extract only changed files, merge into existing graph
/graphify ./raw --directed # build directed graph (preserves edge direction: source→target)
/graphify ./raw --cluster-only # rerun clustering on existing graph, no re-extraction
/graphify ./raw --no-viz # skip HTML, just produce report + JSON
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # write vault to a specific directory
/graphify ./raw --mode deep # more aggressive relationship extraction
/graphify ./raw --update # re-extract only changed files
/graphify ./raw --directed # preserve edge direction
/graphify ./raw --cluster-only # rerun clustering on existing graph
/graphify ./raw --no-viz # skip HTML visualization
/graphify ./raw --obsidian # generate Obsidian vault
/graphify ./raw --wiki # build agent-crawlable markdown wiki
/graphify ./raw --svg # export graph.svg
/graphify ./raw --graphml # export for Gephi / yEd
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687
/graphify ./raw --watch # auto-sync as files change
/graphify ./raw --mcp # start MCP stdio server
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
/graphify add https://x.com/karpathy/status/... # fetch a tweet
/graphify add <video-url> # download audio, transcribe, add to graph
/graphify add https://... --author "Name" # tag the original author
/graphify add https://... --contributor "Name" # tag who added it to the corpus
/graphify add https://arxiv.org/abs/1706.03762
/graphify add <video-url>
/graphify add https://... --author "Name" --contributor "Name"
/graphify query "what connects attention to the optimizer?"
/graphify query "what connects attention to the optimizer?" --dfs # trace a specific path
/graphify query "what connects attention to the optimizer?" --budget 1500 # cap at N tokens
/graphify query "..." --dfs --budget 1500
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
/graphify ./raw --watch # auto-sync graph as files change (code: instant, docs: notifies you)
/graphify ./raw --wiki # build agent-crawlable wiki (index.md + article per community)
/graphify ./raw --svg # export graph.svg
/graphify ./raw --graphml # export graph.graphml (Gephi, yEd)
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687 # push directly to a running Neo4j instance
/graphify ./raw --mcp # start MCP stdio server
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
# git hooks - platform-agnostic, rebuild graph on commit and branch switch
graphify hook install
graphify hook install # post-commit + post-checkout hooks
graphify hook uninstall
graphify hook status
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify 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)
@@ -338,150 +541,153 @@ 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
# query and navigate the graph directly from the terminal (no AI assistant needed)
graphify query "what connects attention to the optimizer?"
graphify query "show the auth flow" --dfs
graphify query "what is CfgNode?" --budget 500
graphify query "..." --graph path/to/graph.json
graphify path "DigestAuth" "Response" # shortest path between two nodes
graphify explain "SwinTransformer" # plain-language explanation of a node
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, 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
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 ./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)
graphify extract ./docs --global --as myrepo # extract and register into the cross-project global graph
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # raise output cap for dense corpora
# add content and update the graph from the terminal
graphify add https://arxiv.org/abs/1706.03762 # fetch paper, save to ./raw, update graph
graphify add https://... --author "Name" --contributor "Name"
graphify export callflow-html # graphify-out/<project>-callflow.html
graphify export callflow-html --max-sections 8 # cap generated architecture sections
graphify export callflow-html --output docs/arch.html
graphify export callflow-html ./some-repo/graphify-out
# clone any GitHub repo and run the full pipeline on it
graphify clone https://github.com/karpathy/nanoGPT # clones to ~/.graphify/repos/karpathy/nanoGPT
graphify clone https://github.com/org/repo --branch dev --out ./my-clone
graphify global add graphify-out/graph.json myrepo # register a project graph into ~/.graphify/global.json
graphify global remove myrepo # remove a project from the global graph
graphify global list # show all registered repos + node/edge counts
graphify global path # print path to the global graph file
# cross-repo graphs — merge two or more graph.json outputs into one
graphify merge-graphs repo1/graphify-out/graph.json repo2/graphify-out/graph.json
graphify merge-graphs g1.json g2.json g3.json --out cross-repo.json
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
# incremental update and maintenance
graphify watch ./src # auto-rebuild on code changes
graphify check-update ./src # check if semantic re-extraction is pending (cron-safe)
graphify update ./src # re-extract code files, no LLM needed
graphify cluster-only ./my-project # rerun clustering on existing graph.json
graphify clone https://github.com/karpathy/nanoGPT
graphify merge-graphs a.json b.json --out merged.json
graphify --version # print installed version
graphify watch ./src
graphify check-update ./src
graphify update ./src
graphify update ./src --no-cluster # skip reclustering, write raw AST graph only
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 label ./my-project # (re)name communities with the configured backend
graphify label ./my-project --backend=openai # force a specific backend
```
Works with any mix of file types:
> **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.
| Type | Extensions | Extraction |
|------|-----------|------------|
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + Java extends/implements + docstring/comment rationale |
| Docs | `.md .mdx .html .txt .rst` | Concepts + relationships + design rationale via Claude |
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
| Papers | `.pdf` | Citation mining + concept extraction |
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
| Video / Audio | `.mp4 .mov .mkv .webm .avi .m4v .mp3 .wav .m4a .ogg` | Transcribed locally with faster-whisper, transcript fed into Claude extraction (requires `pip install graphifyy[video]`) |
| YouTube / URLs | any video URL | Audio downloaded via yt-dlp, then same Whisper pipeline (requires `pip install graphifyy[video]`) |
---
## Video and audio corpus
## Learn more
Drop video or audio files into your corpus folder alongside your code and docs — graphify picks them up automatically:
- [How it works](docs/how-it-works.md) — the extraction pipeline, community detection, confidence scoring, benchmarks
- [ARCHITECTURE.md](ARCHITECTURE.md) — module breakdown, how to add a language
- [Optional integrations](docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
```bash
pip install 'graphifyy[video]' # one-time setup
/graphify ./my-corpus # transcribes any video/audio files it finds
```
Add a YouTube video (or any public video URL) directly:
```bash
/graphify add <video-url>
```
yt-dlp downloads audio-only (fast, small), Whisper transcribes it locally, and the transcript is fed into the same extraction pipeline as your other docs. Transcripts are cached in `graphify-out/transcripts/` so re-runs skip already-transcribed files.
For better accuracy on technical content, use a larger model:
```bash
/graphify ./my-corpus --whisper-model medium
```
Audio never leaves your machine. All transcription runs locally.
## What you get
**God nodes** - highest-degree concepts (what everything connects through)
**Surprising connections** - ranked by composite score. Code-paper edges rank higher than code-code. Each result includes a plain-English why.
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
**The "why"** - docstrings, inline comments (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), and design rationale from docs are extracted as `rationale_for` nodes. Not just what the code does - why it was written that way.
**Confidence scores** - every INFERRED edge has a `confidence_score` (0.0-1.0). You know not just what was guessed but how confident the model was. EXTRACTED edges are always 1.0.
**Semantic similarity edges** - cross-file conceptual links with no structural connection. Two functions solving the same problem without calling each other, a class in code and a concept in a paper describing the same algorithm.
**Hyperedges** - group relationships connecting 3+ nodes that pairwise edges can't express. All classes implementing a shared protocol, all functions in an auth flow, all concepts from a paper section forming one idea.
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files. The first run extracts and builds the graph (this costs tokens). Every subsequent query reads the compact graph instead of raw files — that's where the savings compound. The SHA256 cache means re-runs only re-process changed files.
**Auto-sync** (`--watch`) - run in a background terminal and the graph updates itself as your codebase changes. Code file saves trigger an instant rebuild (AST only, no LLM). Doc/image changes notify you to run `--update` for the LLM re-pass.
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. If a rebuild fails, the hook exits with a non-zero code so git surfaces the error instead of silently continuing. No background process needed.
**Wiki** (`--wiki`) - Wikipedia-style markdown articles per community and god node, with an `index.md` entry point. Point any agent at `index.md` and it can navigate the knowledge base by reading files instead of parsing JSON.
## Worked examples
| Corpus | Files | Reduction | Output |
|--------|-------|-----------|--------|
| Karpathy repos + 5 papers + 4 images | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
| graphify source + Transformer paper | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
| httpx (synthetic Python library) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
Token reduction scales with corpus size. 6 files fits in a context window anyway, so graph value there is structural clarity, not compression. At 52 files (code + papers + images) you get 71x+. Each `worked/` folder has the raw input files and the actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify the numbers.
## Privacy
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
## Tech stack
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
---
## Built on graphify — Penpax
[**Penpax**](https://safishamsi.github.io/penpax.ai) is the enterprise layer on top of graphify. Where graphify turns a folder of files into a knowledge graph, Penpax applies the same graph to your entire working life — continuously.
[**Penpax**](https://graphifylabs.ai) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working life: meetings, browser history, emails, files, and code, updating continuously in the background.
| | graphify | Penpax |
|---|---|---|
| Input | A folder of files | Browser history, meetings, emails, files, code — everything |
| Runs | On demand | Continuously in the background |
| Scope | A project | Your entire working life |
| Query | CLI / MCP / AI skill | Natural language, always on |
| Privacy | Local by default | Fully on-device, no cloud |
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
Built for lawyers, consultants, executives, doctors, researchers — anyone whose work lives across hundreds of conversations and documents they can never fully reconstruct.
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
**Free trial launching soon.** [Join the waitlist →](https://safishamsi.github.io/penpax.ai)
## What we are building next
graphify is the graph layer. Penpax is the always-on layer on top of it — an on-device digital twin that connects your meetings, browser history, files, emails, and code into one continuously updating knowledge graph. No cloud, no training on your data. [Join the waitlist.](https://safishamsi.github.io/penpax.ai)
---
<details>
<summary>Contributing</summary>
**Worked examples** are the most trust-building contribution. Run `/graphify` on a real corpus, save output to `worked/{slug}/`, write an honest `review.md` evaluating what the graph got right and wrong, submit a PR.
### Development setup
**Extraction bugs** - open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or invented.
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 v8 # active development branch
# 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
uv run graphify --version
uv run python -c "import graphify; print(graphify.__file__)"
```
### Running tests
```bash
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 `v8` branch.
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
- 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
**Worked examples** are the most useful contribution. Run `/graphify` on a real corpus, save the output to `worked/{slug}/`, write an honest `review.md` covering what the graph got right and wrong, and open a PR.
**Extraction bugs** — open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or wrong.
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
+138
View File
@@ -0,0 +1,138 @@
# Docker MCP Toolkit + SQLite MCP server
A reproducible runbook for installing the **SQLite MCP server** into the
[Docker MCP Toolkit](https://docs.docker.com/desktop/features/mcp/) so any
connected MCP client (Claude Code, Claude Desktop, Cursor, VS Code, etc.) gains
six SQLite tools: `read_query`, `write_query`, `create_table`, `list_tables`,
`describe_table`, and `append_insight`.
This document is *not* required to use graphify — it lives here as a known-good
recipe for users who want a lightweight, persistent SQL workspace exposed to
their AI clients alongside graphify's knowledge-graph tools.
## Why SQLite (and not `sqlite-mcp-server`)
At time of writing the catalog ships two SQLite MCP images:
| Catalog name | Image | Status |
| ------------------- | ---------------------- | ------ |
| `SQLite` | `mcp/sqlite` | Marked "Archived" in catalog metadata, but **boots and serves correctly** |
| `sqlite-mcp-server` | `mcp/sqlite-mcp-server`| **Broken**: entrypoint `/app/.venv/bin/mcp-server-sqlite` does not exist in the published layer |
Use `SQLite` (`mcp/sqlite`) until the newer image is fixed upstream.
## Prerequisites
- Docker Desktop running and healthy
- `docker info` returns a `Server Version`
- Public socket present at `/var/run/docker.sock` (or its symlink to
`~/.docker/run/docker.sock`)
- Docker MCP Toolkit CLI plugin (`docker mcp`)
- Bundled with recent Docker Desktop releases; `docker mcp --version` should
print a version string
## Install
```bash
# Add the working SQLite server to the default MCP profile
docker mcp profile server add default \
--server catalog://mcp/docker-mcp-catalog/SQLite
# Pre-pull the image so the first tool call is fast
docker pull mcp/sqlite:latest
```
Verify the profile now contains both `fetch` (built-in) and `SQLite`:
```bash
docker mcp profile show default | grep -E '^[[:space:]]+name:'
```
Expected output:
```
name: fetch
name: SQLite
```
The Docker MCP gateway should now expose 6 additional tools:
```bash
docker mcp tools count
# → 15 tools (was 9 before adding SQLite)
```
## Smoke test
The CLI can call MCP tools directly (each call boots a fresh gateway, ~5s
overhead per call):
```bash
docker mcp tools call list_tables
docker mcp tools call create_table \
query='CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP)'
docker mcp tools call write_query \
query="INSERT INTO notes(body) VALUES ('first row'), ('second row')"
docker mcp tools call read_query \
query='SELECT * FROM notes ORDER BY id'
docker mcp tools call describe_table table_name=notes
docker mcp tools call append_insight insight='3 rows inserted; aggregates work.'
```
`read_query` should return the inserted rows with timestamps.
## Storage layout
Database file lives in a Docker named volume `mcp-sqlite`, mounted at `/mcp`
inside containers:
```
mcp-sqlite (named volume) → /mcp/db.sqlite
```
Inspect from the host:
```bash
docker volume inspect mcp-sqlite
docker run --rm -v mcp-sqlite:/mcp:ro alpine ls -la /mcp
docker run --rm -v mcp-sqlite:/mcp:ro keinos/sqlite3 \
sqlite3 /mcp/db.sqlite '.schema'
```
The volume persists across `docker run --rm` invocations of the SQLite MCP
container, so writes from one MCP tool call are visible to the next.
## Wiring into MCP clients
Connect once per client; the gateway exposes every server in the active profile:
```bash
docker mcp client connect claude-code # already connected for many users
docker mcp client connect cursor
docker mcp client connect vscode
docker mcp client connect claude-desktop
# Supported: claude-code, claude-desktop, cline, codex, continue, crush,
# cursor, gemini, goose, gordon, kiro, lmstudio, opencode, sema4,
# vscode, zed
```
Verify wiring:
```bash
docker mcp client ls
```
## Uninstall / reset
```bash
# Remove server from the profile
docker mcp profile server remove default SQLite
# Drop the database volume (irreversible)
docker volume rm mcp-sqlite
# Remove the image
docker rmi mcp/sqlite:latest
```
## Troubleshooting
- **`starting client: calling "initialize": EOF`** — the requested server
failed its MCP handshake. Run the image directly to see the error:
```bash
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"smoke","version":"0.0"}}}\n' \
| docker run --rm -i -v mcp-sqlite:/mcp <image-ref> --db-path /mcp/db.sqlite
```
Common causes: missing entrypoint binary in the image (the
`sqlite-mcp-server` failure mode) or missing required env/secrets.
- **`cannot use --enable-all-servers with --servers flag`** — these gateway
args are mutually exclusive; pick one.
- **No new tools appear in `docker mcp tools count` after install** — the
gateway may be running with `dynamic-tools` enabled, exposing only meta-tools
(`mcp-add`, `mcp-find`, …) until a profile is activated mid-session. Either
invoke `docker mcp tools` (which spins up an ephemeral gateway against the
default profile) or call `mcp-activate-profile` from inside an MCP session.
+98
View File
@@ -0,0 +1,98 @@
# How graphify works
## The three passes
graphify processes your files in three passes:
**Pass 1 — Code structure (free, no API calls)**
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. 25 languages supported. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
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.
**Pass 3 — Docs, papers, images (Claude subagents, costs tokens)**
Claude runs in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
Before Pass 3, optional converters turn supported pointer/binary formats into
Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
`.xlsx`) use the `[office]` extra. Google Workspace shortcuts (`.gdoc`,
`.gsheet`, `.gslides`) are opt-in with `--google-workspace` or
`GRAPHIFY_GOOGLE_WORKSPACE=1` and require an authenticated `gws` CLI.
---
## How community detection works
Communities are found using the [Leiden algorithm](https://www.nature.com/articles/s41598-019-41695-z) — a graph-clustering method that groups nodes by edge density. Nodes with many connections between them end up in the same community.
**No embeddings needed.** The semantic similarity edges that Claude extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
---
## Confidence tagging
Every relationship is tagged with one of three labels:
| Tag | Meaning |
|-----|---------|
| `EXTRACTED` | Found directly in the source (e.g. a function call, an import) |
| `INFERRED` | A reasonable inference Claude made, with a `confidence_score` (0.0–1.0) |
| `AMBIGUOUS` | Uncertain — flagged in the report for manual review |
EXTRACTED edges always have confidence 1.0. INFERRED edges use a discrete rubric:
- **0.95** — near-certain (explicit cross-file reference, one plausible target)
- **0.85** — strong evidence (naming + context align)
- **0.75** — reasonable (contextual but not explicit)
- **0.65** — weak (naming similarity only)
- **0.55** — speculative
---
## Token benchmark
The first run extracts and builds the graph — this costs tokens. Every subsequent query reads the compact graph instead of raw files. That's where the savings compound.
On a mixed corpus (Karpathy repos + 5 papers + 4 images, 52 files): **71.5x fewer tokens per query** vs reading the raw files directly.
| Corpus | Files | Reduction |
|--------|-------|-----------|
| Karpathy repos + papers + images | 52 | **71.5x** |
| graphify source + Transformer paper | 4 | **5.4x** |
| httpx (synthetic Python library) | 6 | ~1x |
Token reduction scales with corpus size. Six files already fits in a context window — the graph value there is structural clarity, not compression. At 52 files the savings compound quickly.
Each `worked/` folder in the repo has the raw input files and actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify.
---
## Parallel extraction
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel Claude subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
---
## SHA256 cache
Every extracted file is fingerprinted by content hash. Re-runs skip unchanged files entirely — only new or modified files go through extraction again. The cache lives in `graphify-out/cache/`.
---
## The graph format
The output `graph.json` uses NetworkX's node-link format. Each node has:
- `id` — stable identifier
- `label` — human-readable name
- `file_type` — `code`, `document`, `paper`, `image`, `rationale`
- `source_file` — where it came from
Each edge has:
- `source`, `target` — node IDs
- `relation` — verb phrase (e.g. `calls`, `imports`, `implements`, `semantically_similar_to`)
- `confidence` — `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`
- `confidence_score` — float (INFERRED only)
- `source_file` — where the relationship was found
Hyperedges (group relationships connecting 3+ nodes) live in `G.graph["hyperedges"]`.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,133 @@
# Design: Incremental Updates + Entity Deduplication
**Date:** 2026-05-04
**Issues:** #698 (incremental updates), entity deduplication (no issue, proactive)
**Branch:** v7
---
## Problem
1. `graphify extract` rebuilds the full graph from scratch every run — re-sends all files to the LLM regardless of what changed. For a 1000-file Markdown corpus updated daily this is expensive.
2. LLM extraction is chunk-by-chunk — the same real-world concept can get different labels across chunks (`AuthManager`, `AuthenticationManager`, `auth_mgr`). No semantic dedup exists beyond exact string normalization.
---
## Pipeline (every `graphify extract` run)
```
detect (full or incremental, auto-detected)
↓
AST extract (code files, AST cache-aware)
↓
Semantic LLM extract (doc/paper/image files, semantic cache-aware)
↓
build_merge (merge into existing graph, prune deleted nodes)
↓
deduplicate_entities (normalize → entropy gate → MinHash/LSH → Jaro-Winkler → community boost → optional LLM)
↓
cluster (full graph, always re-run)
↓
score_all + god_nodes + surprising_connections
↓
write graph.json + .graphify_analysis.json + manifest.json
```
---
## Feature 1: Incremental Updates
### Auto-detection
If `graphify-out/manifest.json` + `graphify-out/graph.json` both exist → incremental mode. No flag needed. First run is always full.
### Incremental mode changes
- `detect_incremental(target)` instead of `detect(target)` — returns `new_files`, `unchanged_files`, `deleted_files`
- Only `new_files` go through AST + LLM extraction
- `build_merge(new_chunks, prune_sources=deleted_files)` instead of `build_from_json` — merges into existing graph, prunes nodes from deleted files
- `manifest.json` written only on successful completion (crash mid-run does not corrupt next run's diff)
### Semantic cache (both full and incremental mode)
- Before LLM call: `check_semantic_cache(files)` splits into `(cached_results, uncached_files)`
- Only `uncached_files` sent to `extract_corpus_parallel`
- After LLM call: `save_semantic_cache(fresh_results)` — keyed by content hash
- On file rename: `source_file` updated to new path in cached result (same pattern as existing AST cache)
### Output summary
```
[graphify extract] incremental: 20 changed, 980 cached, 2 deleted
[graphify extract] graph: 4,821 nodes, 12,304 edges, 43 communities
[graphify extract] tokens: 18,432 in / 6,201 out, est. cost: $0.08
```
### Files changed
- `graphify/__main__.py` — `elif cmd == "extract":` block only (~5 targeted changes)
---
## Feature 2: Entity Deduplication
### New module: `graphify/dedup.py`
Single responsibility. Called from `build.py` after graph construction. Returns deduplicated `(nodes, edges)`.
### Pipeline
**Step 1 — Exact normalization**
Wire up the dormant `deduplicate_by_label` in `build.py`. Catches case/punctuation variants across files. Free win, already written.
**Step 2 — Entropy gate**
Skip fuzzy matching on labels with < 2.5 bits/char entropy. Short ambiguous names (`"AI"`, `"DB"`, `"x"`) are too risky to auto-merge. Only high-entropy labels proceed to steps 3-4.
**Step 3 — MinHash + LSH blocking** (`datasketch`)
3-gram shingles, 128 permutations, threshold 0.7. Generates candidate pairs in O(n) instead of O(n²). Sub-second at 10k nodes.
**Step 4 — Jaro-Winkler verification** (`rapidfuzz`)
Each candidate pair verified at ≥ 0.92. Catches typos, plurals, spacing variants. Pairs below threshold discarded.
**Step 5 — Same-community boost**
Pairs where both nodes share a Leiden community ID get +0.05 score bonus. Graphify-specific advantage — community structure is a strong signal that GraphRAG/LightRAG don't exploit.
**Step 6 — Union-find merge**
Confirmed pairs fed into union-find → connected components → each component merged into one node. Edges rewired to survivor. Self-loops dropped. Prefer shorter non-chunk-suffixed IDs as survivor.
**Step 7 — Optional LLM tiebreaker** (`--dedup-llm` flag)
Ambiguous pairs (score 0.75–0.85) batched in groups of 30, one LLM call per batch. ~$0.01 total for 10k nodes. Off by default.
### Integration point
Dedup runs after `build_merge` / `build_from_json`, before `cluster`. Order matters: cleaner graph → better community detection.
```python
# in build.py
G = build_merge(...) # or build_from_json
G = deduplicate_entities(G) # new step
communities = cluster(G) # unchanged
```
### New dependencies
- `datasketch` — always required (added to `[project.dependencies]`)
- `rapidfuzz` — always required (added to `[project.dependencies]`)
- No `sentence-transformers` / PyTorch dependency
### Files changed
- `graphify/dedup.py` — new module, full pipeline
- `graphify/build.py` — call `deduplicate_entities` after graph construction; wire dormant `deduplicate_by_label`
- `graphify/__main__.py` — add `--dedup-llm` flag parsing in extract block
- `pyproject.toml` — add `datasketch`, `rapidfuzz` to base dependencies
---
## Testing
- Unit tests for each dedup step in isolation (`tests/test_dedup.py`)
- Integration test: two chunks with overlapping entity labels → single merged node in output graph
- Incremental test: run extract twice, assert second run makes zero LLM calls for unchanged files
- Rename test: rename a file, assert cache hit and `source_file` updated correctly
- Delete test: delete a file, assert its nodes are pruned from graph
---
## Non-goals
- `--dedup embed` (MiniLM cosine) — explicitly excluded, no PyTorch dependency
- Incremental support for `graphify update` (AST-only) — already handled by existing AST cache
- Dedup across different graph.json files (merge two graphs) — separate feature
+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">
+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">
+544 -35
View File
@@ -1,77 +1,586 @@
<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` |
| `GEMINI_API_KEY` або `GOOGLE_API_KEY` | Backend Google Gemini | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI або OpenAI-сумісні API | `--backend openai` |
| `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
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">
+3408 -341
View File
File diff suppressed because it is too large. Load diff
+154
View File
@@ -0,0 +1,154 @@
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
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 resolve_seed(graph: nx.Graph, query: str) -> str | None:
if query in graph:
return query
query_lower = query.lower()
exact_label_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if str(data.get("label", "")).lower() == query_lower
]
if len(exact_label_matches) == 1:
return exact_label_matches[0]
exact_source_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if str(data.get("source_file", "")).lower() == 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 str(data.get("label", "")).lower()
]
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}
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.
+194 -10
View File
@@ -1,7 +1,46 @@
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
from __future__ import annotations
from pathlib import Path
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",
})
# Language families — extensions sharing a runtime can legitimately call each other
_LANG_FAMILY: dict[str, str] = {
**{e: "python" for e in (".py", ".pyw")},
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
**{e: "go" for e in (".go",)},
**{e: "rust" for e in (".rs",)},
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
**{e: "ruby" for e in (".rb",)},
**{e: "swift" for e in (".swift",)},
**{e: "dotnet" for e in (".cs",)},
**{e: "php" for e in (".php",)},
**{e: "r" for e in (".r",)},
}
def _cross_language(src_a: str, src_b: str) -> bool:
"""Return True if two source files belong to different language families."""
ext_a = Path(src_a).suffix.lower()
ext_b = Path(src_b).suffix.lower()
fam_a = _LANG_FAMILY.get(ext_a)
fam_b = _LANG_FAMILY.get(ext_b)
if fam_a is None or fam_b is None:
return False
return fam_a != fam_b
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
"""Invert communities dict: node_id -> community_id."""
@@ -36,6 +75,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.
@@ -46,7 +102,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,
@@ -136,6 +194,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
@@ -143,27 +202,44 @@ def _surprise_score(
# 1. Confidence weight - uncertain connections are more noteworthy
conf = data.get("confidence", "EXTRACTED")
relation = data.get("relation", "")
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
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")
@@ -173,8 +249,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)
@@ -199,6 +275,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):
@@ -216,7 +293,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
@@ -268,7 +345,7 @@ def _cross_community_surprises(
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
result = []
for (u, v), score in top_edges:
data = G.edges[u, v]
data = edge_data(G, u, v)
result.append({
"source": G.nodes[u].get("label", u),
"target": G.nodes[v].get("label", v),
@@ -345,6 +422,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)
@@ -538,3 +618,107 @@ 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.
cycles: list[list[str]] = []
for cycle in nx.simple_cycles(file_graph):
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
+30 -4
View File
@@ -1,21 +1,44 @@
"""Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach."""
from __future__ import annotations
import json
import sys
from pathlib import Path
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
def _safe(unicode_char: str, ascii_fallback: str) -> str:
"""Return unicode_char if stdout can encode it, else ascii_fallback.
Windows consoles often default to cp1252 which cannot encode box-drawing
or arrow glyphs; printing them raises UnicodeEncodeError mid-output.
"""
encoding = getattr(sys.stdout, "encoding", None) or ""
try:
unicode_char.encode(encoding)
return unicode_char
except (UnicodeEncodeError, LookupError):
return ascii_fallback
def _hr(width: int = 50) -> str:
"""Horizontal rule that survives non-UTF-8 stdout (e.g. Windows cp1252 console)."""
return _safe("─", "-") * width
def _estimate_tokens(text: str) -> int:
return max(1, len(text) // _CHARS_PER_TOKEN)
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()
@@ -46,7 +69,7 @@ def _query_subgraph_tokens(G: nx.Graph, question: str, depth: int = 3) -> int:
lines.append(f"NODE {d.get('label', nid)} src={d.get('source_file', '')} loc={d.get('source_location', '')}")
for u, v in edges_seen:
if u in visited and v in visited:
d = G.edges[u, v]
d = edge_data(G, u, v)
lines.append(f"EDGE {G.nodes[u].get('label', u)} --{d.get('relation', '')}--> {G.nodes[v].get('label', v)}")
return _estimate_tokens("\n".join(lines))
@@ -75,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")
@@ -118,8 +143,9 @@ def print_benchmark(result: dict) -> None:
return
print(f"\ngraphify token reduction benchmark")
print(f"{'─' * 50}")
print(f" Corpus: {result['corpus_words']:,} words → ~{result['corpus_tokens']:,} tokens (naive)")
print(_hr(50))
arrow = _safe("→", "->")
print(f" Corpus: {result['corpus_words']:,} words {arrow} ~{result['corpus_tokens']:,} tokens (naive)")
print(f" Graph: {result['nodes']:,} nodes, {result['edges']:,} edges")
print(f" Avg query cost: ~{result['avg_query_tokens']:,} tokens")
print(f" Reduction: {result['reduction_ratio']}x fewer tokens per query")
+282 -29
View File
@@ -22,36 +22,106 @@
#
from __future__ import annotations
import json
import os
import re
import sys
import unicodedata
from pathlib import Path
import networkx as nx
from .validate import validate_extraction
# Synonym mapper for known invalid file_type values that LLM subagents commonly
# emit. Keeps semantic intent close (markdown→document, tool→code) and falls
# back to "concept" for any other invalid value (see #840).
_FILE_TYPE_SYNONYMS = {
"markdown": "document",
"text": "document",
"tool": "code",
"library": "code",
"pattern": "concept",
"principle": "concept",
"constraint": "concept",
"tech": "concept",
"technology": "concept",
"data-source": "concept",
"data_source": "concept",
"gotcha": "concept",
"framework": "concept",
}
def _normalize_id(s: str) -> str:
"""Normalize an ID string the same way extract._make_id does.
r"""Normalize an ID string the same way extract._make_id does.
Used to reconcile edge endpoints when the LLM generates IDs with slightly
different punctuation or casing than the AST extractor.
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).
"""
cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", s)
return cleaned.strip("_").lower()
s = unicodedata.normalize("NFKC", s)
cleaned = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
cleaned = re.sub(r"_+", "_", cleaned)
return cleaned.strip("_").casefold()
def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
def _norm_source_file(p: str | None, root: str | None = None) -> str | None:
"""Normalize path separators and relativize absolute paths.
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).
"""
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:
"""Return one edge attribute dict for (u, v), tolerating MultiGraph.
For MultiGraph/MultiDiGraph there can be multiple parallel edges;
this returns the first one (sufficient for callers that only need
relation/confidence for rendering). Fixes #796.
"""
raw = G[u][v]
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
return next(iter(raw.values()), {})
return raw
def edge_datas(G: nx.Graph, u: str, v: str) -> list[dict]:
"""Return every edge attribute dict for (u, v); always a list."""
raw = G[u][v]
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
return list(raw.values())
return [raw]
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"])
# Canonicalize legacy node/edge schema before validation.
for node in extraction.get("nodes", []):
if isinstance(node, dict) and "source" in node and "source_file" not in node:
if not isinstance(node, dict):
continue
if "source" in node and "source_file" not in node:
# Count edges that reference this node so the warning is actionable (#479)
node_id = node.get("id", "?")
affected_edges = sum(
@@ -65,6 +135,15 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
file=sys.stderr,
)
node["source_file"] = node.pop("source")
# Default missing/None file_type to "concept" so legacy graph.json
# entries (and stub nodes preserved by `_rebuild_code` from older
# graphify versions that didn't always populate file_type) don't
# trigger spurious "invalid file_type 'None'" validator warnings (#660).
if node.get("file_type") in (None, ""):
node["file_type"] = "concept"
ft = node.get("file_type", "")
if ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
node["file_type"] = _FILE_TYPE_SYNONYMS.get(ft, "concept")
errors = validate_extraction(extraction)
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
@@ -73,13 +152,69 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
G: nx.Graph = nx.DiGraph() if directed else nx.Graph()
for node in extraction.get("nodes", []):
if "source_file" in node:
node["source_file"] = _norm_source_file(node["source_file"], _root)
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
node_set = set(G.nodes())
# #1145: merge semantic ghost-duplicate nodes into AST nodes.
# When AST and semantic extractors emit different IDs for the same symbol
# (one has source_location=L<n>, the other has source_location=None), find
# pairs that share (source_file basename, label) and collapse the semantic
# copy into the AST copy so edges re-point to a single node.
# Two passes: first collect all AST (located) nodes, then find ghosts.
_loc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> AST node id
_noloc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> semantic node id
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
if attrs.get("source_location"):
_loc_nodes[(basename, label)] = nid
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 or attrs.get("source_location"):
continue
key = (basename, label)
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:
@@ -95,10 +230,42 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
if src not in node_set or tgt not in node_set:
continue # skip edges to external/stdlib nodes - expected, not an error
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
if "source_file" in attrs:
attrs["source_file"] = _norm_source_file(attrs["source_file"], _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:
@@ -106,17 +273,29 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
return G
def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
def build(
extractions: list[dict],
*,
directed: bool = False,
dedup: bool = True,
dedup_llm_backend: str | None = None,
root: str | Path | None = None,
) -> nx.Graph:
"""Merge multiple extraction results into one graph.
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
dedup=True (default) runs entity deduplication before building the graph.
dedup_llm_backend: if set (e.g. "gemini", "claude", or "kimi"), uses LLM to resolve
ambiguous pairs in the 75–92 Jaro-Winkler score zone.
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
results before semantic results so semantic labels take precedence, or
reverse the order if you prefer AST source_location precision to win.
"""
from graphify.dedup import deduplicate_entities
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
for ext in extractions:
combined["nodes"].extend(ext.get("nodes", []))
@@ -124,12 +303,18 @@ def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
combined["hyperedges"].extend(ext.get("hyperedges", []))
combined["input_tokens"] += ext.get("input_tokens", 0)
combined["output_tokens"] += ext.get("output_tokens", 0)
return build_from_json(combined, directed=directed)
if dedup and combined["nodes"]:
combined["nodes"], combined["edges"] = deduplicate_entities(
combined["nodes"], combined["edges"], communities={},
dedup_llm_backend=dedup_llm_backend,
)
return build_from_json(combined, directed=directed, root=root)
def _norm_label(label: str) -> str:
"""Canonical dedup key — lowercase, alphanumeric only."""
return re.sub(r"[^a-z0-9 ]", "", label.lower()).strip()
"""Canonical dedup key — Unicode-aware, preserves CJK/word characters."""
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]]:
@@ -184,45 +369,90 @@ def build_merge(
prune_sources: list[str] | None = None,
*,
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).
Never replaces - only grows (or prunes deleted-file nodes via prune_sources).
Safe to call repeatedly: existing nodes and edges are preserved.
root: if given, absolute source_file paths in new_chunks are made relative (#932).
"""
from networkx.readwrite import json_graph as _jg
graph_path = Path(graph_path)
if graph_path.exists():
# Read JSON directly instead of going through node_link_graph().
# The latter rebuilds an undirected nx.Graph and then enumerating
# edges() yields endpoints based on node insertion order, which
# silently flips directional edges (e.g. `calls`) when the callee
# 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"))
try:
existing_G = _jg.node_link_graph(data, edges="links")
except TypeError:
existing_G = _jg.node_link_graph(data)
# Reconstruct as a plain extraction dict so build() can merge it
existing_nodes = [{"id": n, **existing_G.nodes[n]} for n in existing_G.nodes]
existing_edges = [
{"source": u, "target": v, **d} for u, v, d in existing_G.edges(data=True)
]
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}]
else:
existing_nodes = []
base = []
all_chunks = base + list(new_chunks)
G = build(all_chunks, directed=directed)
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)
if to_remove:
print(f"[graphify] Pruned {len(to_remove)} node(s) from deleted sources.", file=sys.stderr)
n_files = len(prune_sources)
n_nodes = len(to_remove)
if n_nodes:
print(
f"[graphify] Pruned {n_nodes} node(s) from {n_files} deleted source file(s).",
file=sys.stderr,
)
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 or edges in graph, already clean.",
file=sys.stderr,
)
# Safety check: refuse to shrink the graph silently (#479)
if graph_path.exists():
# Skip when dedup or prune_sources is active — shrinkage is intentional there.
if graph_path.exists() and not dedup and not prune_sources:
existing_n = len(existing_nodes)
new_n = G.number_of_nodes()
if new_n < existing_n:
@@ -232,3 +462,26 @@ def build_merge(
)
return G
def prefix_graph_for_global(G: nx.Graph, repo_tag: str) -> nx.Graph:
"""Return a copy of G with all node IDs prefixed with repo_tag::.
Labels are preserved unchanged (for display). A 'local_id' attribute
is added to each node so the original ID can be recovered. Edges are
rewritten to match the new prefixed IDs. The 'repo' attribute is set
on every node.
"""
relabel = {n: f"{repo_tag}::{n}" for n in G.nodes}
H = nx.relabel_nodes(G, relabel, copy=True)
for node, data in H.nodes(data=True):
data["repo"] = repo_tag
data.setdefault("local_id", node.split("::", 1)[1])
return H
def prune_repo_from_graph(G: nx.Graph, repo_tag: str) -> int:
"""Remove all nodes tagged with repo_tag from G in-place. Returns count removed."""
to_remove = [n for n, d in G.nodes(data=True) if d.get("repo") == repo_tag]
G.remove_nodes_from(to_remove)
return len(to_remove)
+223 -18
View File
@@ -1,11 +1,18 @@
# per-file extraction cache - skip unchanged files on re-run
from __future__ import annotations
import atexit
import hashlib
import json
import os
import tempfile
from pathlib import Path
# Output directory name — override with GRAPHIFY_OUT env var for worktrees or
# shared-output setups. Accepts a relative name ("graphify-out-feature") or an
# absolute path ("/shared/graphify-out").
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
def _body_content(content: bytes) -> bytes:
"""Strip YAML frontmatter from Markdown content, returning only the body."""
@@ -17,9 +24,83 @@ def _body_content(content: bytes) -> bytes:
return content
# 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:
"""Normalize path for consistent cache keys across Windows path spellings."""
import sys
if sys.platform != "win32":
return path
s = str(path)
if s.startswith("\\\\?\\"):
s = s[4:] # strip extended-length prefix \\?\
return Path(os.path.normcase(s))
def file_hash(path: Path, root: Path = Path(".")) -> str:
"""SHA256 of file contents + path relative to root.
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.
@@ -27,9 +108,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.
"""
p = Path(path)
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()
@@ -37,10 +134,80 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
h.update(b"\x00")
try:
rel = p.resolve().relative_to(Path(root).resolve())
h.update(str(rel).encode())
h.update(rel.as_posix().lower().encode())
except ValueError:
h.update(str(p.resolve()).encode())
return h.hexdigest()
h.update(p.resolve().as_posix().lower().encode())
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:
@@ -49,7 +216,9 @@ def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
entries from overwriting AST cache entries for the same source_file (#582).
"""
d = Path(root).resolve() / "graphify-out" / "cache" / kind
_out = Path(_GRAPHIFY_OUT)
base = _out if _out.is_absolute() else Path(root).resolve() / _out
d = base / "cache" / kind
d.mkdir(parents=True, exist_ok=True)
return d
@@ -71,17 +240,26 @@ 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
# 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
# Migration fallback: check legacy flat cache/ dir for AST entries
if kind == "ast":
legacy = Path(root).resolve() / "graphify-out" / "cache" / f"{h}.json"
legacy = Path(root).resolve() / _GRAPHIFY_OUT / "cache" / f"{h}.json"
if legacy.exists():
try:
return json.loads(legacy.read_text(encoding="utf-8"))
result = json.loads(legacy.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
if isinstance(result, dict):
_absolutize_source_files_in(result, root)
return result
return None
@@ -98,27 +276,51 @@ 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)
entry = cache_dir(root, kind) / f"{h}.json"
tmp = entry.with_suffix(".tmp")
target_dir = cache_dir(root, kind)
entry = target_dir / f"{h}.json"
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
try:
tmp.write_text(json.dumps(result), encoding="utf-8")
os.write(fd, json.dumps(on_disk).encode())
os.close(fd)
try:
os.replace(tmp, entry)
os.replace(tmp_path, entry)
except PermissionError:
# Windows: os.replace can fail with WinError 5 if the target is
# briefly locked. Fall back to copy-then-delete.
import shutil
shutil.copy2(tmp, entry)
tmp.unlink(missing_ok=True)
shutil.copy2(tmp_path, entry)
os.unlink(tmp_path)
except Exception:
tmp.unlink(missing_ok=True)
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(tmp_path)
except OSError:
pass
raise
def cached_files(root: Path = Path(".")) -> set[str]:
"""Return set of file hashes that have a valid cache entry (any kind)."""
base = Path(root).resolve() / "graphify-out" / "cache"
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
hashes: set[str] = set()
# Legacy flat entries
if base.is_dir():
@@ -133,7 +335,7 @@ def cached_files(root: Path = Path(".")) -> set[str]:
def clear_cache(root: Path = Path(".")) -> None:
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
base = Path(root).resolve() / "graphify-out" / "cache"
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
# Legacy flat entries
if base.is_dir():
for f in base.glob("*.json"):
@@ -161,7 +363,10 @@ def check_semantic_cache(
uncached: list[str] = []
for fpath in files:
result = load_cached(Path(fpath), root, kind="semantic")
p = Path(fpath)
if not p.is_absolute():
p = Path(root) / p
result = load_cached(p, root, kind="semantic")
if result is not None:
cached_nodes.extend(result.get("nodes", []))
cached_edges.extend(result.get("edges", []))
File diff suppressed because it is too large. Load diff
+146 -11
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import contextlib
import inspect
import io
import json
import sys
import networkx as nx
@@ -18,24 +19,48 @@ 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.
"""
stable = nx.Graph()
stable.add_nodes_from(sorted(G.nodes(), key=str))
edge_rows = sorted(
G.edges(data=True),
key=lambda row: (
str(row[0]),
str(row[1]),
json.dumps(row[2], sort_keys=True, ensure_ascii=False, default=str),
),
)
for src, tgt, attrs in edge_rows:
stable.add_edge(src, tgt, **attrs)
try:
from graspologic.partition import leiden
lsig = inspect.signature(leiden).parameters
kwargs: dict = {}
if "random_seed" in lsig:
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
try:
sys.stderr = io.StringIO()
with _suppress_output():
result = leiden(G)
result = leiden(stable, **kwargs)
finally:
sys.stderr = old_stderr
return result
@@ -45,18 +70,24 @@ 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(G, **kwargs)
communities = nx.community.louvain_communities(stable, **kwargs)
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
_MAX_COMMUNITY_FRACTION = 0.25 # communities larger than 25% of graph get split
_MIN_SPLIT_SIZE = 10 # only split if community has at least this many nodes
_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.
@@ -65,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 {}
@@ -73,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)
@@ -90,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]] = []
@@ -99,8 +167,24 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
else:
final_communities.append(nodes)
# Re-index by size descending for deterministic ordering
final_communities.sort(key=len, reverse=True)
# Second pass: re-split low-cohesion communities caused by doc-hub nodes
# that bridge otherwise-unrelated subsystems (e.g. CLAUDE.md connected to everything).
second_pass: list[list[str]] = []
for nodes in final_communities:
if len(nodes) >= _COHESION_SPLIT_MIN_SIZE and cohesion_score(G, nodes) < _COHESION_SPLIT_THRESHOLD:
splits = _split_community(G, nodes)
second_pass.extend(splits if len(splits) > 1 else [nodes])
else:
second_pass.append(nodes)
final_communities = second_pass
# Re-index by size descending. 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)}
@@ -130,8 +214,59 @@ 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]:
return {cid: cohesion_score(G, nodes) for cid, nodes in communities.items()}
def remap_communities_to_previous(
communities: dict[int, list[str]],
previous_node_community: dict[str, int],
) -> dict[int, list[str]]:
"""Remap community IDs to maximize overlap with a previous assignment.
Uses greedy one-to-one matching by intersection size, then assigns fresh IDs
to unmatched communities in deterministic order (size desc, lexical tie-break).
"""
if not communities:
return {}
new_sets = {cid: set(nodes) for cid, nodes in communities.items()}
old_sets: dict[int, set[str]] = {}
for node, old_cid in previous_node_community.items():
old_sets.setdefault(old_cid, set()).add(node)
overlaps: list[tuple[int, int, int]] = []
for old_cid, old_nodes in old_sets.items():
for new_cid, new_nodes in new_sets.items():
overlap = len(old_nodes & new_nodes)
if overlap > 0:
overlaps.append((overlap, old_cid, new_cid))
overlaps.sort(key=lambda x: (-x[0], x[1], x[2]))
new_to_final: dict[int, int] = {}
used_old_ids: set[int] = set()
matched_new_ids: set[int] = set()
for _overlap, old_cid, new_cid in overlaps:
if old_cid in used_old_ids or new_cid in matched_new_ids:
continue
new_to_final[new_cid] = old_cid
used_old_ids.add(old_cid)
matched_new_ids.add(new_cid)
unmatched = [cid for cid in communities if cid not in matched_new_ids]
unmatched.sort(key=lambda cid: (-len(communities[cid]), tuple(sorted(communities[cid]))))
next_id = 0
for new_cid in unmatched:
while next_id in used_old_ids:
next_id += 1
new_to_final[new_cid] = next_id
used_old_ids.add(next_id)
next_id += 1
remapped: dict[int, list[str]] = {}
for new_cid, nodes in communities.items():
remapped[new_to_final[new_cid]] = sorted(nodes)
return dict(sorted(remapped.items(), key=lambda kv: kv[0]))
+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.
+429
View File
@@ -0,0 +1,429 @@
"""Entity deduplication pipeline for graphify knowledge graphs.
Pipeline: exact normalization → entropy gate → MinHash/LSH blocking →
Jaro-Winkler verification → same-community boost → union-find merge.
"""
from __future__ import annotations
import math
import re
import unicodedata
from collections import defaultdict
from datasketch import MinHash, MinHashLSH
from rapidfuzz.distance import JaroWinkler
# ── helpers ───────────────────────────────────────────────────────────────────
def _norm(label: str) -> str:
"""Lowercase + collapse non-alphanumeric runs to space (Unicode-aware)."""
label = unicodedata.normalize("NFKC", label)
return re.sub(r"[\W_]+", " ", label.casefold(), flags=re.UNICODE).strip()
def _entropy(label: str) -> float:
"""Shannon entropy in bits/char of the normalised label."""
s = _norm(label)
if not s:
return 0.0
freq: dict[str, int] = defaultdict(int)
for ch in s:
freq[ch] += 1
n = len(s)
return -sum((c / n) * math.log2(c / n) for c in freq.values())
def _shingles(text: str, k: int = 3) -> set[str]:
"""Return k-gram character shingles of text."""
if len(text) < k:
return {text}
return {text[i : i + k] for i in range(len(text) - k + 1)}
def _make_minhash(text: str, num_perm: int = 128) -> MinHash:
# Strip spaces so "graph extractor" and "graphextractor" share shingles
m = MinHash(num_perm=num_perm)
for shingle in _shingles(text.replace(" ", "")):
m.update(shingle.encode("utf-8"))
return m
# 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
# ── union-find ────────────────────────────────────────────────────────────────
class _UF:
def __init__(self) -> None:
self._parent: dict[str, str] = {}
def find(self, x: str) -> str:
self._parent.setdefault(x, x)
while self._parent[x] != x:
self._parent[x] = self._parent[self._parent[x]]
x = self._parent[x]
return x
def union(self, x: str, y: str) -> None:
self._parent.setdefault(x, x)
self._parent.setdefault(y, y)
rx, ry = self.find(x), self.find(y)
if rx != ry:
self._parent[ry] = rx
def components(self) -> dict[str, list[str]]:
groups: dict[str, list[str]] = defaultdict(list)
for x in self._parent:
groups[self.find(x)].append(x)
return dict(groups)
# ── constants ─────────────────────────────────────────────────────────────────
_ENTROPY_THRESHOLD = 2.5
_LSH_THRESHOLD = 0.7
_MERGE_THRESHOLD = 92.0 # rapidfuzz normalized_similarity * 100
_COMMUNITY_BOOST = 5.0 # score bonus when both nodes share community
_NUM_PERM = 128
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
# ── main entry point ──────────────────────────────────────────────────────────
def deduplicate_entities(
nodes: list[dict],
edges: list[dict],
*,
communities: dict[str, int],
dedup_llm_backend: str | None = None,
) -> tuple[list[dict], list[dict]]:
"""Deduplicate near-identical entities in a knowledge graph.
Args:
nodes: list of node dicts with at minimum {"id": str, "label": str}
edges: list of edge dicts with {"source": str, "target": str, ...}
communities: mapping of node_id -> community_id (from cluster())
dedup_llm_backend: if set, use LLM to resolve ambiguous pairs
Returns:
(deduped_nodes, deduped_edges) with edges rewired to survivors
"""
# Guard: cross-project dedup is not supported — nodes from different repos
# share label names by coincidence and must never be merged by string similarity.
# If you need to dedup a global graph, run deduplicate_entities per-repo first.
repos_seen = {n.get("repo") for n in nodes if n.get("repo")}
if len(repos_seen) > 1:
raise ValueError(
f"deduplicate_entities: nodes span multiple repos {sorted(repos_seen)!r}. "
f"Cross-project dedup is disabled — run dedup per-repo before merging."
)
if len(nodes) <= 1:
return nodes, edges
# Pre-deduplicate: keep first occurrence of each id
seen_ids: dict[str, dict] = {}
for node in nodes:
nid = node.get("id", "")
if nid and nid not in seen_ids:
seen_ids[nid] = node
unique_nodes = list(seen_ids.values())
if len(unique_nodes) <= 1:
return unique_nodes, edges
# ── pass 1: exact normalization ───────────────────────────────────────────
norm_to_nodes: dict[str, list[dict]] = defaultdict(list)
for node in unique_nodes:
key = _norm(node.get("label", node.get("id", "")))
if key:
norm_to_nodes[key].append(node)
uf = _UF()
exact_merges = 0
for key, group in norm_to_nodes.items():
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:
key = _norm(node.get("label", node.get("id", "")))
if key and key not in seen_norms:
seen_norms.add(key)
if _entropy(node.get("label", "")) >= _ENTROPY_THRESHOLD:
candidates.append(node)
fuzzy_merges = 0
if len(candidates) >= 2:
lsh = MinHashLSH(threshold=_LSH_THRESHOLD, num_perm=_NUM_PERM)
minhashes: dict[str, MinHash] = {}
for node in candidates:
norm_label = _norm(node.get("label", node.get("id", "")))
m = _make_minhash(norm_label)
minhashes[node["id"]] = m
try:
lsh.insert(node["id"], m)
except ValueError:
pass # duplicate key in LSH — already inserted
for node in candidates:
node_id = node["id"]
norm_label = _norm(node.get("label", node.get("id", "")))
neighbors = lsh.query(minhashes[node_id])
for neighbor_id in neighbors:
if neighbor_id == node_id:
continue
if uf.find(node_id) == uf.find(neighbor_id):
continue
neighbor = next((n for n in candidates if n["id"] == neighbor_id), None)
if neighbor is None:
continue
neighbor_norm = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
if _is_variant_pair(norm_label, neighbor_norm):
continue
if _short_label_blocked(norm_label, neighbor_norm, score):
continue
c1 = communities.get(node_id)
c2 = communities.get(neighbor_id)
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:
# 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
all_group = norm_to_nodes.get(norm_label, [node]) + \
norm_to_nodes.get(neighbor_norm, [neighbor])
winner = _pick_winner(all_group)
uf.union(winner["id"], node_id)
uf.union(winner["id"], neighbor_id)
fuzzy_merges += 1
# ── pass 3: LLM tiebreaker for ambiguous pairs (opt-in) ──────────────────
if dedup_llm_backend is not None:
_llm_tiebreak(candidates, uf, communities, backend=dedup_llm_backend)
# ── build remap table from union-find components ──────────────────────────
components = uf.components()
remap: dict[str, str] = {}
for root, members in components.items():
if len(members) == 1:
continue
group_nodes = [n for n in unique_nodes if n["id"] in members]
winner = _pick_winner(group_nodes) if group_nodes else {"id": root}
winner_id = winner["id"]
for member in members:
if member != winner_id:
remap[member] = winner_id
# ── apply remap ───────────────────────────────────────────────────────────
if not remap:
return unique_nodes, edges
total = len(remap)
msg = f"[graphify] Deduplicated {total} node(s)"
if exact_merges:
msg += f" ({exact_merges} exact"
if fuzzy_merges:
msg += f", {fuzzy_merges} fuzzy"
msg += ")"
print(msg + ".", flush=True)
deduped_nodes = [n for n in unique_nodes if n["id"] not in remap]
deduped_edges = []
for edge in edges:
e = dict(edge)
# Tolerate "from"/"to" keys from LLM backends that don't follow the
# schema exactly — build_from_json normalises later but dedup runs
# first so bracket access would KeyError here (#803).
# Use explicit key presence check (not `or`) so empty-string src/tgt
# aren't silently replaced by the fallback key.
src = e["source"] if "source" in e else e.get("from")
tgt = e["target"] if "target" in e else e.get("to")
if src is None or tgt is None:
continue
e["source"] = remap.get(src, src)
e["target"] = remap.get(tgt, tgt)
# Remove legacy keys so they don't leak into edge attrs in graph.json.
e.pop("from", None)
e.pop("to", None)
if e["source"] != e["target"]:
deduped_edges.append(e)
return deduped_nodes, deduped_edges
def _pick_winner(nodes: list[dict]) -> dict:
"""Pick the canonical survivor: prefer no chunk suffix, then shorter ID."""
if not nodes:
raise ValueError("Cannot pick winner from empty list")
def _score(n: dict) -> tuple[int, int]:
has_suffix = bool(_CHUNK_SUFFIX.search(n["id"]))
return (1 if has_suffix else 0, len(n["id"]))
return min(nodes, key=_score)
def _llm_tiebreak(
candidates: list[dict],
uf: _UF,
communities: dict[str, int],
*,
backend: str,
batch_size: int = 30,
low: float = 75.0,
high: float = 92.0,
) -> None:
"""Batch-resolve ambiguous pairs (score in [low, high)) via LLM."""
try:
from graphify.llm import BACKENDS, _format_backend_env_keys, _get_backend_api_key
if backend not in BACKENDS:
print(f"[graphify] --dedup-llm: unknown backend {backend!r}, skipping LLM tiebreaker.", flush=True)
return
if not _get_backend_api_key(backend):
env_keys = _format_backend_env_keys(backend)
print(f"[graphify] --dedup-llm: {env_keys} not set, skipping LLM tiebreaker.", flush=True)
return
except ImportError:
return
ambiguous: list[tuple[dict, dict, float]] = []
for i, node in enumerate(candidates):
norm_i = _norm(node.get("label", node.get("id", "")))
for j in range(i + 1, len(candidates)):
neighbor = candidates[j]
if uf.find(node["id"]) == uf.find(neighbor["id"]):
continue
norm_j = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
if _is_variant_pair(norm_i, norm_j):
continue
if _short_label_blocked(norm_i, norm_j, score):
continue
c1 = communities.get(node["id"])
c2 = communities.get(neighbor["id"])
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))
if not ambiguous:
return
try:
from graphify.llm import _call_llm
except ImportError as exc:
# F-038: previously this silent fallback hid the fact that `_call_llm`
# didn't exist in `graphify.llm` at all, so `--dedup-llm` was a no-op.
# Surface the import failure so future regressions are visible.
print(
f"[graphify] --dedup-llm: cannot import _call_llm ({exc}); skipping LLM tiebreaker.",
flush=True,
)
return
for batch_start in range(0, len(ambiguous), batch_size):
batch = ambiguous[batch_start : batch_start + batch_size]
pairs_text = "\n".join(
f"{i+1}. \"{a['label']}\" vs \"{b['label']}\""
for i, (a, b, _) in enumerate(batch)
)
prompt = (
"For each pair below, answer only 'yes' or 'no': are they the same real-world concept?\n\n"
f"{pairs_text}\n\n"
"Reply with one line per pair: '1. yes', '2. no', etc."
)
try:
response = _call_llm(prompt, backend=backend, max_tokens=200)
lines = response.strip().splitlines()
for line in lines:
line = line.strip()
if not line:
continue
parts = line.split(".", 1)
if len(parts) != 2:
continue
try:
idx = int(parts[0].strip()) - 1
except ValueError:
continue
if 0 <= idx < len(batch):
answer = parts[1].strip().lower()
if answer.startswith("yes"):
a, b, _ = batch[idx]
winner = _pick_winner([a, b])
uf.union(winner["id"], a["id"])
uf.union(winner["id"], b["id"])
except Exception as exc:
print(f"[graphify] --dedup-llm batch failed: {exc}", flush=True)
+936 -68
View File
File diff suppressed because it is too large. Load diff
+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)
+387 -43
View File
@@ -1,15 +1,106 @@
# 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
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.
Obsidian tags only allow alphanumerics, hyphens, underscores, and slashes.
Spaces become underscores; everything else is stripped.
"""
return re.sub(r"[^a-zA-Z0-9_\-/]", "", name.replace(" ", "_"))
def _strip_diacritics(text: str) -> str:
import unicodedata
@@ -17,6 +108,44 @@ def _strip_diacritics(text: str) -> str:
return "".join(c for c in nfkd if not unicodedata.combining(c))
def _yaml_str(s: str) -> str:
"""Escape a value for safe embedding in a YAML double-quoted scalar (F-009).
See `graphify.ingest._yaml_str` for the full rationale; duplicated here to
avoid pulling the URL-fetching `ingest` module into export's dependency
graph. Handles backslash, double-quote, all line breaks (\\n, \\r,
U+2028, U+2029), tab, NUL, and other C0/DEL control characters that
would otherwise let a hostile `source_file` / `community` / etc. break
out of the YAML scalar and inject sibling keys.
"""
if s is None:
return ""
out: list[str] = []
for ch in str(s):
cp = ord(ch)
if ch == "\\":
out.append("\\\\")
elif ch == '"':
out.append('\\"')
elif ch == "\n":
out.append("\\n")
elif ch == "\r":
out.append("\\r")
elif ch == "\t":
out.append("\\t")
elif ch == "\0":
out.append("\\0")
elif cp == 0x2028:
out.append("\\L")
elif cp == 0x2029:
out.append("\\P")
elif cp < 0x20 or cp == 0x7F:
out.append(f"\\x{cp:02x}")
else:
out.append(ch)
return "".join(out)
COMMUNITY_COLORS = [
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
"#EDC948", "#B07AA1", "#FF9DA7", "#9C755F", "#BAB0AC",
@@ -25,6 +154,22 @@ COMMUNITY_COLORS = [
MAX_NODES_FOR_VIZ = 5_000
def _viz_node_limit() -> int:
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
"""
import os
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
if raw is None or not raw.strip():
return MAX_NODES_FOR_VIZ
try:
return int(raw)
except ValueError:
return MAX_NODES_FOR_VIZ
def _html_styles() -> str:
return """<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
@@ -55,9 +200,14 @@ def _html_styles() -> str:
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.legend-count { color: #666; font-size: 11px; }
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
#legend-controls { display: flex; gap: 6px; margin-bottom: 8px; }
#legend-controls button { flex: 1; background: #0f0f1a; border: 1px solid #3a3a5e; color: #aaa; padding: 4px 0; border-radius: 4px; font-size: 11px; cursor: pointer; }
#legend-controls button:hover { border-color: #4E79A7; color: #e0e0e0; }
#legend-controls { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; padding: 4px 0; }
#legend-controls label { display: flex; align-items: center; gap: 6px; cursor: pointer; font-size: 12px; color: #aaa; user-select: none; }
#legend-controls label:hover { color: #e0e0e0; }
.legend-cb, #select-all-cb { appearance: none; -webkit-appearance: none; width: 14px; height: 14px; border: 1.5px solid #3a3a5e; border-radius: 3px; background: #0f0f1a; cursor: pointer; position: relative; flex-shrink: 0; }
.legend-cb:checked, #select-all-cb:checked { background: #4E79A7; border-color: #4E79A7; }
.legend-cb:checked::after, #select-all-cb:checked::after { content: ''; position: absolute; left: 3.5px; top: 1px; width: 4px; height: 7px; border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg); }
#select-all-cb:indeterminate { background: #4E79A7; border-color: #4E79A7; }
#select-all-cb:indeterminate::after { content: ''; position: absolute; left: 2px; top: 5px; width: 8px; height: 2px; background: #fff; border: none; transform: none; }
</style>"""
@@ -244,26 +394,41 @@ document.addEventListener('click', e => {{
const hiddenCommunities = new Set();
const selectAllCb = document.getElementById('select-all-cb');
function updateSelectAllState() {{
const total = LEGEND.length;
const hidden = hiddenCommunities.size;
selectAllCb.checked = hidden === 0;
selectAllCb.indeterminate = hidden > 0 && hidden < total;
}}
function toggleAllCommunities(hide) {{
document.querySelectorAll('.legend-item').forEach(item => {{
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
}});
document.querySelectorAll('.legend-cb').forEach(cb => {{
cb.checked = !hide;
}});
LEGEND.forEach(c => {{
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
}});
const updates = RAW_NODES.map(n => ({{ id: n.id, hidden: hide }}));
nodesDS.update(updates);
updateSelectAllState();
}}
const legendEl = document.getElementById('legend');
LEGEND.forEach(c => {{
const item = document.createElement('div');
item.className = 'legend-item';
item.innerHTML = `<div class="legend-dot" style="background:${{c.color}}"></div>
<span class="legend-label">${{c.label}}</span>
<span class="legend-count">${{c.count}}</span>`;
item.onclick = () => {{
if (hiddenCommunities.has(c.cid)) {{
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'legend-cb';
cb.checked = true;
cb.addEventListener('change', (e) => {{
e.stopPropagation();
if (cb.checked) {{
hiddenCommunities.delete(c.cid);
item.classList.remove('dimmed');
}} else {{
@@ -272,8 +437,18 @@ LEGEND.forEach(c => {{
}}
const updates = RAW_NODES
.filter(n => n.community === c.cid)
.map(n => ({{ id: n.id, hidden: hiddenCommunities.has(c.cid) }}));
.map(n => ({{ id: n.id, hidden: !cb.checked }}));
nodesDS.update(updates);
updateSelectAllState();
}});
item.innerHTML = `<div class="legend-dot" style="background:${{c.color}}"></div>
<span class="legend-label">${{c.label}}</span>
<span class="legend-count">${{c.count}}</span>`;
item.prepend(cb);
item.onclick = (e) => {{
if (e.target === cb) return;
cb.checked = !cb.checked;
cb.dispatchEvent(new Event('change'));
}};
legendEl.appendChild(item);
}});
@@ -294,11 +469,23 @@ def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
G.graph["hyperedges"] = existing
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False) -> bool:
def _git_head() -> str | None:
"""Return the current git HEAD commit hash, or None if not in a git repo."""
import subprocess as _sp
try:
r = _sp.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=3)
return r.stdout.strip() if r.returncode == 0 else None
except Exception:
return None
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None) -> bool:
# Safety check: refuse to silently shrink an existing graph (#479)
existing_path = Path(output_path)
if not force and existing_path.exists():
try:
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()
@@ -306,9 +493,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
@@ -327,7 +517,19 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
if "confidence_score" not in link:
conf = link.get("confidence", "EXTRACTED")
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
# Restore original edge direction. Undirected NetworkX storage may
# canonicalize endpoint order, flipping `calls` and other directional
# edges in graph.json. The build path stashes the true endpoints in
# _src/_tgt for exactly this purpose (#563).
true_src = link.pop("_src", None)
true_tgt = link.pop("_tgt", None)
if true_src is not None and true_tgt is not None:
link["source"] = true_src
link["target"] = true_tgt
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
commit = built_at_commit if built_at_commit is not None else _git_head()
if commit:
data["built_at_commit"] = commit
with open(output_path, "w", encoding="utf-8") as f: # nosec
json.dump(data, f, indent=2)
return True
@@ -349,8 +551,48 @@ def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
def _cypher_escape(s: str) -> str:
"""Escape a string for safe embedding in a Cypher single-quoted literal."""
return s.replace("\\", "\\\\").replace("'", "\\'")
"""Escape a string for safe embedding in a Cypher single-quoted literal.
Handles all characters that could prematurely terminate the literal or
inject control sequences:
- `\\` and `'` (literal terminators)
- newlines/CRs (would break the per-line statement framing)
- NUL/control bytes (defensive — Neo4j errors on raw NULs)
Also strips any leading/trailing whitespace that would let an attacker
break the `;`-terminated statement boundary used by `cypher-shell`.
Closing `}` and `)` are NOT special inside a single-quoted Cypher string,
so escaping the quote and backslash correctly is sufficient (a `}` inside
a properly-closed `'...'` literal is just a character) — but we previously
missed `\\n` / `\\r` which DO let a payload break out of the statement
line and inject a fresh MATCH/DELETE on the following line. See F-008.
"""
# First normalise: drop NUL and other C0 control chars except tab.
s = "".join(ch for ch in s if ch >= " " or ch == "\t")
return (
s.replace("\\", "\\\\")
.replace("'", "\\'")
.replace("\n", "\\n")
.replace("\r", "\\r")
)
# Restrict identifier-position values (labels and relationship types are NOT
# quoted in Cypher and so cannot be safely escaped — they must be allowlisted).
_CYPHER_IDENT_RE = re.compile(r"[^A-Za-z0-9_]")
def _cypher_label(raw: str, fallback: str) -> str:
"""Sanitise a value used in identifier position (node label / rel type).
Cypher does not provide a way to escape `:Foo` label syntax, so we must
strip everything except `[A-Za-z0-9_]` and require the result to start
with a letter; otherwise we fall back to a safe constant.
"""
cleaned = _CYPHER_IDENT_RE.sub("", raw or "")
if not cleaned or not cleaned[0].isalpha():
return fallback
return cleaned
def to_cypher(G: nx.Graph, output_path: str) -> None:
@@ -358,12 +600,17 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
for node_id, data in G.nodes(data=True):
label = _cypher_escape(data.get("label", node_id))
node_id_esc = _cypher_escape(node_id)
_ft = re.sub(r"[^A-Za-z0-9_]", "", data.get("file_type", "unknown").capitalize())
ftype = (_ft if _ft and _ft[0].isalpha() else "Entity")
ftype = _cypher_label(
(data.get("file_type", "unknown") or "unknown").capitalize(),
"Entity",
)
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
lines.append("")
for u, v, data in G.edges(data=True):
rel = re.sub(r"[^A-Za-z0-9_]", "_", data.get("relation", "RELATES_TO").upper())
rel = _cypher_label(
(data.get("relation", "RELATES_TO") or "RELATES_TO").upper(),
"RELATES_TO",
)
conf = _cypher_escape(data.get("confidence", "EXTRACTED"))
u_esc = _cypher_escape(u)
v_esc = _cypher_escape(v)
@@ -381,6 +628,7 @@ def to_html(
output_path: str,
community_labels: dict[int, str] | None = None,
member_counts: dict[int, int] | None = None,
node_limit: int | None = None,
) -> None:
"""Generate an interactive vis.js HTML visualization of the graph.
@@ -390,11 +638,67 @@ def to_html(
If member_counts is provided (aggregated community view), node sizes are
based on community member counts rather than graph degree.
If node_limit is set and the graph exceeds it, automatically builds an
aggregated community-level meta-graph instead of raising ValueError.
"""
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
limit = node_limit if node_limit is not None else _viz_node_limit()
if G.number_of_nodes() > limit:
if node_limit is not None:
# Build aggregated community meta-graph
from collections import Counter as _Counter
import networkx as _nx
print(f"Graph has {G.number_of_nodes()} nodes (above {limit} limit). Building aggregated community view...")
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
meta = _nx.Graph()
for cid, members in communities.items():
meta.add_node(str(cid), label=(community_labels or {}).get(cid, f"Community {cid}"))
edge_counts = _Counter()
for u, v in G.edges():
cu, cv = node_to_community.get(u), node_to_community.get(v)
if cu is not None and cv is not None and cu != cv:
edge_counts[(min(cu, cv), max(cu, cv))] += 1
for (cu, cv), w in edge_counts.items():
meta.add_edge(str(cu), str(cv), weight=w,
relation=f"{w} cross-community edges", confidence="AGGREGATED")
if meta.number_of_nodes() <= 1:
print("Single community - aggregated view not useful. Skipping graph.html.")
return
meta_communities = {cid: [str(cid)] for cid in communities}
mc = {cid: len(members) for cid, members in communities.items()}
# 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)")
print("Tip: run with --obsidian for full node-level detail.")
return
raise ValueError(
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
f"Use --no-viz or reduce input size."
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
f"or reduce input size."
)
node_community = _node_community_map(communities)
@@ -431,14 +735,19 @@ def to_html(
"degree": deg,
})
# Build edges list
# Build edges list. Restore original edge direction from _src/_tgt
# (stashed by build.py for exactly this reason): undirected NetworkX
# canonicalizes endpoint order, which would otherwise flip the arrow
# for `calls` and `rationale_for` in the rendered graph (#563).
vis_edges = []
for u, v, data in G.edges(data=True):
confidence = data.get("confidence", "EXTRACTED")
relation = data.get("relation", "")
true_src = data.get("_src", u)
true_tgt = data.get("_tgt", v)
vis_edges.append({
"from": u,
"to": v,
"from": true_src,
"to": true_tgt,
"label": relation,
"title": _html.escape(f"{relation} [{confidence}]"),
"dashes": confidence != "EXTRACTED",
@@ -471,7 +780,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>
@@ -488,8 +799,7 @@ def to_html(
<div id="legend-wrap">
<h3>Communities</h3>
<div id="legend-controls">
<button onclick="toggleAllCommunities(false)">Show All</button>
<button onclick="toggleAllCommunities(true)">Hide All</button>
<label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
</div>
<div id="legend"></div>
</div>
@@ -507,6 +817,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]],
@@ -532,8 +859,8 @@ def to_obsidian(
def safe_name(label: str) -> str:
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
# Strip trailing .md/.mdx/.markdown so "CLAUDE.md" doesn't become "CLAUDE.md.md"
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
cleaned = re.sub(r"\.(md|mdx|qmd|markdown)$", "", cleaned, flags=re.IGNORECASE)
return _cap_filename(cleaned) if cleaned else "unnamed"
node_filename: dict[str, str] = {}
seen_names: dict[str, int] = {}
@@ -578,20 +905,22 @@ def to_obsidian(
ftype_tag = _FTYPE_TAG.get(ftype, f"graphify/{ftype}" if ftype else "graphify/document")
dom_conf = _dominant_confidence(node_id)
conf_tag = f"graphify/{dom_conf}"
comm_tag = f"community/{community_name.replace(' ', '_')}"
comm_tag = f"community/{_obsidian_tag(community_name)}"
node_tags = [ftype_tag, conf_tag, comm_tag]
lines: list[str] = []
# YAML frontmatter - readable in Obsidian's properties panel
# YAML frontmatter - readable in Obsidian's properties panel.
# All scalars pass through _yaml_str so a hostile source_file or
# community label cannot break out and inject sibling keys (F-009).
lines += [
"---",
f'source_file: "{data.get("source_file", "")}"',
f'type: "{ftype}"',
f'community: "{community_name}"',
f'source_file: "{_yaml_str(data.get("source_file", ""))}"',
f'type: "{_yaml_str(ftype)}"',
f'community: "{_yaml_str(community_name)}"',
]
if data.get("source_location"):
lines.append(f'location: "{data["source_location"]}"')
lines.append(f'location: "{_yaml_str(str(data["source_location"]))}"')
# Add tags list to frontmatter
lines.append("tags:")
for tag in node_tags:
@@ -603,10 +932,10 @@ def to_obsidian(
if neighbors:
lines.append("## Connections")
for neighbor in sorted(neighbors, key=lambda n: G.nodes[n].get("label", n)):
edge_data = G.edges[node_id, neighbor]
edata = edge_data(G, node_id, neighbor)
neighbor_label = node_filename[neighbor]
relation = edge_data.get("relation", "")
confidence = edge_data.get("confidence", "EXTRACTED")
relation = edata.get("relation", "")
confidence = edata.get("confidence", "EXTRACTED")
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
lines.append("")
@@ -690,7 +1019,7 @@ def to_obsidian(
lines.append("")
# Dataview live query (improvement 2)
comm_tag_name = community_name.replace(" ", "_")
comm_tag_name = _obsidian_tag(community_name)
lines.append("## Live Query (requires Dataview plugin)")
lines.append("")
lines.append("```dataview")
@@ -770,8 +1099,8 @@ 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|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
cleaned = re.sub(r"\.(md|mdx|qmd|markdown)$", "", cleaned, flags=re.IGNORECASE)
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:
@@ -948,7 +1277,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:
@@ -963,7 +1295,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",
@@ -991,6 +1326,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)
+8458 -394
View File
File diff suppressed because it is too large. Load diff
+159
View File
@@ -0,0 +1,159 @@
from __future__ import annotations
import json
import hashlib
import sys
from datetime import datetime, timezone
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph as _jg
_GLOBAL_DIR = Path.home() / ".graphify"
_GLOBAL_GRAPH = _GLOBAL_DIR / "global-graph.json"
_GLOBAL_MANIFEST = _GLOBAL_DIR / "global-manifest.json"
def _load_manifest() -> dict:
if _GLOBAL_MANIFEST.exists():
try:
return json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
except Exception:
pass
return {"version": 1, "repos": {}}
def _save_manifest(manifest: dict) -> None:
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
_GLOBAL_MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
def _load_global_graph() -> nx.Graph:
if _GLOBAL_GRAPH.exists():
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"])
try:
return _jg.node_link_graph(data, edges="links")
except TypeError:
return _jg.node_link_graph(data)
return nx.Graph()
def _save_global_graph(G: nx.Graph) -> None:
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
try:
data = _jg.node_link_data(G, edges="links")
except TypeError:
data = _jg.node_link_data(G)
_GLOBAL_GRAPH.write_text(json.dumps(data, indent=2), encoding="utf-8")
def _file_hash(path: Path) -> str:
h = hashlib.sha256()
h.update(path.read_bytes())
return h.hexdigest()[:16]
def global_add(source_path: Path, repo_tag: str) -> dict:
"""Add or update a project graph in the global graph.
Returns a summary dict with keys: repo_tag, nodes_added, nodes_removed, skipped.
Skipped=True means the source graph hasn't changed since last add.
"""
from graphify.build import prefix_graph_for_global, prune_repo_from_graph
if not source_path.exists():
raise FileNotFoundError(f"graph not found: {source_path}")
manifest = _load_manifest()
src_hash = _file_hash(source_path)
existing = manifest["repos"].get(repo_tag, {})
existing_path = existing.get("source_path", "")
if existing_path and existing_path != str(source_path.resolve()):
print(
f"[graphify global] warning: repo tag '{repo_tag}' previously pointed to "
f"{existing_path!r}, now updating to {str(source_path.resolve())!r}. "
f"Use --as <tag> to give it a different name.",
file=sys.stderr,
)
if existing.get("source_hash") == src_hash:
return {"repo_tag": repo_tag, "nodes_added": 0, "nodes_removed": 0, "skipped": True}
# Load source graph
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"])
try:
src_G = _jg.node_link_graph(data, edges="links")
except TypeError:
src_G = _jg.node_link_graph(data)
# Prefix IDs for cross-project isolation
prefixed = prefix_graph_for_global(src_G, repo_tag)
# Load global graph and prune stale nodes for this repo
G = _load_global_graph()
removed = prune_repo_from_graph(G, repo_tag)
# Merge external-library nodes (no source_file) by label to avoid duplication
external_labels = {
d.get("label", ""): n
for n, d in G.nodes(data=True)
if not d.get("source_file") and d.get("label")
}
nodes_to_skip = set()
for node, data in prefixed.nodes(data=True):
if not data.get("source_file") and data.get("label") in external_labels:
nodes_to_skip.add(node)
# Compose: add prefixed nodes (except deduplicated externals) into global graph
for node, data in prefixed.nodes(data=True):
if node not in nodes_to_skip:
G.add_node(node, **data)
for u, v, data in prefixed.edges(data=True):
if u not in nodes_to_skip and v not in nodes_to_skip:
G.add_edge(u, v, **data)
added = prefixed.number_of_nodes() - len(nodes_to_skip)
_save_global_graph(G)
manifest["repos"][repo_tag] = {
"added_at": datetime.now(timezone.utc).isoformat(),
"source_path": str(source_path.resolve()),
"node_count": added,
"edge_count": prefixed.number_of_edges(),
"source_hash": src_hash,
}
_save_manifest(manifest)
return {"repo_tag": repo_tag, "nodes_added": added, "nodes_removed": removed, "skipped": False}
def global_remove(repo_tag: str) -> int:
"""Remove all nodes for repo_tag from the global graph. Returns count removed."""
from graphify.build import prune_repo_from_graph
manifest = _load_manifest()
if repo_tag not in manifest["repos"]:
raise KeyError(f"repo '{repo_tag}' not in global graph")
G = _load_global_graph()
removed = prune_repo_from_graph(G, repo_tag)
_save_global_graph(G)
del manifest["repos"][repo_tag]
_save_manifest(manifest)
return removed
def global_list() -> dict:
"""Return the manifest repos dict."""
return _load_manifest().get("repos", {})
def global_path() -> Path:
return _GLOBAL_GRAPH
+223
View File
@@ -0,0 +1,223 @@
"""Optional Google Workspace shortcut export support.
Google Drive for desktop stores native Docs, Sheets, and Slides as small JSON
shortcut files (.gdoc, .gsheet, .gslides). Those files are pointers, not the
document content. This module exports them to Markdown sidecars via the
googleworkspace CLI (`gws`) so Graphify can extract their actual contents.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
import urllib.parse
from pathlib import Path
from typing import Callable, Any
GOOGLE_WORKSPACE_EXTENSIONS = {".gdoc", ".gsheet", ".gslides"}
def google_workspace_enabled(value: str | None = None) -> bool:
"""Return True when Google Workspace shortcut export is enabled."""
raw = value if value is not None else os.environ.get("GRAPHIFY_GOOGLE_WORKSPACE", "")
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _safe_yaml_str(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
def _extract_file_id_from_url(url: str) -> str | None:
"""Extract a Drive file ID from common Google Docs/Drive URL shapes."""
if not url:
return None
parsed = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(parsed.query)
if query.get("id"):
return query["id"][0]
match = re.search(r"/(?:document|spreadsheets|presentation|file)/d/([^/?#]+)", parsed.path)
if match:
return match.group(1)
return None
def _extract_resource_key(url: str, data: dict[str, Any]) -> str | None:
for key in ("resource_key", "resourceKey"):
value = data.get(key)
if value:
return str(value)
if not url:
return None
parsed = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(parsed.query)
if query.get("resourcekey"):
return query["resourcekey"][0]
return None
def read_google_shortcut(path: Path) -> dict[str, str | None]:
"""Read a .gdoc/.gsheet/.gslides shortcut and return export metadata."""
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
raise RuntimeError(f"could not read Google Workspace shortcut {path}: {exc}") from exc
url = str(data.get("url") or "")
file_id = (
data.get("doc_id")
or data.get("file_id")
or data.get("fileId")
or data.get("id")
or _extract_file_id_from_url(url)
)
if not file_id:
resource_id = str(data.get("resource_id") or "")
if ":" in resource_id:
file_id = resource_id.split(":", 1)[1]
if not file_id:
raise RuntimeError(f"Google Workspace shortcut {path} does not include a Drive file ID")
return {
"file_id": str(file_id),
"url": url or None,
"resource_key": _extract_resource_key(url, data),
"account": str(data.get("email")) if data.get("email") else None,
}
def _run_gws_export(file_id: str, mime_type: str, output: Path, resource_key: str | None = None) -> None:
exe = shutil.which("gws")
if not exe:
raise RuntimeError(
"gws is required for Google Workspace export. Install it from "
"https://github.com/googleworkspace/cli and run `gws auth login -s drive`."
)
params: dict[str, str] = {"fileId": file_id, "mimeType": mime_type}
# Drive resource keys are sent via X-Goog-Drive-Resource-Keys. The current
# gws export command has no custom-header flag, so do not pass resourceKey
# as an unsupported query parameter.
_ = resource_key
output = output.resolve()
output.parent.mkdir(parents=True, exist_ok=True)
timeout = int(os.environ.get("GRAPHIFY_GOOGLE_WORKSPACE_TIMEOUT", "120"))
result = subprocess.run(
[exe, "drive", "files", "export", "--params", json.dumps(params), "-o", output.name],
capture_output=True,
cwd=output.parent,
text=True,
timeout=timeout,
)
if result.returncode != 0:
stderr = (result.stderr or result.stdout or "").strip()
if len(stderr) > 1200:
stderr = stderr[:1200] + "..."
raise RuntimeError(f"gws export failed for {file_id}: {stderr}")
def _sidecar_path(path: Path, out_dir: Path) -> Path:
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
return out_dir / f"{path.stem}_{name_hash}.md"
def _with_frontmatter(path: Path, shortcut: dict[str, str | None], body: str, exported_mime_type: str) -> str:
source_url = shortcut.get("url") or ""
account = shortcut.get("account") or ""
account_line = ""
if account:
account_hash = hashlib.sha256(account.encode()).hexdigest()[:12]
account_line = f'google_account_hash: "{account_hash}"\n'
return (
"---\n"
f'source_file: "{_safe_yaml_str(str(path))}"\n'
'source_type: "google_workspace"\n'
f'google_file_id: "{_safe_yaml_str(shortcut["file_id"] or "")}"\n'
f'google_export_mime_type: "{_safe_yaml_str(exported_mime_type)}"\n'
f'source_url: "{_safe_yaml_str(source_url)}"\n'
f"{account_line}"
"---\n\n"
f"<!-- converted from Google Workspace shortcut: {path.name} -->\n\n"
f"{body.strip()}\n"
)
def convert_google_workspace_file(
path: Path,
out_dir: Path,
*,
xlsx_to_markdown: Callable[[Path], str] | None = None,
) -> Path | None:
"""Export a Google Workspace shortcut to a Markdown sidecar.
Returns the converted Markdown path, or None when conversion is unsupported
or produced no readable content.
"""
ext = path.suffix.lower()
if ext not in GOOGLE_WORKSPACE_EXTENSIONS:
return None
shortcut = read_google_shortcut(path)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = _sidecar_path(path, out_dir)
if ext == ".gdoc":
with tempfile.NamedTemporaryFile("w+b", suffix=".md", delete=False, dir=out_dir) as tmp:
tmp_path = Path(tmp.name)
try:
_run_gws_export(shortcut["file_id"] or "", "text/markdown", tmp_path, shortcut.get("resource_key"))
body = tmp_path.read_text(encoding="utf-8", errors="replace")
finally:
tmp_path.unlink(missing_ok=True)
if not body.strip():
return None
out_path.write_text(_with_frontmatter(path, shortcut, body, "text/markdown"), encoding="utf-8")
return out_path
if ext == ".gslides":
with tempfile.NamedTemporaryFile("w+b", suffix=".txt", delete=False, dir=out_dir) as tmp:
tmp_path = Path(tmp.name)
try:
_run_gws_export(shortcut["file_id"] or "", "text/plain", tmp_path, shortcut.get("resource_key"))
body = tmp_path.read_text(encoding="utf-8", errors="replace")
finally:
tmp_path.unlink(missing_ok=True)
if not body.strip():
return None
out_path.write_text(_with_frontmatter(path, shortcut, body, "text/plain"), encoding="utf-8")
return out_path
if ext == ".gsheet":
if xlsx_to_markdown is None:
raise RuntimeError("Google Sheets export requires the office extra: pip install graphifyy[office,google]")
with tempfile.NamedTemporaryFile("w+b", suffix=".xlsx", delete=False, dir=out_dir) as tmp:
tmp_path = Path(tmp.name)
try:
_run_gws_export(
shortcut["file_id"] or "",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
tmp_path,
shortcut.get("resource_key"),
)
body = xlsx_to_markdown(tmp_path)
finally:
tmp_path.unlink(missing_ok=True)
if not body.strip():
return None
out_path.write_text(
_with_frontmatter(
path,
shortcut,
body,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
),
encoding="utf-8",
)
return out_path
return None
+293 -73
View File
@@ -1,7 +1,8 @@
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
from __future__ import annotations
import configparser
import re
import subprocess
import sys
from pathlib import Path
_HOOK_MARKER = "# graphify-hook-start"
@@ -9,60 +10,76 @@ _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"
$GRAPHIFY_PYTHON -c "
import os, sys
# 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
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
@@ -74,13 +91,147 @@ if not changed:
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
try:
from graphify.watch import _rebuild_code
_rebuild_code(Path('.'))
from graphify.watch import _rebuild_code, _apply_resource_limits
_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')
_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-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
"""
@@ -89,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
@@ -111,18 +267,11 @@ GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
""" + _PYTHON_DETECT + """
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
$GRAPHIFY_PYTHON -c "
from graphify.watch import _rebuild_code
from pathlib import Path
import sys
try:
_rebuild_code(Path('.'))
except Exception as exc:
print(f'[graphify] Rebuild failed: {exc}')
sys.exit(1)
"
# graphify-checkout-hook-end
_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)"
""" + _detached_launch(_REBUILD_BODY_CHECKOUT) + """# graphify-checkout-hook-end
"""
@@ -138,22 +287,57 @@ def _git_root(path: Path) -> Path | None:
def _hooks_dir(root: Path) -> Path:
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
try:
result = subprocess.run(
["git", "-C", str(root), "config", "core.hooksPath"],
capture_output=True, text=True,
)
if result.returncode == 0:
custom = result.stdout.strip()
if custom:
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
cfg = configparser.RawConfigParser()
cfg.read(root / ".git" / "config", encoding="utf-8")
# configparser lowercases option names; git's hooksPath becomes hookspath
custom = cfg.get("core", "hookspath", fallback="").strip()
if custom:
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
# Validate the resolved path stays within the repository root
# to prevent supply-chain attacks via malicious core.hooksPath values
try:
p.resolve().relative_to(root.resolve())
except ValueError:
pass # Path escapes repo root; fall through to default .git/hooks
else:
p.mkdir(parents=True, exist_ok=True)
return p
except (configparser.Error, OSError) as exc:
# Narrow the exception (PR747-NEW-2): a bare `except Exception: pass`
# was hiding tampering signals (corrupt .git/config, permission flips
# by another tool). Surface them on stderr instead of silently
# falling through to the default hooks directory.
print(
f"[graphify hooks] could not read core.hooksPath from "
f"{root / '.git' / 'config'}: {exc}",
file=sys.stderr,
)
# 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", "--git-path", "hooks"],
capture_output=True, text=True,
)
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")):
d = (root / raw).resolve()
d.mkdir(parents=True, exist_ok=True)
return d
except (OSError, FileNotFoundError):
pass
d = root / ".git" / "hooks"
d.mkdir(exist_ok=True)
d.mkdir(parents=True, exist_ok=True)
return d
@@ -192,16 +376,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}"
@@ -212,7 +432,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)
@@ -224,7 +444,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
+47 -13
View File
@@ -11,8 +11,45 @@ from graphify.security import safe_fetch, safe_fetch_text, validate_url
def _yaml_str(s: str) -> str:
"""Escape a string for embedding in a YAML double-quoted scalar."""
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
"""Escape a string for embedding in a YAML double-quoted scalar.
Handles every YAML 1.1/1.2 line-break and control character that could
let a hostile value (e.g. a fetched page title) break out of the quoted
scalar and inject sibling YAML keys (F-009 / F-019). The previous
implementation missed `\\t`, `\\0`, the unicode line-separator U+2028 and
paragraph-separator U+2029 — all of which YAML treats as line breaks.
We intentionally do not depend on PyYAML (not in pyproject deps) and
instead emit safely-escaped double-quoted scalars by hand: the YAML
double-quoted form recognises `\\\\`, `\\"`, `\\n`, `\\r`, `\\t`, `\\0`,
`\\L` (U+2028), `\\P` (U+2029), and `\\xNN`/`\\uNNNN` numeric escapes.
"""
if s is None:
return ""
out: list[str] = []
for ch in str(s):
cp = ord(ch)
if ch == "\\":
out.append("\\\\")
elif ch == '"':
out.append('\\"')
elif ch == "\n":
out.append("\\n")
elif ch == "\r":
out.append("\\r")
elif ch == "\t":
out.append("\\t")
elif ch == "\0":
out.append("\\0")
elif cp == 0x2028:
out.append("\\L")
elif cp == 0x2029:
out.append("\\P")
elif cp < 0x20 or cp == 0x7F:
out.append(f"\\x{cp:02x}")
else:
out.append(ch)
return "".join(out)
def _safe_filename(url: str, suffix: str) -> str:
@@ -49,19 +86,16 @@ def _fetch_html(url: str) -> str:
def _html_to_markdown(html: str, url: str) -> str:
"""Convert HTML to clean markdown. Uses html2text if available, else basic strip."""
"""Convert HTML to clean markdown. Uses markdownify if available, else basic strip."""
# Always pre-strip script/style so their text content never leaks into output
html = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
html = re.sub(r"<style[^>]*>.*?</style>", "", html, flags=re.DOTALL | re.IGNORECASE)
try:
import html2text
h = html2text.HTML2Text()
h.ignore_links = False
h.ignore_images = True
h.body_width = 0
return h.handle(html)
from markdownify import markdownify
return markdownify(html, heading_style="ATX", bullets="-", strip=["img"])
except ImportError:
# Fallback: strip tags
text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
text = re.sub(r"<[^>]+>", " ", text)
# Fallback: basic tag strip
text = re.sub(r"<[^>]+>", " ", html)
text = re.sub(r"\s+", " ", text).strip()
return text[:8000]
+1896
View File
File diff suppressed because it is too large. Load diff
+392
View File
@@ -0,0 +1,392 @@
"""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.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. Must match extract._make_id's normalisation rules."""
combined = "_".join(p.strip("_.") for p in parts if p)
combined = unicodedata.normalize("NFKC", combined)
cleaned = re.sub(r"[^\w]+", "_", combined, flags=re.UNICODE)
cleaned = re.sub(r"_+", "_", cleaned)
return cleaned.strip("_").casefold()
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
+748
View File
@@ -0,0 +1,748 @@
"""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 subprocess as _sp
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
+46 -9
View File
@@ -23,9 +23,15 @@ def generate(
token_cost: dict,
root: str,
suggested_questions: list[dict] | None = None,
min_community_size: int = 3,
built_at_commit: str | None = None,
) -> str:
today = date.today().isoformat()
# 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)
@@ -52,16 +58,31 @@ def generate(
from .analyze import _is_file_node as _ifn
non_empty = {cid: nodes for cid, nodes in communities.items()
if any(not _ifn(G, n) for n in nodes)}
thin_count_summary = sum(
1 for nodes in communities.values()
if 0 < sum(1 for n in nodes if not _ifn(G, n)) < min_community_size
)
shown_count = len(communities) - thin_count_summary
lines += [
"",
"## Summary",
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(non_empty)} communities detected",
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities"
+ (f" ({shown_count} shown, {thin_count_summary} thin omitted)" if thin_count_summary else ""),
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS"
+ (f" · INFERRED: {len(inf_edges)} edges (avg confidence: {inf_avg})" if inf_avg is not None else ""),
f"- Token cost: {token_cost.get('input', 0):,} input · {token_cost.get('output', 0):,} output",
]
if built_at_commit:
lines += [
"",
"## Graph Freshness",
f"- Built from commit: `{built_at_commit[:8]}`",
"- Run `git rev-parse HEAD` and compare to check if the graph is stale.",
"- Run `graphify update .` after code changes (no API cost).",
]
# Community hub navigation - links to _COMMUNITY_*.md files in the Obsidian vault.
# Without these, GRAPH_REPORT.md is a dead-end and the vault splits into disconnected components.
if non_empty:
@@ -98,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)"]
@@ -108,7 +144,7 @@ def generate(
conf_tag = f"{conf} {cscore:.2f}" if cscore is not None else conf
lines.append(f"- **{h.get('label', h.get('id', ''))}** — {node_labels} [{conf_tag}]")
lines += ["", "## Communities"]
lines += ["", f"## Communities ({len(communities)} total, {thin_count_summary} thin omitted)"]
for cid, nodes in communities.items():
label = community_labels.get(cid, f"Community {cid}")
score = cohesion_scores.get(cid, 0.0)
@@ -116,12 +152,14 @@ def generate(
real_nodes = [n for n in nodes if not _ifn(G, n)]
if not real_nodes:
continue
if len(real_nodes) < min_community_size:
continue
display = [G.nodes[n].get("label", n) for n in real_nodes[:8]]
suffix = f" (+{len(real_nodes)-8} more)" if len(real_nodes) > 8 else ""
lines += [
"",
f"### Community {cid} - \"{label}\"",
f"Cohesion: {score}",
f"Cohesion: {score:.2f}",
f"Nodes ({len(real_nodes)}): {', '.join(display)}{suffix}",
]
@@ -141,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()
@@ -157,11 +198,7 @@ def generate(
lines.append(f"- **{len(isolated)} isolated node(s):** {', '.join(f'`{l}`' for l in isolated_labels)}{suffix}")
lines.append(" These have ≤1 connection - possible missing edges or undocumented components.")
if thin_communities:
for cid, nodes in thin_communities.items():
label = community_labels.get(cid, f"Community {cid}")
node_labels = [G.nodes[n].get("label", n) for n in nodes]
lines.append(f"- **Thin community `{label}`** ({len(nodes)} nodes): {', '.join(f'`{l}`' for l in node_labels)}")
lines.append(" Too small to be a meaningful cluster - may be noise or needs more connections extracted.")
lines.append(f"- **{len(thin_communities)} thin communities (<{min_community_size} nodes) omitted from report** — run `graphify query` to explore isolated nodes.")
if amb_pct > 20:
lines.append(f"- **High ambiguity: {amb_pct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.")
+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
+135 -4
View File
@@ -1,12 +1,15 @@
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
from __future__ import annotations
import contextlib
import html
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
@@ -15,9 +18,22 @@ _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.
_MAX_GRAPH_FILE_BYTES = 512 * 1024 * 1024 # 512 MiB
# 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
@@ -53,17 +69,54 @@ 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:
# For NAT64 addresses, check the embedded IPv4 instead of the wrapper
if isinstance(ip, ipaddress.IPv6Address) and ip in _NAT64_WKP:
embedded = ipaddress.ip_address(int(ip) & 0xFFFFFFFF)
ip = embedded
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local or ip in _CGN_NETWORK:
raise ValueError(
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
f"Got: {url!r}"
)
except socket.gaierror:
pass # DNS failure will surface later during fetch
except socket.gaierror as exc:
raise ValueError(
f"DNS resolution failed for '{hostname}': {exc}. Got: {url!r}"
) from exc
return url
@contextlib.contextmanager
def _ssrf_guarded_socket():
"""Patch socket.getaddrinfo for the duration of a fetch to catch DNS rebinding.
Validates every IP that urllib resolves so a DNS server cannot return a public IP
for validate_url and swap to a private IP for the actual connection (TOCTOU fix).
Not thread-safe, but graphify is a single-threaded CLI tool.
"""
original = socket.getaddrinfo
def _guarded(host, port, *args, **kwargs):
results = original(host, port, *args, **kwargs)
for info in results:
addr = info[4][0]
try:
ip = ipaddress.ip_address(addr)
except ValueError:
continue
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local 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 _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
"""Redirect handler that re-validates every redirect target.
@@ -104,7 +157,7 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
opener = _build_opener()
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 graphify/1.0"})
with opener.open(req, timeout=timeout) as resp:
with _ssrf_guarded_socket(), opener.open(req, timeout=timeout) as resp:
# urllib raises HTTPError for non-2xx when using urlopen directly;
# with a custom opener we check manually to be safe.
status = getattr(resp, "status", None) or getattr(resp, "code", None)
@@ -183,6 +236,29 @@ 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 ``_MAX_GRAPH_FILE_BYTES``.
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.
Raises:
ValueError - file size exceeds the cap. The message includes the
observed size and the cap so callers can show a usable error.
"""
try:
size = path.stat().st_size
except OSError:
return
if size > _MAX_GRAPH_FILE_BYTES:
raise ValueError(
f"graph file {path} is {size:_d} bytes, "
f"exceeds {_MAX_GRAPH_FILE_BYTES:_d}-byte cap"
)
# ---------------------------------------------------------------------------
# Label sanitisation (mirrors code-review-graph's _sanitize_name pattern)
# ---------------------------------------------------------------------------
@@ -203,3 +279,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
+980 -44
View File
File diff suppressed because it is too large. Load diff
+114 -52
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
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."
trigger: /graphify
---
@@ -51,6 +51,8 @@ Use it for:
## 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.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -58,30 +60,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
@@ -168,7 +187,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
@@ -202,7 +221,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
@@ -235,7 +254,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. 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.
@@ -244,7 +263,7 @@ Process each file one at a time. For each file:
3. Accumulate results across all files
Schema for each file's output:
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|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`.
@@ -254,9 +273,33 @@ For the accumulated result:
If more than half the chunks failed, stop and tell the user.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
total_in, total_out = 0, 0
for c in chunks:
d = json.loads(Path(c).read_text())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
'input_tokens': total_in, 'output_tokens': total_out,
}, indent=2))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
@@ -269,7 +312,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
@@ -302,7 +345,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
@@ -337,7 +380,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
@@ -390,7 +433,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
@@ -430,7 +473,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
@@ -461,7 +504,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
@@ -488,7 +531,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
@@ -503,7 +546,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
@@ -525,7 +568,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
@@ -547,7 +590,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
@@ -589,7 +632,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
@@ -607,7 +650,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
@@ -641,7 +684,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
```
@@ -681,7 +724,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
@@ -690,17 +733,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
@@ -717,10 +764,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
@@ -747,7 +809,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
@@ -781,7 +843,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
@@ -834,7 +896,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.')
@@ -852,7 +914,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
@@ -928,7 +990,7 @@ for nid in ranked_nodes:
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
d = G.edges[u, v]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
output = '\n'.join(lines)
@@ -943,7 +1005,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.
@@ -956,7 +1018,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.')
@@ -966,7 +1028,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
@@ -1000,7 +1062,7 @@ try:
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
edge = G.edges[nid, path[i+1]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1018,7 +1080,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
```
---
@@ -1029,7 +1091,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.')
@@ -1039,7 +1101,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1070,7 +1132,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
@@ -1084,7 +1146,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
```
---
@@ -1094,7 +1156,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
+613
View File
@@ -0,0 +1,613 @@
---
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."
trigger: /graphify
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory → 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> --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\"))
G = build_from_json(extraction)
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\"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
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, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-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>"
```
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 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.
+207 -775
View File
File diff suppressed because it is too large. Load diff
+181 -811
View File
File diff suppressed because it is too large. Load diff
+152 -805
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+185 -812
View File
File diff suppressed because it is too large. Load diff
+625
View File
@@ -0,0 +1,625 @@
---
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."
trigger: /graphify
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory → 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> --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\"))
G = build_from_json(extraction)
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\"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
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, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-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>"
```
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 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.
+207 -775
View File
File diff suppressed because it is too large. Load diff
+161 -846
View File
File diff suppressed because it is too large. Load diff
+615
View File
@@ -0,0 +1,615 @@
---
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> --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\"))
G = build_from_json(extraction)
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\"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
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, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-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>"
```
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 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.
+196 -791
View File
File diff suppressed because it is too large. Load diff
+498 -139
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
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."
trigger: /graphify
---
@@ -11,243 +11,602 @@ 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> --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.
for chunk_json in []: # replace [] with your chunk results
chunk = json.loads(chunk_json) if isinstance(chunk_json, str) else chunk_json
all_nodes.extend(chunk.get('nodes', []))
all_edges.extend(chunk.get('edges', []))
all_hyperedges.extend(chunk.get('hyperedges', []))
merged = {'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, 'input_tokens': 0, 'output_tokens': 0}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
print(f'Merged: {len(all_nodes)} nodes, {len(all_edges)} edges')
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')
"
```
### 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())
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\"))
G = build_from_json(extraction)
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)
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, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-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>"
```
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 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.
+225 -820
View File
File diff suppressed because it is too large. Load diff
+121 -883
View File
File diff suppressed because it is too large. Load diff
@@ -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.
+71
View File
@@ -0,0 +1,71 @@
# graphify reference: extra exports and benchmark
Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-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 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,68 @@
# 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":"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
```
@@ -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
```
+249
View File
@@ -0,0 +1,249 @@
# graphify reference: query, path, explain
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise.
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 |
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
```
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
mode = 'MODE' # 'bfs' or 'dfs'
terms = [t.lower() for t in question.split() if len(t) > 3]
# Find best-matching start nodes
scored = []
for nid, ndata in G.nodes(data=True):
label = ndata.get('label', '').lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
scored.sort(reverse=True)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
print('No matching nodes found for query terms:', terms)
sys.exit(0)
subgraph_nodes = set()
subgraph_edges = []
if mode == 'dfs':
# DFS: follow one path as deep as possible before backtracking.
# Depth-limited to 6 to avoid traversing the whole graph.
visited = set()
stack = [(n, 0) for n in reversed(start_nodes)]
while stack:
node, depth = stack.pop()
if node in visited or depth > 6:
continue
visited.add(node)
subgraph_nodes.add(node)
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, depth + 1))
subgraph_edges.append((node, neighbor))
else:
# BFS: explore all neighbors layer by layer up to depth 3.
frontier = set(start_nodes)
subgraph_nodes = set(start_nodes)
for _ in range(3):
next_frontier = set()
for n in frontier:
for neighbor in G.neighbors(n):
if neighbor not in subgraph_nodes:
next_frontier.add(neighbor)
subgraph_edges.append((n, neighbor))
subgraph_nodes.update(next_frontier)
frontier = next_frontier
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
token_budget = BUDGET # default 2000
char_budget = token_budget * 4
# Score each node by term overlap for ranked output
def relevance(nid):
label = G.nodes[nid].get('label', '').lower()
return sum(1 for t in terms if t in label)
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
for nid in ranked_nodes:
d = G.nodes[nid]
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
output = '\n'.join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
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 user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
b_term = 'NODE_B'
def find_node(term):
term = term.lower()
scored = sorted(
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
return scored[0][1] if scored and scored[0][0] > 0 else None
src = find_node(a_term)
tgt = find_node(b_term)
if not src or not tgt:
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
sys.exit(0)
try:
path = nx.shortest_path(G, src, tgt)
print(f'Shortest path ({len(path)-1} hops):')
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
else:
print(f' {label}')
except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
"
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
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
```
---
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
term_lower = term.lower()
# Find best matching node
scored = sorted(
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
if not scored or scored[0][0] == 0:
print(f'No node matching {term!r}')
sys.exit(0)
nid = scored[0][1]
data_n = G.nodes[nid]
print(f'NODE: {data_n.get(\"label\", nid)}')
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
"
```
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
```
@@ -0,0 +1,48 @@
# graphify reference: transcribe video and audio
Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this.
### Step 2.5 - Transcribe video / audio files (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.
+179
View File
@@ -0,0 +1,179 @@
# graphify reference: incremental update and cluster-only
Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file.
## For --update (incremental re-extraction)
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\")
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)
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.')
"
```
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.
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-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', []))
# Also prune old nodes for re-extracted (changed) files before inserting fresh AST.
# Without this, build_merge's dedup pass tries to reconcile old and new versions of
# the same file's nodes and can collapse same-named symbols across files (#1178).
changed = [f for files in incremental.get('new_files', {}).values() for f in files]
prune = list(dict.fromkeys(deleted + changed)) or None
# 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=prune,
)
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).
Loaded 100 of 499 files, more files were not shown because too many files have changed in this diff. Show more