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
105 changed files with 5775 additions and 476 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
+1
View File
@@ -36,3 +36,4 @@ scripts/run_k2_*.py
scripts/llm.py
scripts/benchmark_kimi*.json
scripts/benchmark_kimi*.py
paper/
+40
View File
@@ -2,6 +2,46 @@
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.
+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"]
+66 -10
View File
@@ -119,12 +119,15 @@ for example `graphify claude install --project` or `graphify codex install --pro
> **Avoid `pip install` on Mac/Windows** if possible. The skill resolves Python at runtime from `graphify-out/.graphify_python`; if that points to a different environment than where `pip` installed the package, you'll get `ModuleNotFoundError: No module named 'graphify'`. `uv tool install` and `pipx install` isolate the package in their own env and avoid this entirely.
> **Git hooks and uv tool / pipx:** `graphify hook install` embeds the current interpreter path directly into the hook scripts at install time, so the post-commit hook fires correctly even in GUI git clients and CI runners where `~/.local/bin` is not on PATH. If you reinstall or upgrade graphify, re-run `graphify hook install` to refresh the embedded path.
### Pick your platform
| Platform | Install command |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install --platform windows` |
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| Kilo Code | `graphify install --platform kilo` |
@@ -145,7 +148,8 @@ for example `graphify claude install --project` or `graphify codex install --pro
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
> Codex users: also add `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as Claude Code. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism.
> Codex uses `$graphify` instead of `/graphify`.
### Optional extras
@@ -167,8 +171,11 @@ Install only what you need:
| `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]"` |
@@ -181,6 +188,7 @@ 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` |
@@ -203,6 +211,10 @@ Run this once in your project after building a graph:
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.
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`).
---
@@ -225,7 +237,9 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| Type | Extensions |
|------|-----------|
| Code (33 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .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` AST extraction requires `uv tool install graphifyy[dm]`) |
| 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]`) |
@@ -287,7 +301,9 @@ See the [full command reference](#full-command-reference) below.
## Ignoring files
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation:
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation.
**`.gitignore` is respected automatically.** 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
@@ -309,11 +325,12 @@ dist/
**Recommended `.gitignore` additions:**
```
graphify-out/manifest.json # mtime-based, breaks after git clone
graphify-out/cost.json # local only
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
```
> `manifest.json` is now portable — keys are stored as relative paths and re-anchored on load, so committing it is safe and avoids a full rebuild on first checkout.
**Workflow:**
1. One person runs `/graphify .` and commits `graphify-out/`.
2. Everyone pulls — their assistant reads the graph immediately.
@@ -334,10 +351,37 @@ 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 MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
### Shared HTTP server
`--transport stdio` (the default) spawns one local server per developer. `--transport http` serves the same tools over the MCP Streamable HTTP transport, so a single shared process can serve the graph for the whole team — clients point their IDE MCP config at `http://<host>:8080/mcp` instead of running graphify locally.
| Flag | Default | Purpose |
|---|---|---|
| `--transport {stdio,http}` | `stdio` | Transport to serve on |
| `--host` | `127.0.0.1` | HTTP bind host (use `0.0.0.0` to expose beyond localhost) |
| `--port` | `8080` | HTTP bind port |
| `--api-key` | env `GRAPHIFY_API_KEY` | Require `Authorization: Bearer <key>` (or `X-API-Key`) |
| `--path` | `/mcp` | HTTP mount path |
| `--json-response` | off | Return plain JSON instead of SSE streams |
| `--stateless` | off | No per-session state (for load-balanced / CI deployments) |
| `--session-timeout` | `3600` | Reap idle stateful sessions after N seconds (`0` disables) |
The default `127.0.0.1` bind is loopback-only. Set `--host 0.0.0.0` **and** `--api-key` together when exposing on a shared host. Run it in a container:
```bash
docker build -t graphify .
docker run -p 8080:8080 -v "$(pwd)/graphify-out:/data" graphify \
/data/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
```
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Use a venv to avoid conflicts:
> ```bash
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
@@ -360,24 +404,32 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
| `OLLAMA_MODEL` | Ollama model name | `--backend ollama` (default: auto-detect) |
| `GRAPHIFY_OLLAMA_NUM_CTX` | Override Ollama KV-cache window size | optional — auto-sized by default |
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | Minutes to keep Ollama model loaded | optional — set `0` to unload after each chunk |
| `AZURE_OPENAI_API_KEY` | Azure OpenAI Service backend | `--backend azure` |
| `AZURE_OPENAI_ENDPOINT` | Azure resource endpoint URL | `--backend azure` (required alongside API key) |
| `AZURE_OPENAI_API_VERSION` | Azure API version override | optional — default `2024-12-01-preview` |
| `AZURE_OPENAI_DEPLOYMENT` or `GRAPHIFY_AZURE_MODEL` | Azure deployment name | optional — default `gpt-4o` |
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — standard credential chain | `--backend bedrock` (no API key, uses IAM) |
| `GRAPHIFY_MAX_WORKERS` | AST parallelism thread count | optional — also `--max-workers` flag |
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Raise output cap for dense corpora | optional — e.g. `32768` for large files |
| `GRAPHIFY_API_TIMEOUT` | HTTP timeout in seconds (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_API_TIMEOUT` | Per-call timeout in seconds for HTTP, claude-cli, and Anthropic SDK backends (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_FORCE` | Force graph rebuild even with fewer nodes | optional — also `--force` flag |
| `GRAPHIFY_GOOGLE_WORKSPACE` | Auto-enable Google Workspace export | optional — set to `1` |
| `GRAPHIFY_TRIAGE_BACKEND` | Backend for `graphify prs --triage` | optional — auto-detected from available keys |
| `GRAPHIFY_TRIAGE_MODEL` | Model override for triage | optional — e.g. `claude-opus-4-7` |
| `GRAPHIFY_QUERY_LOG` | Override query log path (default: `~/.cache/graphify-queries.log`) | optional — set to empty or `/dev/null` to silence |
| `GRAPHIFY_QUERY_LOG_DISABLE` | Set to `1` to disable query logging entirely | optional |
| `GRAPHIFY_QUERY_LOG_RESPONSES` | Set to `1` to also log full subgraph responses (off by default) | optional |
---
## Privacy
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine.
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine. A code-only corpus requires no API key — `graphify extract` runs fully offline.
- **Video / audio** — transcribed locally with faster-whisper. Nothing leaves your machine.
- **Docs, PDFs, images** — sent to your AI assistant for semantic extraction (via the `/graphify` skill, using whatever model your IDE session runs). Headless `graphify extract` requires `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), `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 → 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.
- **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.
---
@@ -399,7 +451,7 @@ PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash)
If a refactor deleted files, the old nodes linger. Pass `--force` (or set `GRAPHIFY_FORCE=1`) to overwrite even when the rebuild has fewer nodes.
**Graph has duplicate nodes for the same entity (ghost duplicates)**
This happens when semantic and AST extraction disagreed on the node ID format. Run a full re-extract to clean up:
Ghost duplicates (same symbol appearing twice — once from AST extraction with a source location, once from semantic extraction without) are now automatically merged at build time. If you see this in a graph built before v0.8.33, run a full re-extract to clean up:
```bash
graphify extract . --force
```
@@ -421,7 +473,7 @@ graphify query "..."
Run `graphify hook install` — it sets up a git merge driver that union-merges `graph.json` automatically so conflicts never happen.
**Extraction returns empty nodes/edges for docs or PDFs**
Docs and PDFs require an LLM call. Check that your API key is set and the backend is correct:
Docs, PDFs, and images require an LLM call — code-only corpora need no key. Check that your API key is set and the backend is correct:
```bash
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
@@ -474,6 +526,8 @@ 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
@@ -515,7 +569,9 @@ GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # overr
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)
+7 -3
View File
@@ -5,7 +5,7 @@
[![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`)。
+357 -135
View File
@@ -415,7 +415,7 @@ _PLATFORM_CONFIG: dict[str, dict] = {
},
"codex": {
"skill_file": "skill-codex.md",
"skill_dst": Path(".agents") / "skills" / "graphify" / "SKILL.md",
"skill_dst": Path(".codex") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
"skill_refs": "codex",
},
@@ -487,6 +487,13 @@ _PLATFORM_CONFIG: dict[str, dict] = {
"claude_md": False,
"skill_refs": "pi",
},
"codebuddy": {
# Reuses claude's split bundle (shares skill.md).
"skill_file": "skill.md",
"skill_dst": Path(".codebuddy") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
"skill_refs": "claude",
},
"antigravity": {
# Rides claude's split bundle (shares skill.md).
"skill_file": "skill.md",
@@ -578,7 +585,38 @@ def _replace_or_append_section(content: str, marker: str, new_section: str) -> s
return out
def _print_banner() -> None:
"""Amber brain banner on graphify install. TTY-only, never raises."""
if not sys.stdout.isatty():
return
try:
if sys.platform == "win32":
import ctypes
ctypes.windll.kernel32.SetConsoleMode(
ctypes.windll.kernel32.GetStdHandle(-11), 7
)
A = "\033[38;5;214m"
D = "\033[38;5;130m"
R = "\033[0m"
print(f"""{A}
╭──◉──╮ ╭──◉──╮
╱ ◉ ◉ ╲ ╱ ◉ ◉ ╲
│ ◉─◉─◉ ◉ ◉─◉─◉ │
│ ◉ ◉ │ ◉ ◉ │
│ ◉─◉─◉ ◉ ◉─◉─◉ │
╲ ◉ ◉ ╱ ╲ ◉ ◉ ╱
╰──◉──╯ ╰──◉──╯
◉
█▀▀ █▀█ ▄▀█ █▀█ █ █ █ █▀▀ █▄█
█▄█ █▀▄ █▀█ █▀▀ █▀█ █ █▀ █{D} {__version__}{R}
""")
except Exception:
pass
def install(platform: str = "claude", *, project: bool = False, project_dir: Path | None = None) -> None:
_print_banner()
if platform == "gemini":
gemini_install(project_dir=project_dir, project=project)
return
@@ -629,6 +667,22 @@ def install(platform: str = "claude", *, project: bool = False, project_dir: Pat
claude_md.write_text(registration.lstrip(), encoding="utf-8")
print(f" CLAUDE.md -> created at {claude_md}")
if platform == "codebuddy":
# Register in ~/.codebuddy/CODEBUDDY.md (CodeBuddy only)
codebuddy_md = Path.home() / ".codebuddy" / "CODEBUDDY.md"
registration = _skill_registration("~/.codebuddy/skills/graphify/SKILL.md")
if codebuddy_md.exists():
content = codebuddy_md.read_text(encoding="utf-8")
if "graphify" in content:
print(f" CODEBUDDY.md -> already registered (no change)")
else:
codebuddy_md.write_text(content.rstrip() + registration, encoding="utf-8")
print(f" CODEBUDDY.md -> skill registered in {codebuddy_md}")
else:
codebuddy_md.parent.mkdir(parents=True, exist_ok=True)
codebuddy_md.write_text(registration.lstrip(), encoding="utf-8")
print(f" CODEBUDDY.md -> created at {codebuddy_md}")
if platform == "opencode":
_install_opencode_plugin(project_dir if project else Path("."))
@@ -659,6 +713,8 @@ def _print_install_usage() -> None:
_CLAUDE_MD_MARKER = "## graphify"
_CODEBUDDY_MD_MARKER = "## graphify"
# AGENTS.md section for Codex, OpenCode, and OpenClaw.
# All three platforms read AGENTS.md in the project root for persistent instructions.
@@ -901,12 +957,11 @@ def _kiro_install(project_dir: Path) -> None:
"""Write graphify skill + steering file for Kiro IDE/CLI."""
project_dir = project_dir or Path(".")
# Skill file → .kiro/skills/graphify/SKILL.md
skill_src = Path(__file__).parent / "skill-kiro.md"
skill_dst = project_dir / ".kiro" / "skills" / "graphify" / "SKILL.md"
skill_dst.parent.mkdir(parents=True, exist_ok=True)
skill_dst.write_text(skill_src.read_text(encoding="utf-8"), encoding="utf-8")
print(f" {skill_dst.relative_to(project_dir)} -> /graphify skill")
# Skill file + references/ sidecar + .graphify_version stamp via the shared
# progressive-disclosure helper. Previously this used a bare write_text that
# bypassed _copy_skill_file, so the references/ dir and version stamp were
# never written even though kiro declares skill_refs: "kiro" (#1142).
_copy_skill_file("kiro", project=True, project_dir=project_dir)
# Steering file → .kiro/steering/graphify.md (always-on)
steering_dir = project_dir / ".kiro" / "steering"
@@ -931,15 +986,10 @@ def _kiro_uninstall(project_dir: Path) -> None:
project_dir = project_dir or Path(".")
removed = []
skill_dst = project_dir / ".kiro" / "skills" / "graphify" / "SKILL.md"
if skill_dst.exists():
skill_dst.unlink()
# Skill + .graphify_version + references/ sidecar + empty-dir walk.
skill_dst = _platform_skill_destination("kiro", project=True, project_dir=project_dir)
if _remove_skill_file("kiro", project=True, project_dir=project_dir):
removed.append(str(skill_dst.relative_to(project_dir)))
# Remove parent dir if empty
try:
skill_dst.parent.rmdir()
except OSError:
pass
steering_dst = project_dir / ".kiro" / "steering" / "graphify.md"
if steering_dst.exists():
@@ -1611,6 +1661,8 @@ def _project_uninstall(platform_name: str, project_dir: Path | None = None) -> N
removed = _remove_skill_file(platform_name, project=True, project_dir=project_dir)
if not removed:
print("nothing to remove")
elif platform_name == "codebuddy":
codebuddy_uninstall(project_dir)
else:
_remove_skill_file(platform_name, project=True, project_dir=project_dir)
@@ -1785,6 +1837,7 @@ def uninstall_all(project_dir: Path | None = None, purge: bool = False) -> None:
# Skill-file / config-section uninstallers
claude_uninstall(pd)
codebuddy_uninstall(pd)
gemini_uninstall(pd)
vscode_uninstall(pd)
_cursor_uninstall(pd)
@@ -1856,6 +1909,104 @@ def claude_uninstall(project_dir: Path | None = None, *, project: bool = False)
_uninstall_claude_hook(project_dir or Path("."))
def codebuddy_install(project_dir: Path | None = None) -> None:
"""Write the graphify section to the local CODEBUDDY.md."""
target = (project_dir or Path(".")) / "CODEBUDDY.md"
if target.exists():
content = target.read_text(encoding="utf-8")
new_content = _replace_or_append_section(
content, _CODEBUDDY_MD_MARKER, _always_on("claude-md")
)
else:
new_content = _always_on("claude-md")
if target.exists() and new_content == target.read_text(encoding="utf-8"):
print(f"graphify already configured in {target.resolve()} (no change)")
else:
target.write_text(new_content, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
# Also write CodeBuddy PreToolUse hook to .codebuddy/settings.json
_install_codebuddy_hook(project_dir or Path("."))
print()
print("CodeBuddy will now check the knowledge graph before answering")
print("codebase questions and rebuild it after code changes.")
def _install_codebuddy_hook(project_dir: Path) -> None:
"""Add graphify PreToolUse hook to .codebuddy/settings.json."""
settings_path = project_dir / ".codebuddy" / "settings.json"
settings_path.parent.mkdir(parents=True, exist_ok=True)
if settings_path.exists():
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
settings = {}
else:
settings = {}
hooks = settings.setdefault("hooks", {})
pre_tool = hooks.setdefault("PreToolUse", [])
hooks["PreToolUse"] = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash", "Read|Glob") and "graphify" in str(h))]
hooks["PreToolUse"].append(_SETTINGS_HOOK)
hooks["PreToolUse"].append(_READ_SETTINGS_HOOK)
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
print(f" .codebuddy/settings.json -> PreToolUse hooks registered")
def _uninstall_codebuddy_hook(project_dir: Path) -> None:
"""Remove graphify PreToolUse hook from .codebuddy/settings.json."""
settings_path = project_dir / ".codebuddy" / "settings.json"
if not settings_path.exists():
return
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
filtered = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash", "Read|Glob") and "graphify" in str(h))]
if len(filtered) == len(pre_tool):
return
settings["hooks"]["PreToolUse"] = filtered
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
print(f" .codebuddy/settings.json -> PreToolUse hook removed")
def codebuddy_uninstall(project_dir: Path | None = None, *, project: bool = False) -> None:
"""Remove the graphify skill tree (SKILL.md + references/) and the CODEBUDDY.md section."""
project_dir = project_dir or Path(".")
_remove_skill_file("codebuddy", project=project, project_dir=project_dir)
target = project_dir / "CODEBUDDY.md"
if not target.exists():
print("No CODEBUDDY.md found in current directory - nothing to do")
return
content = target.read_text(encoding="utf-8")
if _CODEBUDDY_MD_MARKER not in content:
print("graphify section not found in CODEBUDDY.md - nothing to do")
return
# Remove the ## graphify section: from the marker to the next ## heading or EOF
cleaned = re.sub(
r"\n*## graphify\n.*?(?=\n## |\Z)",
"",
content,
flags=re.DOTALL,
).rstrip()
if cleaned:
target.write_text(cleaned + "\n", encoding="utf-8")
print(f"graphify section removed from {target.resolve()}")
else:
target.unlink()
print(f"CODEBUDDY.md was empty after removal - deleted {target.resolve()}")
_uninstall_codebuddy_hook(project_dir or Path("."))
def _clone_repo(
url: str, branch: str | None = None, out_dir: Path | None = None
) -> Path:
@@ -1942,7 +2093,7 @@ def main() -> None:
print("Usage: graphify <command>")
print()
print("Commands:")
print(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|aider|amp|claw|droid|trae|trae-cn|gemini|cursor|antigravity|hermes|kiro|pi|devin)")
print(" install [--platform P] copy skill to platform config dir (claude|windows|codebuddy|codex|opencode|aider|amp|claw|droid|trae|trae-cn|gemini|cursor|antigravity|hermes|kiro|pi|devin)")
print(" uninstall remove graphify from all detected platforms in one shot")
print(" --purge also delete graphify-out/ directory")
print(" path \"A\" \"B\" shortest path between two nodes in graph.json")
@@ -2017,6 +2168,9 @@ def main() -> None:
print(" --out DIR output dir (default: <path>); writes <DIR>/graphify-out/")
print(" --google-workspace export .gdoc/.gsheet/.gslides shortcuts via gws before extraction")
print(" --no-cluster skip clustering, write raw extraction only")
print(" --postgres DSN extract schema from a live PostgreSQL database")
print(" maps tables, views, functions + FK relationships;")
print(" column-level detail is not represented in the graph")
print(" --global also merge the resulting graph into the global graph")
print(" --as <tag> repo tag for --global (default: target directory name)")
print(" global add <graph.json> add/update a project graph in the global graph (~/.graphify/global-graph.json)")
@@ -2035,12 +2189,10 @@ def main() -> None:
print(" gemini uninstall remove GEMINI.md section + BeforeTool hook")
print(" cursor install write .cursor/rules/graphify.mdc (Cursor)")
print(" cursor uninstall remove .cursor/rules/graphify.mdc")
print(
" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)"
)
print(
" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook"
)
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
print(" codebuddy install write graphify section to CODEBUDDY.md + PreToolUse hook (CodeBuddy)")
print(" codebuddy uninstall remove graphify section from CODEBUDDY.md + PreToolUse hook")
print(" codex install write graphify section to AGENTS.md (Codex)")
print(" codex uninstall remove graphify section from AGENTS.md")
print(
@@ -2203,6 +2355,15 @@ def main() -> None:
else:
print("Usage: graphify claude [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "codebuddy":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
codebuddy_install()
elif subcmd == "uninstall":
codebuddy_uninstall()
else:
print("Usage: graphify codebuddy [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "gemini":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
@@ -2486,6 +2647,7 @@ def main() -> None:
from graphify.serve import _query_graph_text
from graphify.security import sanitize_label
from networkx.readwrite import json_graph
from graphify import querylog
question = sys.argv[2]
use_dfs = "--dfs" in sys.argv
@@ -2542,16 +2704,28 @@ def main() -> None:
except Exception as exc:
print(f"error: could not load graph: {exc}", file=sys.stderr)
sys.exit(1)
print(
_query_graph_text(
G,
question,
mode="dfs" if use_dfs else "bfs",
depth=2,
token_budget=budget,
context_filters=context_filters,
)
import time as _time
_t0 = _time.perf_counter()
_mode = "dfs" if use_dfs else "bfs"
_result = _query_graph_text(
G,
question,
mode=_mode,
depth=2,
token_budget=budget,
context_filters=context_filters,
)
querylog.log_query(
kind="query",
question=question,
corpus=str(gp),
result=_result,
mode=_mode,
depth=2,
token_budget=budget,
duration_ms=(_time.perf_counter() - _t0) * 1000,
)
print(_result)
elif cmd == "affected":
if len(sys.argv) < 3:
print("Usage: graphify affected \"<node-or-label>\" [--relation R] [--depth N] [--graph path]", file=sys.stderr)
@@ -2720,6 +2894,13 @@ def main() -> None:
else:
segments.append(f"<--{rel}{conf_str}-- {G.nodes[v].get('label', v)}")
print(f"Shortest path ({hops} hops):\n " + " ".join(segments))
from graphify import querylog
querylog.log_query(
kind="path",
question=f"{sys.argv[2]} -> {sys.argv[3]}",
corpus=str(gp),
nodes_returned=hops,
)
elif cmd == "explain":
if len(sys.argv) < 3:
@@ -2778,6 +2959,13 @@ def main() -> None:
print(f" {arrow} {G.nodes[nb].get('label', nb)} [{rel}] [{conf}]")
if len(connections) > 20:
print(f" ... and {len(connections) - 20} more")
from graphify import querylog
querylog.log_query(
kind="explain",
question=sys.argv[2],
corpus=str(gp),
nodes_returned=len(connections),
)
elif cmd == "diagnose":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
@@ -3656,20 +3844,26 @@ def main() -> None:
"Usage: graphify extract <path> [--backend gemini|kimi|claude|openai|deepseek|ollama] "
"[--model M] [--mode deep] [--out DIR] [--google-workspace] [--no-cluster] "
"[--max-workers N] [--token-budget N] [--max-concurrency N] "
"[--api-timeout S]",
"[--api-timeout S] [--postgres DSN]",
file=sys.stderr,
)
sys.exit(1)
target = Path(sys.argv[2]).resolve()
if not target.exists():
print(f"error: path not found: {target}", file=sys.stderr)
sys.exit(1)
has_path = True
if sys.argv[2].startswith("-"):
has_path = False
target = Path(".").resolve()
else:
target = Path(sys.argv[2]).resolve()
if not target.exists():
print(f"error: path not found: {target}", file=sys.stderr)
sys.exit(1)
backend: str | None = None
model: str | None = None
extract_mode: str | None = None
out_dir: Path | None = None
cli_postgres_dsn: str | None = None
no_cluster = False
dedup_llm = False
google_workspace = False
@@ -3707,7 +3901,7 @@ def main() -> None:
sys.exit(2)
return v
args = sys.argv[3:]
args = sys.argv[3:] if has_path else sys.argv[2:]
i = 0
while i < len(args):
a = args[i]
@@ -3765,9 +3959,17 @@ def main() -> None:
cli_excludes.append(args[i + 1]); i += 2
elif a.startswith("--exclude="):
cli_excludes.append(a.split("=", 1)[1]); i += 1
elif a == "--postgres" and i + 1 < len(args):
cli_postgres_dsn = args[i + 1]; i += 2
elif a.startswith("--postgres="):
cli_postgres_dsn = a.split("=", 1)[1]; i += 1
else:
i += 1
if not has_path and cli_postgres_dsn is None:
print("error: must specify a path to scan or a --postgres DSN", file=sys.stderr)
sys.exit(1)
_VALID_MODES = {"deep"}
if extract_mode is not None and extract_mode not in _VALID_MODES:
print(
@@ -3787,91 +3989,6 @@ def main() -> None:
if cli_max_workers is not None:
os.environ["GRAPHIFY_MAX_WORKERS"] = str(cli_max_workers)
# Backend resolution. If user did not pass --backend, sniff env.
# If backend was explicitly requested, validate its key is present
# and surface a clear error early — don't let extract_corpus_parallel
# raise mid-run after we've spent time on AST extraction.
from graphify.llm import (
BACKENDS as _BACKENDS,
detect_backend as _detect_backend,
estimate_cost as _estimate_cost,
extract_corpus_parallel as _extract_corpus_parallel,
_format_backend_env_keys,
_get_backend_api_key,
)
if backend is None:
backend = _detect_backend()
if backend is None:
print(
"error: no LLM API key found. Set GEMINI_API_KEY or GOOGLE_API_KEY "
"(gemini), MOONSHOT_API_KEY (kimi), ANTHROPIC_API_KEY (claude), "
"OPENAI_API_KEY (openai), DEEPSEEK_API_KEY (deepseek), "
"or pass --backend.",
file=sys.stderr,
)
sys.exit(1)
if backend not in _BACKENDS:
print(
f"error: unknown backend '{backend}'. "
f"Available: {', '.join(sorted(_BACKENDS))}",
file=sys.stderr,
)
sys.exit(1)
if backend == "ollama":
# Fail closed with a clean message (not a deep traceback) if
# OLLAMA_BASE_URL points at a link-local/metadata address. warn=False:
# the later in-flow call owns the user-facing warning for LAN hosts.
from graphify.llm import _validate_ollama_base_url
_oll_url = os.environ.get("OLLAMA_BASE_URL", _BACKENDS["ollama"].get("base_url", ""))
try:
_validate_ollama_base_url(_oll_url, warn=False)
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(2)
if not _get_backend_api_key(backend):
# Ollama on a loopback URL ignores auth entirely; don't block
# the run just because OLLAMA_API_KEY is unset (issue #792).
# extract_files_direct already prints a warning and substitutes
# a placeholder key in that case.
allow_no_key = False
if backend == "ollama":
from urllib.parse import urlparse
ollama_url = os.environ.get(
"OLLAMA_BASE_URL",
_BACKENDS["ollama"].get("base_url", ""),
)
try:
host = (urlparse(ollama_url).hostname or "").lower()
except Exception:
host = ""
allow_no_key = (
host in ("localhost", "127.0.0.1", "::1")
or host.startswith("127.")
)
elif backend == "bedrock":
allow_no_key = bool(
os.environ.get("AWS_PROFILE")
or os.environ.get("AWS_REGION")
or os.environ.get("AWS_DEFAULT_REGION")
or os.environ.get("AWS_ACCESS_KEY_ID")
)
elif backend == "claude-cli":
import shutil as _shutil
allow_no_key = _shutil.which("claude") is not None
if not allow_no_key:
print(
"error: backend 'claude-cli' requires the `claude` CLI on $PATH "
"(install Claude Code and run `claude` once to authenticate).",
file=sys.stderr,
)
sys.exit(1)
if not allow_no_key:
print(
f"error: backend '{backend}' requires {_format_backend_env_keys(backend)} to be set.",
file=sys.stderr,
)
sys.exit(1)
# Resolve output dir. The user-facing contract is "<out>/graphify-out/"
# so a fresh checkout writes graphify-out/ at the project root, matching
# the skill.md pipeline.
@@ -3886,9 +4003,17 @@ def main() -> None:
)
manifest_path = graphify_out / "manifest.json"
existing_graph_path = graphify_out / "graph.json"
incremental_mode = manifest_path.exists() and existing_graph_path.exists()
incremental_mode = manifest_path.exists() and existing_graph_path.exists() if has_path else False
if incremental_mode:
if not has_path:
code_files = []
doc_files = []
paper_files = []
image_files = []
deleted_files = []
unchanged_total = 0
files_by_type = {}
elif incremental_mode:
print(f"[graphify extract] incremental scan of {target}")
detection = _detect_incremental(
target,
@@ -3896,12 +4021,7 @@ def main() -> None:
google_workspace=google_workspace or None,
extra_excludes=cli_excludes or None,
)
else:
print(f"[graphify extract] scanning {target}")
detection = _detect(target, google_workspace=google_workspace or None, extra_excludes=cli_excludes or None)
files_by_type = detection.get("files", {})
if incremental_mode:
files_by_type = detection.get("files", {})
new_by_type = detection.get("new_files", {})
code_files = [Path(p) for p in new_by_type.get("code", [])]
doc_files = [Path(p) for p in new_by_type.get("document", [])]
@@ -3910,6 +4030,9 @@ def main() -> None:
deleted_files = list(detection.get("deleted_files", []))
unchanged_total = sum(len(v) for v in detection.get("unchanged_files", {}).values())
else:
print(f"[graphify extract] scanning {target}")
detection = _detect(target, google_workspace=google_workspace or None, extra_excludes=cli_excludes or None)
files_by_type = detection.get("files", {})
code_files = [Path(p) for p in files_by_type.get("code", [])]
doc_files = [Path(p) for p in files_by_type.get("document", [])]
paper_files = [Path(p) for p in files_by_type.get("paper", [])]
@@ -3931,6 +4054,93 @@ def main() -> None:
f"{len(image_files)} images"
)
# Resolve the LLM backend only now that we know whether the corpus
# needs one. A code-only corpus is pure local AST and must not require
# an API key; the key is enforced below only when there's LLM work.
from graphify.llm import (
BACKENDS as _BACKENDS,
detect_backend as _detect_backend,
estimate_cost as _estimate_cost,
extract_corpus_parallel as _extract_corpus_parallel,
_format_backend_env_keys,
_get_backend_api_key,
)
needs_llm = bool(semantic_files) or dedup_llm
if backend is None and needs_llm:
backend = _detect_backend()
if backend is not None and backend not in _BACKENDS:
print(
f"error: unknown backend '{backend}'. "
f"Available: {', '.join(sorted(_BACKENDS))}",
file=sys.stderr,
)
sys.exit(1)
if needs_llm:
if backend is None:
reasons = []
if semantic_files:
reasons.append(
f"{len(semantic_files)} doc/paper/image file(s) need semantic extraction"
)
if dedup_llm:
reasons.append("--dedup-llm was passed")
print(
"error: no LLM API key found (" + "; ".join(reasons) + "). "
"Set GEMINI_API_KEY or GOOGLE_API_KEY (gemini), MOONSHOT_API_KEY "
"(kimi), ANTHROPIC_API_KEY (claude), OPENAI_API_KEY (openai), "
"DEEPSEEK_API_KEY (deepseek), or pass --backend. A code-only "
"corpus needs no key.",
file=sys.stderr,
)
sys.exit(1)
if backend == "ollama":
from graphify.llm import _validate_ollama_base_url
_oll_url = os.environ.get("OLLAMA_BASE_URL", _BACKENDS["ollama"].get("base_url", ""))
try:
_validate_ollama_base_url(_oll_url, warn=False)
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(2)
if not _get_backend_api_key(backend):
allow_no_key = False
if backend == "ollama":
from urllib.parse import urlparse
ollama_url = os.environ.get(
"OLLAMA_BASE_URL",
_BACKENDS["ollama"].get("base_url", ""),
)
try:
host = (urlparse(ollama_url).hostname or "").lower()
except Exception:
host = ""
allow_no_key = (
host in ("localhost", "127.0.0.1", "::1")
or host.startswith("127.")
)
elif backend == "bedrock":
allow_no_key = bool(
os.environ.get("AWS_PROFILE")
or os.environ.get("AWS_REGION")
or os.environ.get("AWS_DEFAULT_REGION")
or os.environ.get("AWS_ACCESS_KEY_ID")
)
elif backend == "claude-cli":
import shutil as _shutil
allow_no_key = _shutil.which("claude") is not None
if not allow_no_key:
print(
"error: backend 'claude-cli' requires the `claude` CLI on $PATH "
"(install Claude Code and run `claude` once to authenticate).",
file=sys.stderr,
)
sys.exit(1)
if not allow_no_key:
print(
f"error: backend '{backend}' requires {_format_backend_env_keys(backend)} to be set.",
file=sys.stderr,
)
sys.exit(1)
# AST extraction on code files. Empty code list (docs-only corpus) is
# the issue #698 case — skip cleanly instead of crashing inside extract().
ast_result: dict = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
@@ -4040,13 +4250,25 @@ def main() -> None:
sem_result["input_tokens"] += fresh.get("input_tokens", 0)
sem_result["output_tokens"] += fresh.get("output_tokens", 0)
# Merge AST + semantic. Order matters for deduplication: passing AST
pg_result: dict = {"nodes": [], "edges": []}
if cli_postgres_dsn is not None:
from graphify.pg_introspect import introspect_postgres
print(f"[graphify extract] introspecting PostgreSQL schema...")
try:
pg_result = introspect_postgres(cli_postgres_dsn)
except (ConnectionError, ImportError) as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
print(f"[graphify extract] PostgreSQL: {len(pg_result['nodes'])} nodes, "
f"{len(pg_result['edges'])} edges")
# Merge AST + semantic + pg_result. Order matters for deduplication: passing AST
# first means semantic node attributes win on collision (richer labels
# for symbols also referenced in docs). Hyperedges only come from the
# semantic side.
merged: dict = {
"nodes": list(ast_result.get("nodes", [])) + list(sem_result.get("nodes", [])),
"edges": list(ast_result.get("edges", [])) + list(sem_result.get("edges", [])),
"nodes": list(ast_result.get("nodes", [])) + list(sem_result.get("nodes", [])) + list(pg_result.get("nodes", [])),
"edges": list(ast_result.get("edges", [])) + list(sem_result.get("edges", [])) + list(pg_result.get("edges", [])),
"hyperedges": list(sem_result.get("hyperedges", [])),
"input_tokens": ast_result.get("input_tokens", 0) + sem_result.get("input_tokens", 0),
"output_tokens": ast_result.get("output_tokens", 0) + sem_result.get("output_tokens", 0),
@@ -4095,7 +4317,7 @@ def main() -> None:
f"est. cost: ${cost:.4f}"
)
try:
_save_manifest(_manifest_files, manifest_path=str(manifest_path), kind="both")
_save_manifest(_manifest_files, manifest_path=str(manifest_path), kind="both", root=target)
except Exception as exc:
print(f"[graphify extract] warning: could not write manifest: {exc}", file=sys.stderr)
if global_merge:
@@ -4184,7 +4406,7 @@ def main() -> None:
}
analysis_path.write_text(json.dumps(analysis, indent=2), encoding="utf-8")
try:
_save_manifest(_manifest_files, manifest_path=str(manifest_path), kind="both")
_save_manifest(_manifest_files, manifest_path=str(manifest_path), kind="both", root=target)
except Exception as exc:
print(f"[graphify extract] warning: could not write manifest: {exc}", file=sys.stderr)
+3
View File
@@ -145,6 +145,9 @@ def load_graph(path: Path) -> nx.Graph:
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:
+12
View File
@@ -5,6 +5,16 @@ 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")},
@@ -94,6 +104,8 @@ def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
for node_id, deg in sorted_nodes:
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,
"label": G.nodes[node_id].get("label", node_id),
+43
View File
@@ -156,10 +156,53 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
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}
# 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
+91 -3
View File
@@ -146,6 +146,70 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
return digest
def _relativize_source_files_in(payload: dict, root: Path) -> None:
"""Mutate ``payload`` to rewrite absolute ``source_file`` fields as
forward-slash relative paths from ``root``.
Mirror of :func:`graphify.watch._relativize_source_files` so cached
extraction fragments persist in portable form (#777). Already-relative
fields and out-of-root paths pass through unchanged.
Only ``root`` is resolved — ``source_file`` itself is relativized
symbolically so in-root symlinks keep their original name rather than
pointing at the resolved target. Same reasoning as
:func:`graphify.detect._to_relative_for_storage`.
"""
try:
root_resolved = Path(root).resolve()
except OSError:
return
for bucket in ("nodes", "edges", "hyperedges"):
for item in payload.get(bucket, []):
if not isinstance(item, dict):
continue
source = item.get("source_file")
if not source:
continue
sp = Path(source)
if not sp.is_absolute():
continue
try:
rel = os.path.relpath(sp, root_resolved)
except (ValueError, OSError):
continue # out-of-root (e.g. Windows cross-drive)
if rel == ".." or rel.startswith(".." + os.sep) or rel.startswith("../"):
continue # escaped root — keep absolute
item["source_file"] = rel.replace(os.sep, "/")
def _absolutize_source_files_in(payload: dict, root: Path) -> None:
"""Inverse of :func:`_relativize_source_files_in`.
Re-anchor relative ``source_file`` fields against ``root`` so callers
that load a cached fragment see the same absolute-path shape that a
fresh in-process extraction would produce. Legacy cache entries with
absolute ``source_file`` values pass through unchanged.
"""
try:
root_resolved = Path(root).resolve()
except OSError:
return
for bucket in ("nodes", "edges", "hyperedges"):
for item in payload.get(bucket, []):
if not isinstance(item, dict):
continue
source = item.get("source_file")
if not source:
continue
sp = Path(source)
if sp.is_absolute():
continue
try:
item["source_file"] = str(root_resolved / sp)
except (TypeError, OSError):
continue
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
@@ -176,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"
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
@@ -203,12 +276,27 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
p = Path(path)
if not p.is_file():
return
# Relativize source_file fields against ``root`` before write so the
# cache file on disk is portable across machines and checkout
# directories (#777). The cache key is content-hashed so lookup is
# already path-independent; this fixes the embedded path leak.
#
# Serialize a relativized copy rather than mutating the caller's dict —
# downstream pipeline steps (notably extract.py's AST prefix remap, which
# looks up Path(source_file).resolve() in a prefix table) depend on the
# source_file field's original absolute form. Mutating the input here would
# silently break those remaps on the first extraction pass.
on_disk = result
if isinstance(result, dict) and any(result.get(k) for k in ("nodes", "edges", "hyperedges")):
import copy as _copy
on_disk = _copy.deepcopy(result)
_relativize_source_files_in(on_disk, root)
h = file_hash(p, root)
target_dir = cache_dir(root, kind)
entry = target_dir / f"{h}.json"
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
try:
os.write(fd, json.dumps(result).encode())
os.write(fd, json.dumps(on_disk).encode())
os.close(fd)
try:
os.replace(tmp_path, entry)
+5 -1
View File
@@ -186,7 +186,11 @@ def deduplicate_entities(
for node in group:
sf = node.get("source_file") or ""
by_file[sf].append(node)
for file_group in by_file.values():
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:
+135 -14
View File
@@ -25,7 +25,7 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml'}
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml', '.cls', '.trigger'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
@@ -98,23 +98,60 @@ _SENSITIVE_DIRS = frozenset({
".ssh", ".gnupg", ".aws", ".gcloud", "secrets", ".secrets", "credentials",
})
# Files that may contain secrets - skip silently.
# Files that may contain secrets - skip silently. These patterns are specific
# (extensions, exact credential-store names) and always apply.
_SENSITIVE_PATTERNS = [
re.compile(r'(^|[\\/])\.(env|envrc)(\.|$)', re.IGNORECASE),
re.compile(r'\.(pem|key|p12|pfx|cert|crt|der|p8)$', re.IGNORECASE),
re.compile(r'(id_rsa|id_dsa|id_ecdsa|id_ed25519)(\.pub)?$'),
re.compile(r'(\.netrc|\.pgpass|\.htpasswd)$', re.IGNORECASE),
re.compile(r'(aws_credentials|gcloud_credentials|service.account)', re.IGNORECASE),
]
# Generic keyword patterns - these only count when the keyword is LOAD-BEARING
# in the filename (see _generic_keyword_hit), because a keyword buried mid-phrase
# in a long descriptive slug names a topic, not a credential store:
# "token-economics-of-recall.md" is a note ABOUT tokens; "api_token.txt" IS one.
# Uses lookarounds instead of \b so underscore-prefixed names like api_token.txt
# match. Both patterns use (?![a-zA-Z]) so that the trailing-underscore behavior
# is consistent: "secret_store.txt" IS flagged, "tokenizer.py" is NOT (because
# "i" after "token" is alpha and blocks the match).
# `token` is kept separate because its longer suffix "izer"/"ize" is the only
# common false-positive; other keywords have no such well-known derivatives.
_SENSITIVE_PATTERNS = [
re.compile(r'(^|[\\/])\.(env|envrc)(\.|$)', re.IGNORECASE),
re.compile(r'\.(pem|key|p12|pfx|cert|crt|der|p8)$', re.IGNORECASE),
_GENERIC_KEYWORD_PATTERNS = [
re.compile(r'(?<![a-zA-Z0-9])(credential|secret|passwd|password|private_key)s?(?![a-zA-Z])', re.IGNORECASE),
re.compile(r'(?<![a-zA-Z0-9])tokens?(?![a-zA-Z])', re.IGNORECASE),
re.compile(r'(id_rsa|id_dsa|id_ecdsa|id_ed25519)(\.pub)?$'),
re.compile(r'(\.netrc|\.pgpass|\.htpasswd)$', re.IGNORECASE),
re.compile(r'(aws_credentials|gcloud_credentials|service.account)', re.IGNORECASE),
]
# Word separators for the load-bearing check (underscore intentionally included;
# multi-word keywords like private_key are handled by the end-of-stem check,
# which runs before word counting).
_WORD_SPLIT = re.compile(r'[-_\s]+')
def _generic_keyword_hit(name: str) -> bool:
"""True if a generic secret keyword appears load-bearing in the filename.
Secret-store files name their contents, and in English compounds the
content noun is the head, which comes last: "github-personal-access-token",
"api_token", "oauth_token". A keyword that is neither at the end of the
stem nor in a short (<=2 word) name is a topic word in a descriptive slug
("token-economics-of-recall.md", "password-policy-discussion.md") and must
not cause the file to be silently dropped from the graph (#436, #718).
"""
# Stem = name up to the first dot, ignoring leading dots so dotfiles like
# ".token" keep their keyword ("" stems would never match).
stem = name.lstrip('.').split('.')[0]
for pat in _GENERIC_KEYWORD_PATTERNS:
hit = False
for m in pat.finditer(stem):
hit = True
if m.end() == len(stem): # keyword ends the stem -> names the contents
return True
if hit and len([w for w in _WORD_SPLIT.split(stem) if w]) <= 2:
return True # short name like token_config.yaml / secret_handler.txt
return False
# Signals that a .md/.txt file is actually a converted academic paper
_PAPER_SIGNALS = [
re.compile(r'\barxiv\b', re.IGNORECASE),
@@ -143,7 +180,10 @@ def _is_sensitive(path: Path) -> bool:
return True
# Stage 2: filename pattern match
name = path.name
return any(p.search(name) for p in _SENSITIVE_PATTERNS)
if any(p.search(name) for p in _SENSITIVE_PATTERNS):
return True
# Stage 3: generic keywords, only when load-bearing in the name
return _generic_keyword_hit(name)
def _looks_like_paper(path: Path) -> bool:
@@ -1091,12 +1131,71 @@ def _md5_file(path: Path) -> str:
return h.hexdigest()
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
"""Load the manifest from a previous run. Returns {} on any error."""
def _to_relative_for_storage(key: str, root: Path) -> str:
"""Return ``key`` as a forward-slash relative path from ``root``.
Keys outside ``root`` (out-of-tree symlinked sources, external --include
paths) and already-relative keys pass through unchanged — mirrors the
fallback in :func:`graphify.watch._relativize_source_files` so the
on-disk artifact survives the round-trip even when some paths cannot be
portably encoded.
Only ``root`` is resolved — the key itself is relativized symbolically
so an in-root symlink (e.g. ``alias.py -> sub/target.py``) is stored
under its own name. Resolving the key would point the stored entry at
the symlink target, and the original key would then miss on reload and
re-extract on every incremental run.
"""
p = Path(key)
if not p.is_absolute():
return key
try:
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
rel = os.path.relpath(p, Path(root).resolve())
except (ValueError, OSError):
return key # outside root (e.g. Windows cross-drive)
# ``os.path.relpath`` happily produces ``../foo`` for paths outside
# root; mirror the prior ``relative_to``-raises-ValueError semantics by
# keeping out-of-root entries in their absolute form.
if rel == ".." or rel.startswith(".." + os.sep) or rel.startswith("../"):
return key
return rel.replace(os.sep, "/")
def _to_absolute_from_storage(key: str, root: Path) -> str:
"""Inverse of :func:`_to_relative_for_storage`.
Re-anchor a stored key against ``root``. Already-absolute keys
(legacy manifests, out-of-root entries) pass through unchanged so
that newly-loaded manifests from before this change remain readable.
Uses ``Path(root).resolve()`` so the produced absolute path matches
what :func:`detect` returns (which also resolves the scan root).
"""
p = Path(key)
if p.is_absolute():
return str(p)
return str(Path(root).resolve() / p)
def load_manifest(
manifest_path: str = _MANIFEST_PATH,
*,
root: Path | None = None,
) -> dict:
"""Load the manifest from a previous run. Returns {} on any error.
When ``root`` is provided, stored relative keys are re-anchored against
it so callers see absolute paths regardless of on-disk format. Legacy
manifests with absolute keys pass through unchanged, so a graphify-out/
written by an older version (or by a caller that didn't supply ``root``
to :func:`save_manifest`) remains readable.
"""
try:
raw = json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except Exception:
return {}
if root is None or not isinstance(raw, dict):
return raw
return {_to_absolute_from_storage(k, root): v for k, v in raw.items()}
def save_manifest(
@@ -1104,6 +1203,7 @@ def save_manifest(
manifest_path: str = _MANIFEST_PATH,
*,
kind: str = "both",
root: Path | None = None,
) -> None:
"""Save current file mtimes + content hashes for change detection.
@@ -1113,8 +1213,14 @@ def save_manifest(
kind="semantic" — written by `graphify extract` after semantic extraction.
Stamps semantic_hash; preserves existing ast_hash.
kind="both" — full pipeline: stamps both hashes (default).
When ``root`` is provided, keys are relativized against it before write
(forward-slash, posix-style) so the on-disk manifest is portable across
machines and checkout locations (#777). Out-of-root entries are written
as absolute so they continue to round-trip on the saving machine.
When ``root`` is None the legacy absolute-keyed format is preserved.
"""
existing = load_manifest(manifest_path)
existing = load_manifest(manifest_path, root=root)
def _normalise_entry(entry):
if isinstance(entry, (int, float)):
@@ -1160,6 +1266,12 @@ def save_manifest(
# Preserve semantic_hash only when content is unchanged
entry["semantic_hash"] = prev.get("semantic_hash", "") if h == prev.get("ast_hash", "") else ""
manifest[f] = entry
if root is not None:
# Persist in portable form: forward-slash relative paths. Keys outside
# ``root`` (out-of-tree symlinked corpora, --include sources) keep
# their absolute form so the manifest round-trips on the saving
# machine even when not every entry can be portably encoded.
manifest = {_to_relative_for_storage(k, root): v for k, v in manifest.items()}
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
Path(manifest_path).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
@@ -1197,7 +1309,10 @@ def detect_incremental(
contains at least one direct symlinked child, ``False`` otherwise.
"""
full = detect(root, follow_symlinks=follow_symlinks, google_workspace=google_workspace, extra_excludes=extra_excludes)
manifest = load_manifest(manifest_path)
# Pass ``root`` so a manifest written with relative keys (post-#777) is
# re-anchored to the absolute form the rest of this function compares
# against. Legacy absolute-keyed manifests pass through unchanged.
manifest = load_manifest(manifest_path, root=root)
if not manifest:
# No previous run - treat everything as new
@@ -1232,6 +1347,12 @@ def detect_incremental(
changed = True
else:
stored_mtime = stored.get("mtime")
# Schema-drift guard (#1163): tolerate a nested {mtime: ...}
# dict or any non-numeric value without crashing.
if isinstance(stored_mtime, dict):
stored_mtime = stored_mtime.get("mtime")
if not isinstance(stored_mtime, (int, float)):
stored_mtime = None
if stored_mtime is None or current_mtime != stored_mtime:
# mtime bumped — verify with content hash before re-extracting
changed = _md5_file(Path(f)) != stored_hash
+23 -5
View File
@@ -493,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
@@ -1274,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:
@@ -1289,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",
@@ -1317,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)
+438 -5
View File
@@ -473,6 +473,18 @@ _PYTHON_TYPE_CONTAINERS = frozenset({
"None", "Ellipsis",
})
# Scalar builtins and test-mock names that appear as type annotations but carry
# no useful semantic meaning as graph nodes (#1147). Suppressed at the annotation
# walker level so they are never created as nodes or emitted as edges.
_PYTHON_ANNOTATION_NOISE = frozenset({
# scalar builtins
"str", "int", "float", "bool", "bytes", "bytearray", "complex", "object",
"True", "False",
# unittest.mock
"MagicMock", "Mock", "AsyncMock", "NonCallableMock",
"NonCallableMagicMock", "PropertyMock", "patch", "sentinel",
})
def _python_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[str, str]]) -> None:
"""Walk a Python type annotation; append (name, role) where role is 'type' or 'generic_arg'.
@@ -490,19 +502,19 @@ def _python_collect_type_refs(node, source: bytes, generic: bool, out: list[tupl
return
if t == "identifier":
name = _read_text(node, source)
if name and name not in _PYTHON_TYPE_CONTAINERS:
if name and name not in _PYTHON_TYPE_CONTAINERS and name not in _PYTHON_ANNOTATION_NOISE:
out.append((name, "generic_arg" if generic else "type"))
return
if t == "attribute":
tail = _read_text(node, source).rsplit(".", 1)[-1]
if tail and tail not in _PYTHON_TYPE_CONTAINERS:
if tail and tail not in _PYTHON_TYPE_CONTAINERS and tail not in _PYTHON_ANNOTATION_NOISE:
out.append((tail, "generic_arg" if generic else "type"))
return
if t == "generic_type":
for c in node.children:
if c.type == "identifier":
container = _read_text(c, source)
if container and container not in _PYTHON_TYPE_CONTAINERS:
if container and container not in _PYTHON_TYPE_CONTAINERS and container not in _PYTHON_ANNOTATION_NOISE:
out.append((container, "generic_arg" if generic else "type"))
elif c.type == "type_parameter":
for sub in c.children:
@@ -4029,6 +4041,205 @@ def extract_csharp(path: Path) -> dict:
return _extract_generic(path, _CSHARP_CONFIG)
def extract_apex(path: Path) -> dict:
"""Extract classes, interfaces, enums, methods, and Salesforce constructs from
Apex .cls and .trigger files using regex (no tree-sitter grammar on PyPI)."""
import re as _re
try:
source = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return {"nodes": [], "edges": []}
str_path = str(path)
stem = _file_stem(path)
file_nid = _make_id(str_path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
def add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": label,
"file_type": "code",
"source_file": str_path,
"source_location": f"L{line}",
})
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED") -> None:
edges.append({
"source": src,
"target": tgt,
"relation": relation,
"confidence": confidence,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
add_node(file_nid, path.name, 1)
lines = source.splitlines()
_ACCESS = r"(?:public|private|protected|global|webService)?"
_SHARING = r"(?:\s+(?:with|without|inherited)\s+sharing)?"
_MOD = r"(?:\s+(?:abstract|virtual|override|static|final|transient|testMethod))?"
_ANNOTATION = r"(?:\s*@\w+(?:\s*\([^)]*\))?\s*)*"
cls_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*class\s+(\w+)"
rf"(?:\s+extends\s+(\w+))?(?:\s+implements\s+([\w,\s]+))?\s*\{{?",
_re.IGNORECASE,
)
iface_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*interface\s+(\w+)"
rf"(?:\s+extends\s+([\w,\s]+))?\s*\{{?",
_re.IGNORECASE,
)
enum_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*enum\s+(\w+)\s*\{{?",
_re.IGNORECASE,
)
trigger_re = _re.compile(
r"^\s*trigger\s+(\w+)\s+on\s+(\w+)\s*\(",
_re.IGNORECASE,
)
method_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_MOD}\s*(?:static\s+)?[\w<>\[\]]+\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+\w+\s*)?\{{?",
_re.IGNORECASE,
)
annotation_re = _re.compile(r"@(\w+)", _re.IGNORECASE)
soql_re = _re.compile(r"\[\s*SELECT\b[^\]]+FROM\s+(\w+)", _re.IGNORECASE)
dml_re = _re.compile(r"\b(insert|update|delete|upsert|merge|undelete)\s+\w", _re.IGNORECASE)
_CONTROL_FLOW = frozenset({
"if", "else", "for", "while", "do", "switch", "try", "catch",
"finally", "return", "throw", "new", "void", "null",
"true", "false", "this", "super", "class", "interface", "enum",
"trigger", "on",
})
current_class_nid: str | None = None
pending_annotations: list[str] = []
for lineno, line_text in enumerate(lines, start=1):
stripped = line_text.strip()
if stripped.startswith("@"):
for m in annotation_re.finditer(stripped):
pending_annotations.append(m.group(1).lower())
continue
tm = trigger_re.match(stripped)
if tm:
trig_name, sobject = tm.group(1), tm.group(2)
trig_nid = _make_id(stem, trig_name)
add_node(trig_nid, trig_name, lineno)
add_edge(file_nid, trig_nid, "contains", lineno)
sob_nid = _make_id(sobject)
if sob_nid not in seen_ids:
add_node(sob_nid, sobject, lineno)
add_edge(trig_nid, sob_nid, "uses", lineno, confidence="INFERRED")
current_class_nid = trig_nid
pending_annotations = []
continue
cm = cls_re.match(stripped)
if cm:
class_name = cm.group(1)
if class_name.lower() in _CONTROL_FLOW:
pending_annotations = []
continue
class_nid = _make_id(stem, class_name)
add_node(class_nid, class_name, lineno)
add_edge(file_nid, class_nid, "contains", lineno)
if cm.group(2):
base = cm.group(2).strip()
base_nid = _make_id(stem, base)
if base_nid not in seen_ids:
base_nid = _make_id(base)
if base_nid not in seen_ids:
add_node(base_nid, base, lineno)
add_edge(class_nid, base_nid, "extends", lineno, confidence="INFERRED")
if cm.group(3):
for iface in cm.group(3).split(","):
iface = iface.strip()
if iface:
iface_nid = _make_id(stem, iface)
if iface_nid not in seen_ids:
iface_nid = _make_id(iface)
if iface_nid not in seen_ids:
add_node(iface_nid, iface, lineno)
add_edge(class_nid, iface_nid, "implements", lineno, confidence="INFERRED")
current_class_nid = class_nid
pending_annotations = []
continue
im = iface_re.match(stripped)
if im:
iface_name = im.group(1)
if iface_name.lower() in _CONTROL_FLOW:
pending_annotations = []
continue
iface_nid = _make_id(stem, iface_name)
add_node(iface_nid, iface_name, lineno)
add_edge(file_nid if current_class_nid is None else current_class_nid,
iface_nid, "contains", lineno)
pending_annotations = []
continue
em = enum_re.match(stripped)
if em:
enum_name = em.group(1)
if enum_name.lower() in _CONTROL_FLOW:
pending_annotations = []
continue
enum_nid = _make_id(stem, enum_name)
add_node(enum_nid, enum_name, lineno)
add_edge(file_nid if current_class_nid is None else current_class_nid,
enum_nid, "contains", lineno)
pending_annotations = []
continue
if current_class_nid is not None:
mm = method_re.match(stripped)
if mm:
method_name = mm.group(1)
if method_name.lower() not in _CONTROL_FLOW:
method_nid = _make_id(current_class_nid, method_name)
method_label = f".{method_name}()"
add_node(method_nid, method_label, lineno)
add_edge(current_class_nid, method_nid, "method", lineno)
if "auraenabled" in pending_annotations or "invocablemethod" in pending_annotations:
add_edge(file_nid, method_nid, "contains", lineno, confidence="INFERRED")
pending_annotations = []
continue
pending_annotations = []
for sm in soql_re.finditer(line_text):
sobject = sm.group(1)
sob_nid = _make_id(sobject)
if sob_nid not in seen_ids:
add_node(sob_nid, sobject, lineno)
src = current_class_nid or file_nid
add_edge(src, sob_nid, "uses", lineno, confidence="INFERRED")
for dm in dml_re.finditer(line_text):
dml_op = dm.group(1).lower()
dml_nid = _make_id(f"dml_{dml_op}")
if dml_nid not in seen_ids:
add_node(dml_nid, dml_op, lineno)
src = current_class_nid or file_nid
add_edge(src, dml_nid, "uses", lineno, confidence="INFERRED")
return {"nodes": nodes, "edges": edges}
def extract_kotlin(path: Path) -> dict:
"""Extract classes, objects, functions, and imports from a .kt/.kts file."""
return _extract_generic(path, _KOTLIN_CONFIG)
@@ -4716,7 +4927,7 @@ def extract_verilog(path: Path) -> dict:
return {"nodes": nodes, "edges": edges}
def extract_sql(path: Path) -> dict:
def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
"""Extract tables, views, functions, and relationships from .sql files via tree-sitter."""
try:
import tree_sitter_sql as tssql
@@ -4727,12 +4938,17 @@ def extract_sql(path: Path) -> dict:
try:
language = Language(tssql.language())
parser = Parser(language)
source = path.read_bytes()
source = (
content.encode("utf-8") if isinstance(content, str)
else content if content is not None
else path.read_bytes()
)
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
file_nid = _make_id(str_path)
@@ -6731,6 +6947,9 @@ class _SymbolResolutionFacts:
exports: list[_SymbolExportFact] = field(default_factory=list)
star_exports: list[_StarExportFact] = field(default_factory=list)
uses: list[_SymbolUseFact] = field(default_factory=list)
# File-to-file submodule imports from `from pkg import submod` (#1146).
# Each entry is (importing_file, submodule_file, line).
module_imports: list[tuple[Path, Path, int]] = field(default_factory=list)
def _apply_symbol_resolution_facts(
@@ -6748,6 +6967,7 @@ def _apply_symbol_resolution_facts(
or facts.exports
or facts.star_exports
or facts.uses
or facts.module_imports
):
return
@@ -6914,6 +7134,17 @@ def _apply_symbol_resolution_facts(
import_fact.file_path,
)
# #1146: emit file-to-file imports_from edges for package-form submodule imports.
for from_path, to_path, line in facts.module_imports:
try:
from_rel = from_path.relative_to(root)
to_rel = to_path.relative_to(root)
except ValueError:
continue
source_id = _make_id(_file_stem(from_rel))
target_id = _make_id(_file_stem(to_rel))
add_edge(source_id, target_id, "imports_from", "submodule_import", line, from_path)
for use_fact in facts.uses:
file_path = use_fact.file_path.resolve()
target_id = None
@@ -7540,8 +7771,20 @@ def _collect_python_symbol_resolution_facts(
target_path = _resolve_python_module_path(module_name, path, root, level)
if target_path is None:
continue
# #1146: `from pkg import submod` — if the target is a package
# (__init__.py) and an imported name matches a submodule file on
# disk, emit a file-level import edge to that submodule rather
# than only to the package.
pkg_dir = target_path.parent if target_path.name == "__init__.py" else None
for imported_name, local_name in _python_imported_names(node, source):
line = node.start_point[0] + 1
if pkg_dir is not None:
sub_py = pkg_dir / f"{imported_name}.py"
sub_pkg = pkg_dir / imported_name / "__init__.py"
submodule = sub_py if sub_py.is_file() else (sub_pkg if sub_pkg.is_file() else None)
if submodule is not None:
facts.module_imports.append((path, submodule, line))
continue
facts.imports.append(
_SymbolImportFact(path, local_name, target_path, imported_name, line)
)
@@ -10526,6 +10769,184 @@ def extract_dmf(path: Path) -> dict:
return {"nodes": nodes, "edges": edges}
# Head tokens in an HCL traversal that are meta/builtins, not references to a
# block defined in the corpus (count.index, each.key, self.*, path.module, ...).
_TF_META_HEADS = frozenset({"count", "each", "self", "path", "terraform"})
def extract_terraform(path: Path) -> dict:
"""Extract Terraform/HCL blocks and the references between them via tree-sitter.
Nodes: resources, data sources, modules, variables, outputs, providers, and
locals. Edges: `contains` (file -> block), `references` (block -> the blocks
it interpolates, e.g. `aws_instance.web` -> `var.region`), and `depends_on`
(explicit dependency edges).
Node IDs are scoped by the parent directory, not the file stem, because
Terraform resources are module(directory)-scoped: a resource defined in
main.tf is referenced from other .tf files in the same directory. Directory
scoping lets those cross-file references resolve when per-file extractions
are merged (stem scoping would split a definition from its references).
"""
try:
import tree_sitter_hcl as tshcl
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree_sitter_hcl not installed. Run: pip install tree-sitter-hcl"}
try:
language = Language(tshcl.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
str_path = str(path)
file_nid = _make_id(str_path)
scope = path.parent.name or "tf"
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str_path, "source_location": None}]
edges: list[dict] = []
seen_ids: set[str] = {file_nid}
seen_edges: set[tuple[str, str, str]] = set()
def _read(n) -> str:
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
def _label_text(n) -> str:
return _read(n).strip().strip('"')
def _add_node(address: str, label: str, line: int) -> str:
nid = _make_id(scope, address)
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({"id": nid, "label": label, "file_type": "code",
"source_file": str_path, "source_location": f"L{line}"})
edges.append({"source": file_nid, "target": nid, "relation": "contains",
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line}", "weight": 1.0})
return nid
def _add_edge(src: str, address: str, relation: str, line: int) -> None:
tgt = _make_id(scope, address)
if src == tgt:
return
key = (src, tgt, relation)
if key in seen_edges:
return
seen_edges.add(key)
edges.append({"source": src, "target": tgt, "relation": relation,
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line}", "weight": 1.0})
def _block_parts(block) -> tuple:
btype = None
labels: list[str] = []
for c in block.children:
if c.type in ("block_start", "body", "block_end"):
break
if c.type == "identifier" and btype is None:
btype = _read(c)
elif c.type in ("string_lit", "identifier"):
labels.append(_label_text(c))
return btype, labels
def _ref_address(expr):
head = _read(expr)
parent = expr.parent
attrs: list[str] = []
if parent is not None:
seen_self = False
for c in parent.children:
if c.id == expr.id:
seen_self = True
continue
if seen_self and c.type == "get_attr":
name = None
for gc in c.children:
if gc.type == "identifier":
name = _read(gc)
break
if name is None:
break
attrs.append(name)
elif seen_self and c.type not in ("get_attr",):
break
if head in _TF_META_HEADS or not head:
return None
if head == "var":
return f"var.{attrs[0]}" if attrs else None
if head == "local":
return f"local.{attrs[0]}" if attrs else None
if head == "module":
return f"module.{attrs[0]}" if attrs else None
if head == "data":
return f"data.{attrs[0]}.{attrs[1]}" if len(attrs) >= 2 else None
return f"{head}.{attrs[0]}" if attrs else None
def _collect_refs(node, owner_nid: str, relation: str) -> None:
rel = relation
if node.type == "attribute":
key_node = node.child_by_field_name("key") or (
node.children[0] if node.children else None
)
if key_node is not None and _read(key_node) == "depends_on":
rel = "depends_on"
if node.type == "variable_expr":
addr = _ref_address(node)
if addr:
_add_edge(owner_nid, addr, rel, node.start_point[0] + 1)
for c in node.children:
if c.is_named:
_collect_refs(c, owner_nid, rel)
def _body_of(block):
for c in block.children:
if c.type == "body":
return c
return None
body = next((c for c in root.children if c.type == "body"), root)
for block in body.children:
if block.type != "block":
continue
btype, labels = _block_parts(block)
line = block.start_point[0] + 1
blk_body = _body_of(block)
if btype == "resource" and len(labels) >= 2:
owner = _add_node(f"{labels[0]}.{labels[1]}", f"{labels[0]}.{labels[1]}", line)
elif btype == "data" and len(labels) >= 2:
owner = _add_node(f"data.{labels[0]}.{labels[1]}", f"data.{labels[0]}.{labels[1]}", line)
elif btype == "module" and labels:
owner = _add_node(f"module.{labels[0]}", f"module.{labels[0]}", line)
elif btype == "variable" and labels:
owner = _add_node(f"var.{labels[0]}", f"var.{labels[0]}", line)
elif btype == "output" and labels:
owner = _add_node(f"output.{labels[0]}", f"output.{labels[0]}", line)
elif btype == "provider" and labels:
owner = _add_node(f"provider.{labels[0]}", f"provider.{labels[0]}", line)
elif btype == "locals" and blk_body is not None:
for attr in blk_body.children:
if attr.type != "attribute":
continue
key_node = attr.children[0] if attr.children else None
if key_node is None:
continue
key = _read(key_node)
lnid = _add_node(f"local.{key}", f"local.{key}", attr.start_point[0] + 1)
_collect_refs(attr, lnid, "references")
continue
else:
continue
if blk_body is not None:
_collect_refs(blk_body, owner, "references")
return {"nodes": nodes, "edges": edges}
_DISPATCH: dict[str, Any] = {
".py": extract_python,
".js": extract_js,
@@ -10594,6 +11015,9 @@ _DISPATCH: dict[str, Any] = {
".sh": extract_bash,
".bash": extract_bash,
".json": extract_json,
".tf": extract_terraform,
".tfvars": extract_terraform,
".hcl": extract_terraform,
".dm": extract_dm,
".dme": extract_dm,
".dmi": extract_dmi,
@@ -10605,6 +11029,8 @@ _DISPATCH: dict[str, Any] = {
".vbproj": extract_csproj,
".razor": extract_razor,
".cshtml": extract_razor,
".cls": extract_apex,
".trigger": extract_apex,
}
@@ -11078,6 +11504,13 @@ def extract(
except ValueError:
pass
# Tag AST provenance so the incremental watch rebuild can distinguish
# AST-extracted nodes from semantic/LLM nodes. On a full re-extraction
# the watcher drops any AST-marked node missing from the fresh output
# even when its source file still exists (#1116).
for n in all_nodes:
n["_origin"] = "ast"
return {
"nodes": all_nodes,
"edges": all_edges,
+199 -77
View File
@@ -10,39 +10,186 @@ _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
"""
# 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', '')
changed = [Path(f.strip()) for f in changed_raw.strip().splitlines() if f.strip()]
if not changed:
sys.exit(0)
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
try:
from graphify.watch import _rebuild_code, _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)
"""
_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).
@@ -76,41 +223,15 @@ fi
""" + _PYTHON_DETECT + """
export GRAPHIFY_CHANGED="$CHANGED"
# Run rebuild detached so git commit returns immediately.
# Full repo rebuilds can take hours; blocking the post-commit hook stalls the shell.
# 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)"
nohup $GRAPHIFY_PYTHON -c "
import os, signal, sys
from pathlib import Path
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
changed = [Path(f.strip()) for f in changed_raw.strip().splitlines() if f.strip()]
if not changed:
sys.exit(0)
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
try:
from graphify.watch import _rebuild_code, _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')
_rebuild_code(Path('.'), changed_paths=changed, force=_force)
except TimeoutError as exc:
print(f'[graphify hook] {exc}')
sys.exit(1)
except Exception as exc:
print(f'[graphify hook] Rebuild failed: {exc}')
sys.exit(1)
" >> "$_GRAPHIFY_LOG" 2>&1 < /dev/null &
disown 2>/dev/null || true
# graphify-hook-end
""" + _detached_launch(_REBUILD_BODY_COMMIT) + """# graphify-hook-end
"""
@@ -148,31 +269,9 @@ GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
""" + _PYTHON_DETECT + """
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
echo "[graphify] Branch switched - launching background rebuild (log: $_GRAPHIFY_LOG)"
nohup $GRAPHIFY_PYTHON -c "
from graphify.watch import _rebuild_code, _apply_resource_limits
from pathlib import Path
import os, signal, sys
try:
_apply_resource_limits()
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
signal.alarm(_timeout)
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
# post-checkout: branch switch can touch arbitrary files; full rebuild path
# (no changed_paths) is correct here. The flock inside _rebuild_code still
# prevents pile-ups when commit + checkout fire back-to-back.
_rebuild_code(Path('.'), force=_force)
except TimeoutError as exc:
print(f'[graphify] {exc}')
sys.exit(1)
except Exception as exc:
print(f'[graphify] Rebuild failed: {exc}')
sys.exit(1)
" >> "$_GRAPHIFY_LOG" 2>&1 < /dev/null &
disown 2>/dev/null || true
# graphify-checkout-hook-end
""" + _detached_launch(_REBUILD_BODY_CHECKOUT) + """# graphify-checkout-hook-end
"""
@@ -298,8 +397,31 @@ def install(path: Path = Path(".")) -> str:
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}"
+425 -28
View File
@@ -5,6 +5,7 @@
# this module provides a direct API path for non-Claude-Code environments.
from __future__ import annotations
import base64
import json
import os
import re
@@ -12,6 +13,7 @@ import sys
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, replace
from pathlib import Path
# `_read_files` truncates each file at this many characters before joining into
@@ -53,11 +55,15 @@ BACKENDS: dict[str, dict] = {
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
"temperature": 0,
"max_tokens": 16384,
"vision": True,
},
"kimi": {
"base_url": "https://api.moonshot.ai/v1",
"default_model": "kimi-k2.6",
"env_key": "MOONSHOT_API_KEY",
# kimi-k2.6 is natively multimodal (MoonViT) and accepts the same
# OpenAI image_url data-URI block via Moonshot's compat endpoint.
"vision": True,
"pricing": {"input": 0.74, "output": 4.66}, # USD per 1M tokens
"temperature": None, # kimi-k2.6 enforces its own fixed temperature; sending any value raises 400
"max_tokens": 16384,
@@ -79,6 +85,7 @@ BACKENDS: dict[str, dict] = {
"temperature": 0,
"reasoning_effort": "low",
"max_completion_tokens": 16384,
"vision": True,
},
"openai": {
"base_url": "https://api.openai.com/v1",
@@ -87,6 +94,7 @@ BACKENDS: dict[str, dict] = {
"model_env_key": "GRAPHIFY_OPENAI_MODEL",
"pricing": {"input": 0.40, "output": 1.60}, # USD per 1M tokens
"temperature": 0,
"vision": True,
},
"deepseek": {
"base_url": "https://api.deepseek.com",
@@ -99,12 +107,28 @@ BACKENDS: dict[str, dict] = {
"temperature": 0,
"max_tokens": 16384,
},
"azure": {
# Azure OpenAI Service — uses AzureOpenAI SDK client, not the standard
# OpenAI client, so it has its own call path (_call_azure).
# Required env vars: AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT.
# Optional: AZURE_OPENAI_API_VERSION (defaults to 2024-12-01-preview),
# AZURE_OPENAI_DEPLOYMENT or GRAPHIFY_AZURE_MODEL (deployment name).
# base_url is intentionally absent — prevents accidental routing through
# _call_openai_compat, which requires it and uses the wrong SDK client class.
"default_model": os.environ.get("AZURE_OPENAI_DEPLOYMENT", os.environ.get("GRAPHIFY_AZURE_MODEL", "gpt-4o")),
"env_key": "AZURE_OPENAI_API_KEY",
"model_env_key": "GRAPHIFY_AZURE_MODEL",
"pricing": {"input": 2.50, "output": 10.00}, # USD per 1M tokens (gpt-4o; may mis-estimate other deployments)
"temperature": 0,
"max_tokens": 16384,
},
"bedrock": {
"default_model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"model_env_key": "GRAPHIFY_BEDROCK_MODEL",
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
"temperature": 0,
"max_tokens": 16384,
"vision": True,
},
"claude-cli": {
# Routes through the locally-installed `claude` CLI (Claude Code) using
@@ -115,6 +139,9 @@ BACKENDS: dict[str, dict] = {
"pricing": {"input": 0.0, "output": 0.0},
"temperature": 0,
"max_tokens": 16384,
# Claude Code is multimodal; images are passed by path and read with the
# CLI's Read tool rather than as inline base64 (see `_call_claude_cli`).
"vision": True,
},
}
@@ -214,6 +241,19 @@ def _resolve_max_tokens(default: int) -> int:
pass
return default
def _resolve_api_timeout(default: float = 600.0) -> float:
"""Honour GRAPHIFY_API_TIMEOUT env var override, else use default (seconds)."""
raw = os.environ.get("GRAPHIFY_API_TIMEOUT", "").strip()
if raw:
try:
v = float(raw)
if v > 0:
return v
except ValueError:
pass
return default
_EXTRACTION_SYSTEM = """\
You are a graphify semantic extraction agent. Extract a knowledge graph fragment from the files provided.
Output ONLY valid JSON — no explanation, no markdown fences, no preamble.
@@ -246,6 +286,20 @@ def _extraction_system(*, deep: bool = False) -> str:
return _EXTRACTION_SYSTEM + _DEEP_EXTRACTION_SUFFIX
def _file_to_text(path: Path) -> str:
"""Return a text-like file's content for the extraction prompt.
Most files are read directly. PDFs are binary, so reading them with
`read_text` yields garbage (the same failure images had); route them through
pypdf instead. A scanned PDF with no text layer extracts to an empty string,
which still produces a reference node rather than noise.
"""
if path.suffix.lower() == ".pdf":
from graphify.detect import extract_pdf_text
return extract_pdf_text(path)
return path.read_text(encoding="utf-8", errors="replace")
def _read_files(paths: list[Path], root: Path) -> str:
"""Return file contents formatted for the extraction prompt."""
parts: list[str] = []
@@ -255,13 +309,226 @@ def _read_files(paths: list[Path], root: Path) -> str:
except ValueError:
rel = p
try:
content = p.read_text(encoding="utf-8", errors="replace")
content = _file_to_text(p)
except OSError:
continue
parts.append(f"=== {rel} ===\n{content[:20000]}")
return "\n\n".join(parts)
# ── Image (vision) handling ───────────────────────────────────────────────────
# Raster image types a vision model can actually look at. `.svg` is intentionally
# excluded: it is XML markup, so `_read_files` reads it as text (the model parses
# the source directly), which is more useful than rasterising it. Before this,
# every image was fed through `path.read_text(errors="replace")`, turning binary
# pixels into garbage text — noise for API backends and an outright `exit 1` for
# the claude-cli backend.
_VISION_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp"}
_IMAGE_MEDIA_TYPES = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
}
# Per-image byte ceiling. Anthropic caps a request at 32 MB and Bedrock images
# at ~5 MB; 5 MB per image keeps every backend within limits. Oversized images
# fall back to a text reference (the node is still created, just unseen).
_MAX_IMAGE_BYTES = 5 * 1024 * 1024
# Flat token estimate per image for chunk packing. Vision models bill an image
# at a roughly fixed cost regardless of file size, so estimating by byte size
# (as the generic path does) would force every large PNG into its own chunk.
_IMAGE_TOKEN_ESTIMATE = 1_600
# Hard cap on images per chunk, independent of the token budget. A large
# token budget would otherwise pack hundreds of images into one request —
# past provider per-request image limits (Anthropic allows 100), and far too
# many for the claude-cli Read-tool loop to work through. Keeps memory and
# request size bounded on image-dense corpora.
_MAX_IMAGES_PER_CHUNK = 20
# Backends that read an image by file path (claude-cli's Read tool)
# instead of inlining base64. They open the file themselves and downsample as
# needed, so `_MAX_IMAGE_BYTES` does not apply and the bytes never need loading.
_PATH_IMAGE_BACKENDS = {"claude-cli"}
@dataclass
class _ImageRef:
"""A single image destined for a vision request.
`raw` is None when the image is unreadable or exceeds `_MAX_IMAGE_BYTES`, or
when the target backend has no vision support — in every such case the
renderers emit a text reference instead of pixels, so the image still
becomes a graph node.
"""
path: Path # absolute path (claude-cli reads it via the Read tool)
rel: str # path relative to the corpus root (the node's source_file)
media_type: str # e.g. "image/png"
raw: bytes | None
@property
def b64(self) -> str:
return base64.standard_b64encode(self.raw).decode("ascii") if self.raw else ""
@property
def bedrock_format(self) -> str:
# Converse wants a bare format token, not a media type.
return self.media_type.split("/", 1)[-1]
def _is_vision_image(path: Path) -> bool:
return path.suffix.lower() in _VISION_IMAGE_EXTENSIONS
def _partition_semantic_files(files: list[Path]) -> tuple[list[Path], list[Path]]:
"""Split a chunk into (text-like files, raster-image files)."""
text_files = [f for f in files if not _is_vision_image(f)]
image_files = [f for f in files if _is_vision_image(f)]
return text_files, image_files
def _build_image_refs(image_files: list[Path], root: Path, *, read_bytes: bool = True) -> list[_ImageRef]:
"""Build `_ImageRef`s for raster images.
`read_bytes=True` (base64 backends) loads the pixels and drops any image over
`_MAX_IMAGE_BYTES` to a reference, because a base64 request body has a hard
size ceiling. `read_bytes=False` (path-based backends — claude-cli)
skips the read entirely: those backends open the file themselves and
downsample as needed, so there is no per-image size limit and no reason to
load (potentially tens of MB of) bytes that would never be used.
"""
refs: list[_ImageRef] = []
for p in image_files:
try:
rel = str(p.relative_to(root))
except ValueError:
rel = str(p)
media = _IMAGE_MEDIA_TYPES.get(p.suffix.lower(), "image/png")
raw: bytes | None = None
if read_bytes:
try:
raw = p.read_bytes()
except OSError as exc:
print(f"[graphify] could not read image {rel}: {exc}", file=sys.stderr)
raw = None
if raw is not None and len(raw) > _MAX_IMAGE_BYTES:
print(
f"[graphify] image {rel} is {len(raw) // 1024} KB, over the "
f"{_MAX_IMAGE_BYTES // (1024 * 1024)} MB inline-image limit for this "
"backend; sending it as a reference node without inline pixels.",
file=sys.stderr,
)
raw = None
try:
abs_path = p.resolve()
except OSError:
abs_path = p
refs.append(_ImageRef(abs_path, rel, media, raw))
return refs
def _strip_pixels(refs: list[_ImageRef]) -> list[_ImageRef]:
"""Return refs with pixel data dropped (for non-vision backends)."""
return [replace(r, raw=None) for r in refs]
def _backend_supports_vision(backend: str) -> bool:
"""Whether `backend`'s configured model can see images.
Ollama is special-cased: its default model is text-only, so vision is
opt-in via GRAPHIFY_OLLAMA_VISION=1 once the user selects a vision model
(e.g. --model llama3.2-vision).
"""
if backend == "ollama":
return os.environ.get("GRAPHIFY_OLLAMA_VISION", "").strip() == "1"
return bool(BACKENDS.get(backend, {}).get("vision", False))
def _image_notes(refs: list[_ImageRef], *, with_paths: bool = False) -> str:
"""Text block listing the images so the model emits one node per image.
Always included alongside the visual payload (and used on its own when the
backend can't see pixels), so an image becomes a graph node either way.
`with_paths=True` also lists the absolute path and asks the model to open it
with the Read tool — used by the claude-cli backend.
"""
if not refs:
return ""
if with_paths:
header = (
"Use the Read tool to open and view each image file at the path below, "
"then emit one node per image"
)
else:
header = (
"The following image file(s) are attached as visual input. Emit one "
"node per image"
)
lines = [
"=== IMAGES ===",
f"{header} with \"file_type\":\"image\" and the listed source_file, a label "
"describing what it depicts (diagram, screenshot, chart, photo, UI, logo), "
"and edges to any code/doc nodes the image clearly references.",
]
for i, r in enumerate(refs, 1):
note = f"[image {i}] source_file: {r.rel}"
if with_paths:
note += f" path: {r.path}"
if r.raw is None and not with_paths:
note += " (not shown: unreadable or exceeds size limit)"
lines.append(note)
return "\n".join(lines)
def _with_image_notes(user_message: str, refs: list[_ImageRef], *, with_paths: bool = False) -> str:
notes = _image_notes(refs, with_paths=with_paths)
if not notes:
return user_message
if not user_message.strip():
return notes
return f"{user_message}\n\n{notes}"
def _anthropic_content(user_message: str, refs: list[_ImageRef]):
"""Build the Anthropic `messages[].content` value (str, or block list with images)."""
blocks = [
{"type": "image", "source": {"type": "base64", "media_type": r.media_type, "data": r.b64}}
for r in refs
if r.raw
]
text = _with_image_notes(user_message, refs)
if not blocks:
return text
return [*blocks, {"type": "text", "text": text}]
def _openai_content(user_message: str, refs: list[_ImageRef]):
"""Build the OpenAI-compatible user `content` value (str, or part list with images)."""
parts: list[dict] = [
{
"type": "image_url",
"image_url": {"url": f"data:{r.media_type};base64,{r.b64}", "detail": "auto"},
}
for r in refs
if r.raw
]
text = _with_image_notes(user_message, refs)
if not parts:
return text
return [{"type": "text", "text": text}, *parts]
def _bedrock_content(user_message: str, refs: list[_ImageRef]) -> list[dict]:
"""Build the Bedrock Converse user content list (raw bytes, not base64)."""
content: list[dict] = [
{"image": {"format": r.bedrock_format, "source": {"bytes": r.raw}}}
for r in refs
if r.raw
]
content.append({"text": _with_image_notes(user_message, refs)})
return content
_LLM_JSON_MAX_BYTES = 10 * 1024 * 1024 # 10 MB hard cap before json.loads (F-016)
@@ -421,6 +688,7 @@ def _call_openai_compat(
*,
backend: str = "",
deep_mode: bool = False,
images: list[_ImageRef] | None = None,
) -> dict:
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
try:
@@ -434,21 +702,12 @@ def _call_openai_compat(
# default. Honour GRAPHIFY_API_TIMEOUT (seconds) for explicit override;
# default to 600s, which is long enough for a 31B model on a 16k chunk
# but still bounds runaway connections (issue #792 addendum).
timeout_raw = os.environ.get("GRAPHIFY_API_TIMEOUT", "").strip()
timeout_s: float = 600.0
if timeout_raw:
try:
v = float(timeout_raw)
if v > 0:
timeout_s = v
except ValueError:
pass
client = OpenAI(api_key=api_key, base_url=base_url, timeout=timeout_s)
client = OpenAI(api_key=api_key, base_url=base_url, timeout=_resolve_api_timeout())
kwargs: dict = {
"model": model,
"messages": [
{"role": "system", "content": _extraction_system(deep=deep_mode)},
{"role": "user", "content": user_message},
{"role": "user", "content": _openai_content(user_message, images or [])},
],
"max_completion_tokens": max_completion_tokens,
}
@@ -543,19 +802,19 @@ def _call_openai_compat(
return result
def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False) -> dict:
def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False, images: list[_ImageRef] | None = None) -> dict:
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
try:
import anthropic
except ImportError as exc:
raise ImportError(_backend_pkg_hint("anthropic", "anthropic")) from exc
client = anthropic.Anthropic(api_key=api_key)
client = anthropic.Anthropic(api_key=api_key, timeout=_resolve_api_timeout())
resp = client.messages.create(
model=model,
max_tokens=max_tokens,
system=_extraction_system(deep=deep_mode),
messages=[{"role": "user", "content": user_message}],
messages=[{"role": "user", "content": _anthropic_content(user_message, images or [])}],
)
raw_content = resp.content[0].text if resp.content else None
result = _parse_llm_json(raw_content or "{}")
@@ -576,12 +835,16 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
return result
def _call_claude_cli(user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False) -> dict:
def _call_claude_cli(user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False, images: list[_ImageRef] | None = None) -> dict:
"""Call Claude via the locally-installed Claude Code CLI (`claude -p`).
Routes through the user's Claude Code subscription auth instead of a separate
ANTHROPIC_API_KEY. Useful for Pro/Max subscribers who don't want to provision
a pay-as-you-go API key just to run graphify's semantic pass.
Images are passed by absolute path rather than inline base64: the prompt asks
the model to open each one with its Read tool, and each containing directory
is allowlisted with `--add-dir` so the read is permitted.
"""
import platform
import shutil
@@ -617,10 +880,23 @@ def _call_claude_cli(user_message: str, max_tokens: int = 8192, *, deep_mode: bo
# preamble — both of which fail the strict json.loads in _parse_llm_json.
# Replacing the default prompt eliminates the conflict at the source.
# Side benefit: cache-creation tokens per call drop ~19% in practice.
# When images are present, append the Read-the-paths instruction and
# allowlist each containing directory so the CLI's Read tool can open them.
add_dir_args: list[str] = []
if images:
user_message = _with_image_notes(user_message, images, with_paths=True)
seen_dirs: set[str] = set()
for r in images:
d = str(r.path.parent)
if d not in seen_dirs:
seen_dirs.add(d)
add_dir_args.extend(["--add-dir", d])
cli_args = [
claude_cmd, "-p",
"--output-format", "json",
"--no-session-persistence",
*add_dir_args,
"--system-prompt", _extraction_system(deep=deep_mode),
]
# claude-cli defaults to Opus, which is overkill for the structured-JSON
@@ -637,7 +913,7 @@ def _call_claude_cli(user_message: str, max_tokens: int = 8192, *, deep_mode: bo
capture_output=True,
text=True,
encoding="utf-8", # Force UTF-8 — prevents UnicodeEncodeError on Windows cp1252
timeout=600,
timeout=_resolve_api_timeout(),
check=False,
)
if proc.returncode != 0:
@@ -676,7 +952,69 @@ def _call_claude_cli(user_message: str, max_tokens: int = 8192, *, deep_mode: bo
return result
def _call_bedrock(model: str, user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False) -> dict:
def _azure_client(api_key: str, endpoint: str):
"""Construct an AzureOpenAI client with env-driven api_version and timeout."""
try:
from openai import AzureOpenAI
except ImportError as exc:
raise ImportError(
"Azure OpenAI requires the openai package. Run: pip install openai"
) from exc
api_version = os.environ.get("AZURE_OPENAI_API_VERSION", "2024-12-01-preview").strip()
timeout_raw = os.environ.get("GRAPHIFY_API_TIMEOUT", "").strip()
timeout_s: float = 600.0
if timeout_raw:
try:
v = float(timeout_raw)
if v > 0:
timeout_s = v
except ValueError:
pass
return AzureOpenAI(api_key=api_key, azure_endpoint=endpoint, api_version=api_version, timeout=timeout_s)
def _call_azure(
api_key: str,
endpoint: str,
model: str,
user_message: str,
temperature: float | None = 0,
max_tokens: int = 8192,
*,
deep_mode: bool = False,
) -> dict:
"""Call Azure OpenAI Service via the AzureOpenAI SDK client."""
client = _azure_client(api_key, endpoint)
kwargs: dict = {
"model": model,
"messages": [
{"role": "system", "content": _extraction_system(deep=deep_mode)},
{"role": "user", "content": user_message},
],
"max_completion_tokens": max_tokens,
}
if temperature is not None:
kwargs["temperature"] = temperature
resp = client.chat.completions.create(**kwargs)
if not resp.choices or resp.choices[0].message is None:
raise ValueError("Azure OpenAI returned empty or filtered response")
raw_content = resp.choices[0].message.content
result = _parse_llm_json(raw_content or "{}")
result["input_tokens"] = resp.usage.prompt_tokens if resp.usage else 0
result["output_tokens"] = resp.usage.completion_tokens if resp.usage else 0
result["model"] = model
result["finish_reason"] = resp.choices[0].finish_reason
if _response_is_hollow(raw_content, result) and result["finish_reason"] != "length":
print(
"[graphify] azure returned a hollow response; treating as "
"truncation so adaptive retry can bisect the chunk.",
file=sys.stderr,
)
result["finish_reason"] = "length"
return result
def _call_bedrock(model: str, user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False, images: list[_ImageRef] | None = None) -> dict:
"""Call AWS Bedrock via boto3 Converse API using the standard AWS credential chain."""
try:
import boto3
@@ -695,7 +1033,7 @@ def _call_bedrock(model: str, user_message: str, max_tokens: int = 8192, *, deep
resp = client.converse(
modelId=model,
system=[{"text": _extraction_system(deep=deep_mode)}],
messages=[{"role": "user", "content": [{"text": user_message}]}],
messages=[{"role": "user", "content": _bedrock_content(user_message, images or [])}],
inferenceConfig={"maxTokens": max_tokens, "temperature": 0},
)
except botocore.exceptions.ClientError as exc:
@@ -740,7 +1078,8 @@ def extract_files_direct(
if backend is None:
raise ValueError(
"No LLM backend configured. Set one of: GEMINI_API_KEY, ANTHROPIC_API_KEY, "
"OPENAI_API_KEY, DEEPSEEK_API_KEY, MOONSHOT_API_KEY, OLLAMA_BASE_URL, "
"OPENAI_API_KEY, DEEPSEEK_API_KEY, MOONSHOT_API_KEY, "
"AZURE_OPENAI_API_KEY+AZURE_OPENAI_ENDPOINT, OLLAMA_BASE_URL, "
"or AWS credentials. Pass backend= explicitly to select a provider."
)
if backend not in BACKENDS:
@@ -767,15 +1106,42 @@ def extract_files_direct(
f"Set {_format_backend_env_keys(backend)} or pass api_key=."
)
mdl = model or _default_model_for_backend(backend)
user_msg = _read_files(files, root)
# Separate raster images from text-like files. Text goes through _read_files
# as before; images become structured refs the backend renders as pixels
# (vision backends) or as a text reference node (everything else).
text_files, image_files = _partition_semantic_files(files)
user_msg = _read_files(text_files, root)
vision = _backend_supports_vision(backend)
# Only base64 (inline) vision backends need the bytes loaded + size-capped;
# path-based backends (claude-cli) and non-vision backends do not.
read_bytes = vision and backend not in _PATH_IMAGE_BACKENDS
image_refs = _build_image_refs(image_files, root, read_bytes=read_bytes) if image_files else []
if image_refs and not vision:
image_refs = _strip_pixels(image_refs)
max_out = _resolve_max_tokens(cfg.get("max_tokens", 8192))
if backend == "claude":
return _call_claude(key, mdl, user_msg, max_tokens=max_out, deep_mode=deep_mode)
return _call_claude(key, mdl, user_msg, max_tokens=max_out, deep_mode=deep_mode, images=image_refs)
if backend == "claude-cli":
return _call_claude_cli(user_msg, max_tokens=max_out, deep_mode=deep_mode)
return _call_claude_cli(user_msg, max_tokens=max_out, deep_mode=deep_mode, images=image_refs)
if backend == "bedrock":
return _call_bedrock(mdl, user_msg, max_tokens=max_out, deep_mode=deep_mode)
return _call_bedrock(mdl, user_msg, max_tokens=max_out, deep_mode=deep_mode, images=image_refs)
if backend == "azure":
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT", "").strip()
if not endpoint:
raise ValueError(
"Azure OpenAI backend requires AZURE_OPENAI_ENDPOINT to be set "
"(e.g. https://my-resource.openai.azure.com/)."
)
return _call_azure(
key,
endpoint,
mdl,
user_msg,
temperature=cfg.get("temperature", 0),
max_tokens=max_out,
deep_mode=deep_mode,
)
return _call_openai_compat(
cfg["base_url"],
key,
@@ -786,6 +1152,7 @@ def extract_files_direct(
max_completion_tokens=_resolve_max_tokens(cfg.get("max_completion_tokens", 8192)),
backend=backend,
deep_mode=deep_mode,
images=image_refs,
)
@@ -798,6 +1165,10 @@ def _estimate_file_tokens(path: Path) -> int:
the `=== rel ===` separator. Returns 0 for unreadable paths so they don't
blow up packing.
"""
# Raster images are not read as text; a vision model bills them at a roughly
# fixed token cost, so estimate by image count rather than (binary) byte size.
if _is_vision_image(path):
return _IMAGE_TOKEN_ESTIMATE
if _TOKENIZER is None:
try:
size = path.stat().st_size
@@ -837,16 +1208,22 @@ def _pack_chunks_by_tokens(
chunks: list[list[Path]] = []
current: list[Path] = []
current_tokens = 0
current_images = 0
for directory in sorted(by_dir):
for path in by_dir[directory]:
cost = _estimate_file_tokens(path)
if current and current_tokens + cost > token_budget:
is_image = _is_vision_image(path)
over_budget = current_tokens + cost > token_budget
over_images = is_image and current_images >= _MAX_IMAGES_PER_CHUNK
if current and (over_budget or over_images):
chunks.append(current)
current = []
current_tokens = 0
current_images = 0
current.append(path)
current_tokens += cost
current_images += is_image
if current:
chunks.append(current)
@@ -1200,7 +1577,7 @@ def _call_llm(prompt: str, *, backend: str, max_tokens: int = 200) -> str:
capture_output=True,
text=True,
encoding="utf-8", # Force UTF-8 — prevents UnicodeEncodeError on Windows cp1252
timeout=600,
timeout=_resolve_api_timeout(),
check=False,
)
if proc.returncode != 0:
@@ -1211,6 +1588,7 @@ def _call_llm(prompt: str, *, backend: str, max_tokens: int = 200) -> str:
raise RuntimeError(f"claude -p produced unparseable JSON envelope: {exc}") from exc
return envelope.get("result", "")
if backend == "bedrock":
try:
import boto3
@@ -1227,6 +1605,23 @@ def _call_llm(prompt: str, *, backend: str, max_tokens: int = 200) -> str:
)
return resp.get("output", {}).get("message", {}).get("content", [{}])[0].get("text", "")
if backend == "azure":
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT", "").strip()
if not endpoint:
raise ValueError(
"Azure OpenAI backend requires AZURE_OPENAI_ENDPOINT to be set."
)
azure_client = _azure_client(key, endpoint)
resp = azure_client.chat.completions.create(
model=mdl,
messages=[{"role": "user", "content": prompt}],
max_completion_tokens=max_tokens,
temperature=cfg.get("temperature", 0),
)
if not resp.choices or resp.choices[0].message is None:
raise ValueError("Azure OpenAI returned empty or filtered response")
return resp.choices[0].message.content or ""
# OpenAI-compatible (kimi, openai, gemini, ollama)
try:
from openai import OpenAI
@@ -1336,7 +1731,7 @@ def _validate_ollama_base_url(url: str, *, warn: bool = True) -> None:
def detect_backend() -> str | None:
"""Return the name of whichever backend has an API key set, or None.
Priority: gemini → kimi → claude → openai → bedrock → ollama (last, opt-in).
Priority: gemini → kimi → claude → openai → deepseek → azure → bedrock → ollama (last, opt-in).
Ollama is intentionally checked LAST so a paid API key (Anthropic/OpenAI/etc.)
is never silently shadowed by an incidental OLLAMA_BASE_URL in the environment
@@ -1347,6 +1742,8 @@ def detect_backend() -> str | None:
for backend in ("gemini", "kimi", "claude", "openai", "deepseek"):
if _get_backend_api_key(backend):
return backend
if _get_backend_api_key("azure") and os.environ.get("AZURE_OPENAI_ENDPOINT"):
return "azure"
if os.environ.get("AWS_PROFILE") or os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION"):
return "bedrock"
ollama_url = os.environ.get("OLLAMA_BASE_URL")
@@ -1354,7 +1751,7 @@ def detect_backend() -> str | None:
_validate_ollama_base_url(ollama_url)
return "ollama"
for name in BACKENDS:
if name not in ("gemini", "kimi", "claude", "openai", "deepseek", "bedrock", "ollama", "claude-cli"):
if name not in ("gemini", "kimi", "claude", "openai", "deepseek", "azure", "bedrock", "ollama", "claude-cli"):
if _get_backend_api_key(name):
return name
return None
+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
+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
+323 -7
View File
@@ -136,11 +136,38 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
scored = []
norm_terms = [tok for t in terms for tok in _search_tokens(t)]
idf = _compute_idf(G, norm_terms)
# Whole-query string for full-label matching (mirrors _find_node's `term`).
joined = " ".join(norm_terms)
# Weight the full-query bonus by the rarest constituent term so a specific
# multi-word label still outweighs common-token noise; floor at 1.0.
joined_w = max((idf.get(t, 1.0) for t in norm_terms), default=1.0)
for nid, data in G.nodes(data=True):
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
bare_label = norm_label.rstrip("()")
# Tokenized form of the label (punctuation stripped, same transform as the
# query). norm_label may still carry punctuation like ':' or '-', which a
# tokenized query can never equal; comparing token-joined forms on both
# sides makes "uoce: dehumidifier driver" match query "uoce dehumidifier
# driver".
label_tokens = " ".join(_search_tokens(data.get("label") or ""))
source = (data.get("source_file") or "").lower()
score = 0.0
# Full-query tier: a multi-word query that equals (or prefixes) the whole
# label must dominate the per-token bag-of-words sums below, so `path`/
# `query` resolve the same node `explain` does (via _find_node). Without
# this, no single token equals a multi-word label, the per-token exact
# tier never fires, and every node sharing the token set ties -> arbitrary
# node-id sort -> wrong/disconnected endpoint -> false "No path found".
if joined:
nid_lower = nid.lower()
if joined in (norm_label, bare_label, label_tokens, nid_lower):
score += _EXACT_MATCH_BONUS * 10 * joined_w
elif (
norm_label.startswith(joined)
or bare_label.startswith(joined)
or label_tokens.startswith(joined)
):
score += _PREFIX_MATCH_BONUS * 10 * joined_w
for t in norm_terms:
w = idf.get(t, 1.0)
# Three-tier precedence: exact > prefix > substring (take the
@@ -155,7 +182,10 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
score += _SOURCE_MATCH_BONUS * w
if score > 0:
scored.append((score, nid))
return sorted(scored, reverse=True)
# Sort by score desc; break ties toward the shorter label so a concise exact
# match beats a longer superset that happens to share the same score.
scored.sort(key=lambda s: (-s[0], len(G.nodes[s[1]].get("label") or s[1]), s[1]))
return scored
def _pick_seeds(scored: list[tuple[float, str]], max_k: int = 3, gap_ratio: float = 0.2) -> list[str]:
@@ -472,13 +502,18 @@ def _filter_blank_stdin() -> None:
sys.stdin = open(0, "r", closefd=False)
def serve(graph_path: str = "graphify-out/graph.json") -> None:
"""Start the MCP server. Requires pip install mcp."""
def _build_server(graph_path: str):
"""Build the configured low-level MCP Server (shared by every transport).
All graph query tools and resources are registered here over a single
``mcp.server.Server`` instance; the caller picks the transport (stdio or
Streamable HTTP) and runs it. Hot-reload of graph.json works the same way
regardless of transport, since reloads happen inside the tool handlers.
"""
import threading
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
from mcp.types import AnyUrl
except ImportError as e:
@@ -649,12 +684,15 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
]
def _tool_query_graph(arguments: dict) -> str:
import time as _time
from graphify import querylog
question = arguments["question"]
mode = arguments.get("mode", "bfs")
depth = min(int(arguments.get("depth", 3)), 6)
budget = int(arguments.get("token_budget", 2000))
context_filter = arguments.get("context_filter")
return _query_graph_text(
_t0 = _time.perf_counter()
result = _query_graph_text(
G,
question,
mode=mode,
@@ -662,6 +700,17 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
token_budget=budget,
context_filters=context_filter,
)
querylog.log_query(
kind="mcp_query",
question=question,
corpus=str(graph_path),
result=result,
mode=mode,
depth=depth,
token_budget=budget,
duration_ms=(_time.perf_counter() - _t0) * 1000,
)
return result
def _tool_get_node(arguments: dict) -> str:
label = arguments["label"].lower()
@@ -978,8 +1027,19 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
except Exception as exc:
return [types.TextContent(type="text", text=f"Error executing {name}: {exc}")]
return server
def serve(graph_path: str = "graphify-out/graph.json") -> None:
"""Start the MCP server over stdio (the default, per-developer transport)."""
try:
from mcp.server.stdio import stdio_server
except ImportError as e:
raise ImportError('mcp not installed. Run: pip install "graphifyy[mcp]"') from e
import asyncio
server = _build_server(graph_path)
async def main() -> None:
async with stdio_server() as streams:
await server.run(streams[0], streams[1], server.create_initialization_options())
@@ -988,6 +1048,262 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
asyncio.run(main())
class _MCPASGIApp:
"""Raw-ASGI wrapper around the Streamable HTTP session manager.
Passed to a Starlette ``Route`` as a class instance (not a function) so
Starlette treats it as an ASGI app: it serves the exact mount path for all
methods (GET/POST/DELETE) with no request/response wrapping and no
trailing-slash redirect — mirroring how FastMCP mounts the same manager.
"""
def __init__(self, manager) -> None:
self._manager = manager
async def __call__(self, scope, receive, send) -> None:
await self._manager.handle_request(scope, receive, send)
class _ApiKeyMiddleware:
"""Pure-ASGI API-key gate for the HTTP transport.
Implemented as raw ASGI (not Starlette's BaseHTTPMiddleware) on purpose:
BaseHTTPMiddleware buffers responses and breaks the Streamable HTTP SSE
stream. This short-circuits with 401 before the request ever reaches the
session manager, leaving the streaming path untouched for authorized calls.
"""
def __init__(self, app, api_key: str) -> None:
self.app = app
self._expected = api_key.encode("utf-8")
async def __call__(self, scope, receive, send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
import hmac
headers = dict(scope.get("headers") or [])
provided = headers.get(b"x-api-key")
if provided is None:
# RFC 6750: the auth scheme token is case-insensitive.
scheme, _, token = headers.get(b"authorization", b"").partition(b" ")
if scheme.lower() == b"bearer" and token:
provided = token.strip()
# Constant-time compare; reject when no key was supplied at all.
if provided is None or not hmac.compare_digest(provided, self._expected):
body = b'{"error": "unauthorized"}'
await send({
"type": "http.response.start",
"status": 401,
"headers": [
(b"content-type", b"application/json"),
(b"content-length", str(len(body)).encode("ascii")),
],
})
await send({"type": "http.response.body", "body": body})
return
await self.app(scope, receive, send)
def _build_http_app(
graph_path: str,
*,
host: str = "127.0.0.1",
port: int = 8080,
api_key: str | None = None,
path: str = "/mcp",
json_response: bool = False,
stateless: bool = False,
session_timeout: float | None = 3600.0,
):
"""Build the Starlette ASGI app for the Streamable HTTP transport.
Split out from :func:`serve_http` (which blocks on uvicorn) so the wiring
can be exercised with an in-process ASGI test client.
``session_timeout`` reaps stateful sessions idle for that many seconds so a
long-running shared server does not leak memory when IDE clients disconnect
without sending a DELETE. ``None`` (or <= 0) disables reaping; it is forced
to ``None`` in stateless mode, which has no sessions to reap.
"""
try:
import contextlib
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.routing import Route
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.server.transport_security import TransportSecuritySettings
except ImportError as e:
raise ImportError(
'HTTP transport needs the mcp extra (mcp + starlette + uvicorn). '
'Run: pip install "graphifyy[mcp]"'
) from e
# A blank key (e.g. --api-key "" or an empty GRAPHIFY_API_KEY) must not be
# mistaken for "auth on" — normalize it to None so the gate is unambiguous.
api_key = (api_key or "").strip() or None
server = _build_server(graph_path)
# DNS-rebinding protection. When the operator binds a wildcard address they
# are intentionally exposing the server, so accept any Host header; for a
# loopback/specific bind, restrict Host to that address (with and without
# the port) plus the localhost aliases.
if host in ("0.0.0.0", "::", ""):
security = TransportSecuritySettings(enable_dns_rebinding_protection=False)
else:
allowed = {host, "localhost", "127.0.0.1"}
allowed |= {f"{h}:{port}" for h in list(allowed)}
security = TransportSecuritySettings(allowed_hosts=sorted(allowed))
# The SDK rejects a non-positive timeout and forbids one in stateless mode.
idle_timeout = None if (stateless or not session_timeout or session_timeout <= 0) else session_timeout
manager = StreamableHTTPSessionManager(
app=server,
json_response=json_response,
stateless=stateless,
security_settings=security,
session_idle_timeout=idle_timeout,
)
@contextlib.asynccontextmanager
async def lifespan(_app):
# The session manager owns an anyio task group that must wrap the whole
# server lifetime, so enter it here rather than per-request.
async with manager.run():
yield
middleware = []
if api_key:
middleware.append(Middleware(_ApiKeyMiddleware, api_key=api_key))
return Starlette(
routes=[Route(path, endpoint=_MCPASGIApp(manager))],
middleware=middleware,
lifespan=lifespan,
)
def serve_http(
graph_path: str = "graphify-out/graph.json",
*,
host: str = "127.0.0.1",
port: int = 8080,
api_key: str | None = None,
path: str = "/mcp",
json_response: bool = False,
stateless: bool = False,
session_timeout: float | None = 3600.0,
) -> None:
"""Start the MCP server over Streamable HTTP (MCP spec 2025-03-26).
Serves the same tools/resources as the stdio transport, so a single shared
process can host the graph for a whole team. Clients point their IDE MCP
config at ``http://<host>:<port><path>`` (default ``/mcp``).
``api_key`` (or the ``GRAPHIFY_API_KEY`` env var) enables a simple header
check (``Authorization: Bearer <key>`` or ``X-API-Key: <key>``). OAuth is a
deliberate follow-up. Binding ``0.0.0.0`` exposes the server beyond
localhost — set an api_key when you do.
"""
try:
import uvicorn
except ImportError as e:
raise ImportError(
'HTTP transport needs the mcp extra (mcp + starlette + uvicorn). '
'Run: pip install "graphifyy[mcp]"'
) from e
api_key = (api_key or "").strip() or None
app = _build_http_app(
graph_path,
host=host,
port=port,
api_key=api_key,
path=path,
json_response=json_response,
stateless=stateless,
session_timeout=session_timeout,
)
auth_note = "api-key required" if api_key else "no auth (set --api-key to require one)"
print(
f"graphify MCP server (streamable-http) on http://{host}:{port}{path} - {auth_note}",
file=sys.stderr,
)
if host in ("0.0.0.0", "::", "") and not api_key:
print(
f"WARNING: binding {host or '0.0.0.0'} with no api-key exposes the graph "
"unauthenticated on the network. Set --api-key (or GRAPHIFY_API_KEY).",
file=sys.stderr,
)
uvicorn.run(app, host=host, port=port)
def _main(argv: list[str] | None = None) -> None:
import argparse
import os
parser = argparse.ArgumentParser(
prog="python -m graphify.serve",
description="Serve a graphify knowledge graph over MCP (stdio or Streamable HTTP).",
)
parser.add_argument(
"graph_path",
nargs="?",
default="graphify-out/graph.json",
help="Path to graph.json (default: graphify-out/graph.json)",
)
parser.add_argument(
"--transport",
choices=["stdio", "http"],
default="stdio",
help="Transport to serve on (default: stdio)",
)
parser.add_argument("--host", default="127.0.0.1", help="HTTP bind host (default: 127.0.0.1)")
parser.add_argument("--port", type=int, default=8080, help="HTTP bind port (default: 8080)")
parser.add_argument(
"--api-key",
default=os.environ.get("GRAPHIFY_API_KEY"),
help="Require this key on the HTTP transport (env: GRAPHIFY_API_KEY)",
)
parser.add_argument("--path", default="/mcp", help="HTTP mount path (default: /mcp)")
parser.add_argument(
"--json-response",
action="store_true",
help="Return plain JSON responses instead of SSE streams",
)
parser.add_argument(
"--stateless",
action="store_true",
help="Run without per-session state (for load-balanced / CI deployments)",
)
parser.add_argument(
"--session-timeout",
type=float,
default=3600.0,
help="Reap stateful sessions idle this many seconds (default: 3600; 0 disables)",
)
args = parser.parse_args(argv)
if args.transport == "http":
serve_http(
args.graph_path,
host=args.host,
port=args.port,
api_key=args.api_key,
path=args.path,
json_response=args.json_response,
stateless=args.stateless,
session_timeout=args.session_timeout,
)
else:
serve(args.graph_path)
if __name__ == "__main__":
graph_path = sys.argv[1] if len(sys.argv) > 1 else "graphify-out/graph.json"
serve(graph_path)
_main()
+1 -1
View File
@@ -684,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
```
+2 -1
View File
@@ -520,7 +520,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -520,7 +520,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+1 -1
View File
@@ -801,7 +801,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json graphify-out/.graphify_incremental.json graphify-out/.graphify_transcripts.json graphify-out/.graphify_old.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_incremental.json graphify-out/.graphify_transcripts.json graphify-out/.graphify_old.json; find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -520,7 +520,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -522,7 +522,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -515,7 +515,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -522,7 +522,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -521,7 +521,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -519,7 +519,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -545,7 +545,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+6 -1
View File
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+19 -4
View File
@@ -543,9 +543,19 @@ def _rebuild_code(
evict_sources.add(sf)
evict_sources.add(norm)
deleted_paths.add(norm)
# On a full re-extraction every code file is re-extracted, so
# new_ast_ids is the complete current AST set. Any AST-marked node
# missing from it is stale and must be dropped even if its source
# file still exists (a symbol removed from a surviving file, #1116).
# Gate on full_rebuild: in incremental mode an AST node from an
# unchanged file is legitimately absent from new_ast_ids. Semantic
# nodes lack the "_origin" marker, so they are never dropped here —
# only by the deleted-file eviction in evict_sources above.
full_rebuild = changed_paths is None
preserved_nodes = [
n for n in existing.get("nodes", [])
if n["id"] not in new_ast_ids
and not (full_rebuild and n.get("_origin") == "ast")
and (not evict_sources or n.get("source_file") not in evict_sources)
]
all_ids = new_ast_ids | {n["id"] for n in preserved_nodes}
@@ -565,7 +575,12 @@ def _rebuild_code(
_relativize_source_files(result, project_root)
out.mkdir(exist_ok=True)
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
# Write the user-supplied path rather than the resolved absolute form
# so a committed ``graphify-out/.graphify_root`` is portable across
# clones and CI runners (#777). When ``watch_path`` is ``.`` (the
# common case for ``graphify update``), this writes ``.`` and the
# subsequent re-run resolves it against the caller's CWD.
(out / ".graphify_root").write_text(str(watch_path), encoding="utf-8")
if no_cluster:
# Normalise to "links" key so schema is consistent with the full clustered path.
@@ -595,7 +610,7 @@ def _rebuild_code(
try:
from graphify.detect import save_manifest
save_manifest(detected["files"], kind="ast")
save_manifest(detected["files"], kind="ast", root=project_root)
except Exception:
pass
@@ -633,7 +648,7 @@ def _rebuild_code(
if same_topology:
try:
from graphify.detect import save_manifest
save_manifest(detected["files"], kind="ast")
save_manifest(detected["files"], kind="ast", root=project_root)
except Exception:
pass
flag = out / "needs_update"
@@ -704,7 +719,7 @@ def _rebuild_code(
try:
from graphify.detect import save_manifest
save_manifest(detected["files"], kind="ast")
save_manifest(detected["files"], kind="ast", root=project_root)
except Exception:
pass
+11 -8
View File
@@ -4,16 +4,16 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.8.30"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Devin CLI, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
version = "0.8.34"
description = "AI coding assistant skill (Claude Code, CodeBuddy, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Devin CLI, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "kilo", "cursor", "gemini", "aider", "kiro", "pi", "devin", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
keywords = ["claude", "claude-code", "codebuddy", "codex", "opencode", "kilo", "cursor", "gemini", "aider", "kiro", "pi", "devin", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10"
dependencies = [
"networkx",
"datasketch",
"rapidfuzz",
"networkx>=3.4",
"datasketch>=1.6",
"rapidfuzz>=3.0",
"tree-sitter>=0.23.0",
"tree-sitter-python",
"tree-sitter-javascript",
@@ -52,10 +52,11 @@ mcp = ["mcp"]
neo4j = ["neo4j"]
pdf = ["pypdf", "markdownify"]
watch = ["watchdog"]
svg = ["matplotlib"]
svg = ["matplotlib", "numpy>=2.0; python_version >= '3.13'"]
leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
google = ["openpyxl"]
postgres = ["psycopg[binary]"]
video = ["faster-whisper; python_version >= '3.11'", "yt-dlp"]
kimi = ["openai", "tiktoken"]
ollama = ["openai"]
@@ -69,7 +70,8 @@ sql = ["tree-sitter-sql"]
# must compile from source (needs a C toolchain + python3-dev). Keeping it optional
# avoids breaking the default `uv tool install graphifyy` for everyone (#1104).
dm = ["tree-sitter-dm"]
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper; python_version >= '3.11'", "yt-dlp", "matplotlib", "openai", "tiktoken", "boto3", "anthropic", "tree-sitter-sql", "jieba", "tree-sitter-dm"]
terraform = ["tree-sitter-hcl"]
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper; python_version >= '3.11'", "yt-dlp", "matplotlib", "numpy>=2.0; python_version >= '3.13'", "openai", "tiktoken", "boto3", "anthropic", "tree-sitter-sql", "jieba", "tree-sitter-dm", "tree-sitter-hcl"]
[project.scripts]
graphify = "graphify.__main__:main"
@@ -91,6 +93,7 @@ dev = [
"setuptools>=82.0.1",
"wheel>=0.47.0",
"tomli>=2.0 ; python_version < '3.11'",
"tree-sitter-hcl>=1.2.0",
]
[tool.uv]
+55
View File
@@ -0,0 +1,55 @@
public with sharing class AccountService {
private static final String DEFAULT_TYPE = 'Customer';
public interface Notifiable {
void notify(String message);
}
public enum AccountStatus { ACTIVE, INACTIVE, PENDING }
@AuraEnabled
public static List<Account> getAccounts(String accountType) {
return [SELECT Id, Name, Type FROM Account WHERE Type = :accountType];
}
@future
public static void updateAccountsAsync(List<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account acc : accounts) {
acc.Type = DEFAULT_TYPE;
}
update accounts;
}
@InvocableMethod(label='Create Account' description='Creates a new Account')
public static List<Id> createAccounts(List<String> names) {
List<Account> toInsert = new List<Account>();
for (String n : names) {
toInsert.add(new Account(Name = n));
}
insert toInsert;
List<Id> ids = new List<Id>();
for (Account a : toInsert) {
ids.add(a.Id);
}
return ids;
}
public static void deleteOldAccounts(Date cutoff) {
List<Account> old = [SELECT Id FROM Account WHERE CreatedDate < :cutoff];
delete old;
}
@isTest
static void testGetAccounts() {
List<Account> result = getAccounts('Customer');
System.assertNotEquals(null, result);
}
@isTest
static void testCreateAccounts() {
List<Id> ids = createAccounts(new List<String>{'Test'});
System.assertEquals(1, ids.size());
}
}
+8
View File
@@ -0,0 +1,8 @@
trigger AccountTrigger on Account (before insert, before update, after insert, after update) {
if (Trigger.isBefore) {
AccountService.validateAccounts(Trigger.new);
}
if (Trigger.isAfter && Trigger.isInsert) {
AccountService.sendWelcomeNotifications(Trigger.new);
}
}
+34
View File
@@ -58,3 +58,37 @@ def test_affected_cli_relation_filter_limits_reverse_traversal(monkeypatch, tmp_
assert "Relations: calls" in out
assert "X()" in out
assert "__init__.py" not in out
def test_affected_cli_forces_directed_on_undirected_graph(monkeypatch, tmp_path, capsys):
"""A graph persisted with directed=false must still recover caller->callee
direction (#1174): affected on the callee returns the caller, not the callee
or nothing. Without forcing directed=True, node_link_graph builds an
undirected Graph, predecessors() collapses, and the reverse traversal breaks.
"""
graph = nx.DiGraph()
graph.add_node("A", label="caller_fn", source_file="a.py", source_location="L1")
graph.add_node("B", label="callee_fn", source_file="b.py", source_location="L2")
graph.add_edge("A", "B", relation="calls", context="call", confidence="EXTRACTED")
data = json_graph.node_link_data(graph, edges="links")
# Persist as undirected on disk to reproduce the bug condition.
data["directed"] = False
graph_path = tmp_path / "graph.json"
graph_path.write_text(json.dumps(data), encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
mainmod.sys,
"argv",
["graphify", "affected", "B", "--relation", "calls", "--graph", str(graph_path)],
)
mainmod.main()
out = capsys.readouterr().out
# A (the caller) is affected by a change to B (the callee).
assert "caller_fn" in out
assert "calls" in out
# B is the query node, not an affected node, and the result is not empty.
assert "No affected nodes found." not in out
+144
View File
@@ -126,3 +126,147 @@ def test_body_content_no_frontmatter():
"""_body_content returns content unchanged when no frontmatter present."""
content = b"No frontmatter here."
assert _body_content(content) == content
# --- #777: portable cache source_file fields --------------------------------
# ``save_cached`` relativizes ``source_file`` entries inside the cache file
# so a committed ``graphify-out/cache/`` is portable across machines and
# CI runners. ``load_cached`` re-absolutizes them so consumers (extract,
# merge into graph.json) see the same shape that fresh extraction emits.
def test_save_cached_relativizes_source_file(tmp_path):
"""The on-disk cache JSON contains forward-slash relative source_file
entries — no absolute prefix from the saving machine leaks in."""
import json
from graphify.cache import save_cached, file_hash, cache_dir
(tmp_path / "src").mkdir()
src = tmp_path / "src" / "foo.py"
src.write_text("def x(): pass\n")
abs_src = str(src.resolve())
result = {
"nodes": [{"id": "n1", "label": "foo", "source_file": abs_src}],
"edges": [{"source": "n1", "target": "n1", "source_file": abs_src}],
}
save_cached(src, result, root=tmp_path, kind="ast")
h = file_hash(src, tmp_path)
entry = cache_dir(tmp_path, "ast") / f"{h}.json"
on_disk = json.loads(entry.read_text(encoding="utf-8"))
node_sources = {n["source_file"] for n in on_disk["nodes"]}
edge_sources = {e["source_file"] for e in on_disk["edges"]}
assert node_sources == {"src/foo.py"}, (
f"cache nodes must store relative source_file; got {node_sources}"
)
assert edge_sources == {"src/foo.py"}
def test_load_cached_absolutizes_source_file(tmp_path):
"""``load_cached`` returns the same absolute-path shape that a fresh
extraction produces, so consumers don't need to special-case cache
hits vs. fresh extraction."""
from graphify.cache import save_cached, load_cached
(tmp_path / "src").mkdir()
src = tmp_path / "src" / "foo.py"
src.write_text("def x(): pass\n")
abs_src = str(src.resolve())
save_cached(src, {
"nodes": [{"id": "n1", "source_file": abs_src}],
"edges": [{"source": "n1", "target": "n1", "source_file": abs_src}],
}, root=tmp_path, kind="ast")
loaded = load_cached(src, root=tmp_path, kind="ast")
assert loaded is not None
assert loaded["nodes"][0]["source_file"] == abs_src
assert loaded["edges"][0]["source_file"] == abs_src
def test_load_cached_passes_through_legacy_absolute_source_file(tmp_path):
"""Cache entries written by an older graphify (with absolute source_file
inside) must still load correctly: the absolutize step is a no-op for
already-absolute values."""
import json
from graphify.cache import load_cached, file_hash, cache_dir
(tmp_path / "src").mkdir()
src = tmp_path / "src" / "foo.py"
src.write_text("pass\n")
abs_src = str(src.resolve())
# Hand-write a legacy-format cache entry (absolute source_file).
h = file_hash(src, tmp_path)
entry = cache_dir(tmp_path, "ast") / f"{h}.json"
entry.write_text(json.dumps({
"nodes": [{"id": "n1", "source_file": abs_src}],
"edges": [],
}))
loaded = load_cached(src, root=tmp_path, kind="ast")
assert loaded is not None
assert loaded["nodes"][0]["source_file"] == abs_src
def test_cache_portable_across_roots(tmp_path):
"""End-to-end portability: a cache entry written at one root can be
consumed at a different absolute root because the file is content-hashed
AND its embedded source_file is stored relative."""
import json
import shutil
from graphify.cache import save_cached, load_cached, file_hash, cache_dir
repo_a = tmp_path / "repo_a"
repo_a.mkdir()
(repo_a / "src").mkdir()
src_a = repo_a / "src" / "foo.py"
src_a.write_text("def x(): pass\n")
save_cached(src_a, {
"nodes": [{"id": "n1", "source_file": str(src_a.resolve())}],
"edges": [],
}, root=repo_a, kind="ast")
# Copy corpus + cache to a second location with a different absolute prefix.
repo_b = tmp_path / "repo_b"
shutil.copytree(repo_a, repo_b)
src_b = repo_b / "src" / "foo.py"
loaded = load_cached(src_b, root=repo_b, kind="ast")
assert loaded is not None, (
"cache must port across absolute prefixes (content hash + relative source_file)"
)
# Source path re-anchored to the new root, not the old one.
assert loaded["nodes"][0]["source_file"] == str(src_b.resolve())
assert not str(repo_a) in loaded["nodes"][0]["source_file"]
def test_save_cached_in_root_symlink_keeps_symlink_name(tmp_path):
"""``source_file`` for an in-root symlink must be stored under the
symlink's own name, not the resolved target. Lower-impact than the
manifest case (cache lookup is content-hashed, not key-matched), but
keeps the on-disk shape consistent with what callers passed in."""
import json
from graphify.cache import save_cached, file_hash, cache_dir
(tmp_path / "sub").mkdir()
target = tmp_path / "sub" / "target.py"
target.write_text("pass\n")
alias = tmp_path / "alias.py"
try:
alias.symlink_to(target)
except (OSError, NotImplementedError):
import pytest
pytest.skip("filesystem does not support symlinks")
abs_alias = str(alias) # caller's view — the symlink path, unresolved
save_cached(alias, {
"nodes": [{"id": "n1", "source_file": abs_alias}],
"edges": [],
}, root=tmp_path, kind="ast")
h = file_hash(alias, tmp_path)
entry = cache_dir(tmp_path, "ast") / f"{h}.json"
on_disk = json.loads(entry.read_text(encoding="utf-8"))
assert on_disk["nodes"][0]["source_file"] == "alias.py", (
f"cache must store symlink name, not resolved target; got "
f"{on_disk['nodes'][0]['source_file']!r}"
)
+35
View File
@@ -193,3 +193,38 @@ def test_non_windows_uses_bare_claude(monkeypatch):
argv = run.call_args.args[0]
assert argv[0] == "claude"
# ---------- GRAPHIFY_API_TIMEOUT honoured by all backends ----------
def test_resolve_api_timeout_default(monkeypatch):
monkeypatch.delenv("GRAPHIFY_API_TIMEOUT", raising=False)
assert llm._resolve_api_timeout() == 600.0
def test_resolve_api_timeout_env_override(monkeypatch):
monkeypatch.setenv("GRAPHIFY_API_TIMEOUT", "45")
assert llm._resolve_api_timeout() == 45.0
def test_resolve_api_timeout_ignores_invalid(monkeypatch):
monkeypatch.setenv("GRAPHIFY_API_TIMEOUT", "not-a-number")
assert llm._resolve_api_timeout() == 600.0
def test_resolve_api_timeout_ignores_nonpositive(monkeypatch):
monkeypatch.setenv("GRAPHIFY_API_TIMEOUT", "0")
assert llm._resolve_api_timeout() == 600.0
def test_claude_cli_extraction_honours_timeout(monkeypatch, fake_claude):
monkeypatch.setenv("GRAPHIFY_API_TIMEOUT", "30")
llm._call_claude_cli("dummy", max_tokens=8192)
assert fake_claude.call_args.kwargs["timeout"] == 30.0
def test_call_llm_claude_cli_branch_honours_timeout(monkeypatch, fake_claude):
monkeypatch.setenv("GRAPHIFY_API_TIMEOUT", "30")
llm._call_llm(prompt="x", backend="claude-cli", max_tokens=10)
assert fake_claude.call_args.kwargs["timeout"] == 30.0
+341
View File
@@ -0,0 +1,341 @@
"""Tests for graphify codebuddy install / uninstall commands."""
import json
from pathlib import Path
import sys
from unittest.mock import patch
import pytest
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _codebuddy_install_user(tmp_path):
from graphify.__main__ import install
old_cwd = Path.cwd()
try:
import os
os.chdir(tmp_path)
with patch("graphify.__main__.Path.home", return_value=tmp_path):
install(platform="codebuddy")
finally:
import os
os.chdir(old_cwd)
def _skill_path_user(tmp_path):
return tmp_path / ".codebuddy" / "skills" / "graphify" / "SKILL.md"
def _skill_path_project(project_dir):
return project_dir / ".codebuddy" / "skills" / "graphify" / "SKILL.md"
def _codebuddy_md_path(project_dir):
return project_dir / "CODEBUDDY.md"
def _settings_path(project_dir):
return project_dir / ".codebuddy" / "settings.json"
# ---------------------------------------------------------------------------
# User-scope install (graphify install --platform codebuddy)
# ---------------------------------------------------------------------------
def test_codebuddy_install_user_creates_skill_file(tmp_path):
"""User-scope install copies skill to ~/.codebuddy/skills/graphify/SKILL.md."""
_codebuddy_install_user(tmp_path)
skill_path = _skill_path_user(tmp_path)
assert skill_path.exists()
def test_codebuddy_skill_file_contains_frontmatter(tmp_path):
"""Installed skill file must include graphify YAML frontmatter."""
_codebuddy_install_user(tmp_path)
content = _skill_path_user(tmp_path).read_text()
assert "name: graphify" in content
assert "description:" in content
def test_codebuddy_skill_file_references_graphify_query(tmp_path):
"""/graphify skill must mention graphify query (query-first policy)."""
_codebuddy_install_user(tmp_path)
content = _skill_path_user(tmp_path).read_text()
assert "graphify query" in content or "/graphify query" in content
# ---------------------------------------------------------------------------
# Project-scope install (graphify codebuddy install)
# ---------------------------------------------------------------------------
def test_codebuddy_install_project_writes_codebuddy_md(tmp_path):
"""Project-scope install writes CODEBUDDY.md with graphify section."""
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
md = _codebuddy_md_path(tmp_path)
assert md.exists()
content = md.read_text()
assert "## graphify" in content
assert "graphify-out/" in content
def test_codebuddy_install_project_writes_hook(tmp_path):
"""Project-scope install registers PreToolUse hook in .codebuddy/settings.json."""
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
settings_path = _settings_path(tmp_path)
assert settings_path.exists()
settings = json.loads(settings_path.read_text())
hooks = settings["hooks"]["PreToolUse"]
assert any("graphify" in str(h) for h in hooks)
def test_codebuddy_install_hook_has_bash_matcher(tmp_path):
"""The installed hook must include Bash matcher for code search interception."""
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
settings = json.loads(_settings_path(tmp_path).read_text())
hooks = settings["hooks"]["PreToolUse"]
bash_hooks = [h for h in hooks if h.get("matcher") == "Bash"]
assert any("graphify" in str(h) for h in bash_hooks)
def test_codebuddy_install_hook_has_read_glob_matcher(tmp_path):
"""The installed hook must include Read|Glob matcher for file-read interception."""
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
settings = json.loads(_settings_path(tmp_path).read_text())
hooks = settings["hooks"]["PreToolUse"]
read_hooks = [h for h in hooks if h.get("matcher") == "Read|Glob"]
assert any("graphify" in str(h) for h in read_hooks)
def test_codebuddy_install_idempotent(tmp_path):
"""Re-install does not duplicate ## graphify sections."""
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
codebuddy_install(tmp_path)
md = _codebuddy_md_path(tmp_path)
assert md.read_text().count("## graphify") == 1
def test_codebuddy_install_upgrades_stale_section(tmp_path):
"""Re-install replaces an old graphify section with the current template."""
from graphify.__main__ import codebuddy_install, _CODEBUDDY_MD_MARKER
# Write a stale section manually
md = _codebuddy_md_path(tmp_path)
md.write_text("old content\n\n## graphify\nThis is old instructions\n")
codebuddy_install(tmp_path)
content = md.read_text()
assert _CODEBUDDY_MD_MARKER in content
assert "old content" in content
assert "This is old instructions" not in content
assert "graphify-out/" in content
assert content.count("## graphify") == 1
def test_codebuddy_install_merges_existing_codebuddy_md(tmp_path):
"""Install appends to an existing CODEBUDDY.md, preserving other content."""
from graphify.__main__ import codebuddy_install
_codebuddy_md_path(tmp_path).write_text("# My project rules\n")
codebuddy_install(tmp_path)
content = _codebuddy_md_path(tmp_path).read_text()
assert "# My project rules" in content
assert "## graphify" in content
assert "graphify-out/" in content
def test_codebuddy_install_prints_no_change_on_second_run(tmp_path, capsys):
"""Second install prints '(no change)' when content is identical."""
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
out1 = capsys.readouterr().out
codebuddy_install(tmp_path)
out2 = capsys.readouterr().out
assert "no change" in out2
def test_codebuddy_install_hint_git_add(tmp_path, capsys):
"""Project-scoped install via CLI prints a git add hint."""
from graphify.__main__ import main
home = tmp_path / "home"
project = tmp_path / "project"
project.mkdir()
old_cwd = Path.cwd()
try:
import os
os.chdir(project)
with patch("graphify.__main__.Path.home", return_value=home):
sys.argv = ["graphify", "codebuddy", "install"]
main()
finally:
import os
os.chdir(old_cwd)
# codebuddy_install calls print() directly, no git add hint printed there
# so this test checks that no errors occur
# ---------------------------------------------------------------------------
# Uninstall
# ---------------------------------------------------------------------------
def test_codebuddy_uninstall_removes_section(tmp_path):
"""Uninstall removes the ## graphify section from CODEBUDDY.md."""
from graphify.__main__ import codebuddy_install, codebuddy_uninstall
codebuddy_install(tmp_path)
codebuddy_uninstall(tmp_path)
md = _codebuddy_md_path(tmp_path)
assert not md.exists()
def test_codebuddy_uninstall_removes_hook(tmp_path):
"""Uninstall removes the PreToolUse hook from .codebuddy/settings.json."""
from graphify.__main__ import codebuddy_install, codebuddy_uninstall
codebuddy_install(tmp_path)
codebuddy_uninstall(tmp_path)
settings_path = _settings_path(tmp_path)
if settings_path.exists():
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert not any("graphify" in str(h) for h in hooks)
def test_codebuddy_uninstall_noop_if_not_installed(tmp_path):
"""Uninstall should not raise when CODEBUDDY.md doesn't exist."""
from graphify.__main__ import codebuddy_uninstall
codebuddy_uninstall(tmp_path) # should not raise
def test_codebuddy_uninstall_noop_if_no_section(tmp_path):
"""Uninstall should not error when CODEBUDDY.md exists but no graphify section."""
from graphify.__main__ import codebuddy_uninstall
_codebuddy_md_path(tmp_path).write_text("# Some other project\n")
codebuddy_uninstall(tmp_path)
content = _codebuddy_md_path(tmp_path).read_text()
assert "# Some other project" in content
def test_codebuddy_uninstall_preserves_other_content(tmp_path):
"""Uninstall preserves non-graphify content in CODEBUDDY.md."""
from graphify.__main__ import codebuddy_install, codebuddy_uninstall
_codebuddy_md_path(tmp_path).write_text("# My project rules\n")
codebuddy_install(tmp_path)
codebuddy_uninstall(tmp_path)
# When graphify section was appended, uninstall removes it and the file
# becomes the original content
content = _codebuddy_md_path(tmp_path).read_text()
assert "## graphify" not in content
assert "# My project rules" in content
# ---------------------------------------------------------------------------
# uninstall_all integration
# ---------------------------------------------------------------------------
def test_uninstall_all_removes_codebuddy_md(tmp_path, monkeypatch):
"""graphify uninstall must clean up CODEBUDDY.md."""
from graphify.__main__ import main
home = tmp_path / "home"
project = tmp_path / "project"
project.mkdir()
monkeypatch.chdir(project)
with patch("graphify.__main__.Path.home", return_value=home):
monkeypatch.setattr(sys, "argv", ["graphify", "codebuddy", "install"])
main()
md = _codebuddy_md_path(project)
assert md.exists()
monkeypatch.setattr(sys, "argv", ["graphify", "uninstall"])
main()
assert not md.exists()
def test_uninstall_all_removes_codebuddy_hook(tmp_path, monkeypatch):
"""graphify uninstall must clean up .codebuddy/settings.json hooks."""
from graphify.__main__ import main
home = tmp_path / "home"
project = tmp_path / "project"
project.mkdir()
monkeypatch.chdir(project)
with patch("graphify.__main__.Path.home", return_value=home):
monkeypatch.setattr(sys, "argv", ["graphify", "codebuddy", "install"])
main()
monkeypatch.setattr(sys, "argv", ["graphify", "uninstall"])
main()
settings_path = _settings_path(project)
if settings_path.exists():
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert not any("graphify" in str(h) for h in hooks)
# ---------------------------------------------------------------------------
# Platform config sanity
# ---------------------------------------------------------------------------
def test_codebuddy_in_platform_config():
"""codebuddy must be registered in _PLATFORM_CONFIG."""
from graphify.__main__ import _PLATFORM_CONFIG
assert "codebuddy" in _PLATFORM_CONFIG
assert _PLATFORM_CONFIG["codebuddy"]["skill_file"] == "skill.md"
assert _PLATFORM_CONFIG["codebuddy"]["claude_md"] is False
def test_codebuddy_platform_skill_destination_user_scope(tmp_path):
"""User-scope destination must be ~/.codebuddy/skills/graphify/SKILL.md."""
from graphify.__main__ import _platform_skill_destination
with patch("graphify.__main__.Path.home", return_value=tmp_path):
dst = _platform_skill_destination("codebuddy", project=False)
assert dst == tmp_path / ".codebuddy" / "skills" / "graphify" / "SKILL.md"
def test_codebuddy_platform_skill_destination_project_scope(tmp_path):
"""Project-scope destination must be <project>/.codebuddy/skills/graphify/SKILL.md."""
from graphify.__main__ import _platform_skill_destination
dst = _platform_skill_destination("codebuddy", project=True, project_dir=tmp_path)
assert dst == tmp_path / ".codebuddy" / "skills" / "graphify" / "SKILL.md"
def test_codebuddy_in_main_help_text(capsys, monkeypatch):
"""`graphify --help` must list codebuddy in the platform list and per-platform section."""
from graphify.__main__ import main
monkeypatch.setattr(sys, "argv", ["graphify", "--help"])
main()
captured = capsys.readouterr().out
# codebuddy should appear in the top-level platform list
assert "|codebuddy)" in captured or "codebuddy" in captured, (
"codebuddy missing from `graphify --help` platform list"
)
# codebuddy install / uninstall should appear in the per-platform section
assert "codebuddy install" in captured, "`codebuddy install` line missing from help text"
assert "codebuddy uninstall" in captured, "`codebuddy uninstall` line missing from help text"
def test_codebuddy_skill_file_exists_in_package():
"""skill.md must be present in the installed package (shared with claude)."""
import graphify
skill = Path(graphify.__file__).parent / "skill.md"
assert skill.exists(), "skill.md missing from package"
def test_codebuddy_installation_roundtrip(tmp_path):
"""Install then uninstall leaves no trace of graphify CODEBUDDY.md or hook."""
from graphify.__main__ import codebuddy_install, codebuddy_uninstall
# Pre-existing project file
_codebuddy_md_path(tmp_path).write_text("# My project\n")
# One section above graphify to test cleanup
codebuddy_install(tmp_path)
codebuddy_uninstall(tmp_path)
# CODEBUDDY.md should exist with original content only
md = _codebuddy_md_path(tmp_path)
assert md.exists()
content = md.read_text()
assert "## graphify" not in content
assert "# My project" in content
# Hook should be removed
settings_path = _settings_path(tmp_path)
if settings_path.exists():
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert not any("graphify" in str(h) for h in hooks)
+243
View File
@@ -298,6 +298,43 @@ def test_detect_incremental_propagates_follow_symlinks(tmp_path, monkeypatch):
assert second["new_total"] == 0
def test_detect_incremental_survives_dict_valued_mtime(tmp_path, monkeypatch):
"""A schema-drifted manifest whose entry stores mtime as a nested dict
(instead of a float) must not crash detect_incremental (#1163). The guard
coerces the bad mtime to None so the file is re-verified by content hash and
treated as new, rather than blowing up on the int/float comparison.
"""
import json
monkeypatch.chdir(tmp_path)
src = tmp_path / "mod.py"
src.write_text("def f():\n return 1\n", encoding="utf-8")
manifest_dir = tmp_path / "graphify-out"
manifest_dir.mkdir()
manifest_path = str(manifest_dir / "manifest.json")
# Drifted entry: a non-empty ast_hash (so the dict branch reaches the mtime
# comparison) with mtime stored as a dict rather than a float. Absolute key
# so it matches detect's absolute file paths without re-anchoring.
drifted = {
str(src.resolve()): {
"mtime": {"mtime": 123.0},
"ast_hash": "deadbeef" * 4,
"semantic_hash": "cafebabe" * 4,
}
}
Path(manifest_path).write_text(json.dumps(drifted), encoding="utf-8")
# Must not raise (pre-fix: TypeError comparing float and dict).
result = detect_incremental(tmp_path, manifest_path)
# The drifted file is re-classified as new rather than silently skipped.
assert any("mod.py" in f for f in result["new_files"]["code"])
assert not any("mod.py" in f for f in result["unchanged_files"]["code"])
def test_classify_video_extensions():
"""Video and audio file extensions should classify as VIDEO."""
from graphify.detect import FileType
@@ -638,6 +675,33 @@ def test_sensitive_token_config_yaml():
assert _is_sensitive(Path("token_config.yaml"))
# ── Generic keywords must be load-bearing: topic slugs are not secret stores ──
# A keyword buried mid-phrase in a >=3-word descriptive name is a note ABOUT
# the topic, not a credential file. It must not be silently dropped.
def test_sensitive_does_not_flag_token_economics_note():
assert not _is_sensitive(Path("token-economics-of-recall.md"))
def test_sensitive_does_not_flag_password_policy_discussion():
assert not _is_sensitive(Path("password-policy-discussion.md"))
def test_sensitive_flags_keyword_at_end_of_long_name():
# Keyword as the final word names the file's contents — still a secret store.
assert _is_sensitive(Path("github-personal-access-token.txt"))
def test_sensitive_flags_my_private_key_txt():
# Multi-word keyword at end of stem (end-of-stem check runs before word
# counting, so splitting private_key on "_" cannot un-flag it).
assert _is_sensitive(Path("my_private_key.txt"))
def test_sensitive_flags_dotfile_token():
# Leading dot stripped before stem extraction; ".token" keeps its keyword.
assert _is_sensitive(Path(".token"))
def test_sensitive_flags_plural_tokens_txt():
assert _is_sensitive(Path("tokens.txt"))
# ── Issue #933: failed-chunk files must not be frozen in manifest ─────────────
def test_save_manifest_skips_semantic_hash_for_files_without_cache(tmp_path):
@@ -1057,3 +1121,182 @@ def test_shebang_interpreter_env_vs_assignment_before_interpreter(tmp_path):
script.write_bytes(b"#!/usr/bin/env -vS DEBUG=1 python3 -u\nprint('x')\n")
assert _shebang_interpreter(script) == "python3"
assert classify_file(script) == FileType.CODE
# --- #777: portable manifest paths ------------------------------------------
# When ``root`` is supplied, the on-disk manifest stores forward-slash
# relative keys so a committed ``graphify-out/`` round-trips across machines
# and CI runners. In-memory the keys are still absolute, so internal callers
# (notably :func:`detect_incremental`) remain unchanged.
def test_save_manifest_relativizes_keys_when_root_given(tmp_path):
"""``save_manifest(root=...)`` writes forward-slash relative keys."""
import json
from graphify.detect import save_manifest, load_manifest
(tmp_path / "src").mkdir()
(tmp_path / "src" / "foo.py").write_text("def x(): pass\n")
(tmp_path / "doc.md").write_text("hello\n")
manifest_path = str(tmp_path / "graphify-out" / "manifest.json")
files = {
"code": [str(tmp_path / "src" / "foo.py")],
"document": [str(tmp_path / "doc.md")],
}
save_manifest(files, manifest_path, root=tmp_path)
raw = json.loads(Path(manifest_path).read_text(encoding="utf-8"))
assert set(raw) == {"src/foo.py", "doc.md"}, (
f"on-disk keys must be relative posix paths, got {set(raw)}"
)
# Same file, loaded with root: callers see absolute keys back.
loaded = load_manifest(manifest_path, root=tmp_path)
abs_foo = str((tmp_path / "src" / "foo.py").resolve())
abs_doc = str((tmp_path / "doc.md").resolve())
assert set(loaded) == {abs_foo, abs_doc}
def test_save_manifest_without_root_keeps_absolute_keys(tmp_path):
"""Back-compat: callers that don't pass ``root`` still get the legacy
absolute-keyed manifest format. Required so skill-generated scripts that
call ``save_manifest(detect['files'])`` keep working unchanged."""
import json
from graphify.detect import save_manifest
f = tmp_path / "foo.py"
f.write_text("pass\n")
manifest_path = str(tmp_path / "graphify-out" / "manifest.json")
save_manifest({"code": [str(f)]}, manifest_path)
raw = json.loads(Path(manifest_path).read_text(encoding="utf-8"))
assert list(raw)[0] == str(f.resolve()), (
f"without root, keys must remain absolute; got {list(raw)}"
)
def test_load_manifest_absolutizes_relative_keys(tmp_path):
"""``load_manifest(root=...)`` re-anchors stored relative keys so the
in-memory shape matches what :func:`detect` returns."""
import json
from graphify.detect import load_manifest
manifest_path = tmp_path / "graphify-out" / "manifest.json"
manifest_path.parent.mkdir(parents=True)
manifest_path.write_text(json.dumps({
"src/foo.py": {"mtime": 0.0, "ast_hash": "h1", "semantic_hash": ""},
"doc.md": {"mtime": 0.0, "ast_hash": "h2", "semantic_hash": ""},
}))
loaded = load_manifest(str(manifest_path), root=tmp_path)
assert str((tmp_path / "src" / "foo.py").resolve()) in loaded
assert str((tmp_path / "doc.md").resolve()) in loaded
def test_load_manifest_passes_through_legacy_absolute_keys(tmp_path):
"""Legacy absolute-keyed manifests still load correctly when ``root``
is supplied — the absolutize step is a no-op for already-absolute keys."""
import json
from graphify.detect import load_manifest
manifest_path = tmp_path / "graphify-out" / "manifest.json"
manifest_path.parent.mkdir(parents=True)
abs_key = str((tmp_path / "foo.py").resolve())
manifest_path.write_text(json.dumps({abs_key: {"mtime": 0.0, "ast_hash": "h", "semantic_hash": ""}}))
loaded = load_manifest(str(manifest_path), root=tmp_path)
assert abs_key in loaded
def test_save_manifest_out_of_root_keeps_absolute(tmp_path):
"""Files outside ``root`` (e.g. symlinked external corpora) are stored
absolute so they round-trip on the saving machine even when they can't
be portably encoded."""
import json
from graphify.detect import save_manifest
outside = tmp_path.parent / f"{tmp_path.name}-sibling.py"
outside.write_text("pass\n")
try:
manifest_path = str(tmp_path / "graphify-out" / "manifest.json")
save_manifest({"code": [str(outside)]}, manifest_path, root=tmp_path)
raw = json.loads(Path(manifest_path).read_text(encoding="utf-8"))
key = list(raw)[0]
assert Path(key).is_absolute(), (
f"out-of-root entries must keep absolute keys, got {key!r}"
)
finally:
outside.unlink(missing_ok=True)
def test_detect_incremental_portable_across_paths(tmp_path):
"""End-to-end: a manifest written at one root must be readable from a
different absolute prefix (the cross-machine case #777 is about).
Simulates two checkouts of the same corpus by hard-linking files into a
second tmp dir and comparing detection results."""
import json
from graphify.detect import save_manifest, detect_incremental
# First "machine": create corpus, save manifest with root.
repo_a = tmp_path / "repo_a"
repo_a.mkdir()
(repo_a / "src").mkdir()
(repo_a / "src" / "foo.py").write_text("pass\n")
(repo_a / "doc.md").write_text("hello\n")
manifest_a = str(repo_a / "graphify-out" / "manifest.json")
files = {
"code": [str(repo_a / "src" / "foo.py")],
"document": [str(repo_a / "doc.md")],
}
save_manifest(files, manifest_a, root=repo_a)
# Second "machine": copy the corpus + manifest to a different absolute path.
repo_b = tmp_path / "repo_b"
(repo_b / "src").mkdir(parents=True)
(repo_b / "src" / "foo.py").write_text("pass\n")
(repo_b / "doc.md").write_text("hello\n")
(repo_b / "graphify-out").mkdir()
manifest_b = repo_b / "graphify-out" / "manifest.json"
manifest_b.write_text(Path(manifest_a).read_text())
# Stat the copied files match the originals' content hash so
# detect_incremental should see zero new files.
inc = detect_incremental(repo_b, str(manifest_b))
assert inc["new_total"] == 0, (
f"manifest must port across absolute paths; got new_total={inc['new_total']}"
)
def test_save_manifest_in_root_symlink_roundtrips(tmp_path):
"""In-root symlinks must store under the symlink's own name, not the
resolved target. Resolving the key when relativizing pointed the stored
entry at ``sub/target.py`` instead of ``alias.py``, so the original
``alias.py`` key missed on reload and re-extracted on every incremental
run."""
import json
from graphify.detect import save_manifest, load_manifest
(tmp_path / "sub").mkdir()
target = tmp_path / "sub" / "target.py"
target.write_text("pass\n")
alias = tmp_path / "alias.py"
try:
alias.symlink_to(target)
except (OSError, NotImplementedError):
import pytest
pytest.skip("filesystem does not support symlinks")
manifest_path = str(tmp_path / "graphify-out" / "manifest.json")
save_manifest({"code": [str(alias)]}, manifest_path, root=tmp_path)
raw = json.loads(Path(manifest_path).read_text(encoding="utf-8"))
assert "alias.py" in raw, (
f"in-root symlink must be stored under its own name, got {list(raw)}"
)
assert "sub/target.py" not in raw, (
f"symlink must not be stored under resolved target path; got {list(raw)}"
)
loaded = load_manifest(manifest_path, root=tmp_path)
assert str(tmp_path.resolve() / "alias.py") in loaded
+77
View File
@@ -121,3 +121,80 @@ def test_extract_succeeds_when_at_least_one_chunk_completes(
assert (out_dir / "graphify-out" / "graph.json").exists(), (
"graph.json must be written on the happy path"
)
def _code_only_corpus(tmp_path):
"""A corpus with only code — no docs/papers/images."""
(tmp_path / "auth.py").write_text(
"def login(user):\n return validate(user)\n\n"
"def validate(user):\n return True\n"
)
return tmp_path
def _clear_backend_keys(monkeypatch):
"""Clear every env var that detect_backend() or _get_backend_api_key() reads."""
for key in (
"GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENAI_API_KEY",
"ANTHROPIC_API_KEY", "DEEPSEEK_API_KEY", "MOONSHOT_API_KEY",
# bedrock: presence of any of these is treated as a valid credential
"AWS_PROFILE", "AWS_REGION", "AWS_DEFAULT_REGION", "AWS_ACCESS_KEY_ID",
# ollama: a set OLLAMA_BASE_URL triggers backend detection
"OLLAMA_BASE_URL",
):
monkeypatch.delenv(key, raising=False)
def test_extract_codeonly_succeeds_without_api_key(monkeypatch, tmp_path):
"""A code-only corpus must run with no LLM API key.
Regression: graphify extract validated a backend upfront and exited 1 with
'no LLM API key found' even for a code-only corpus that never calls a model.
The keyless AST path now runs to a written graph.json (#1122).
"""
corpus = _code_only_corpus(tmp_path)
out_dir = tmp_path / "out"
_clear_backend_keys(monkeypatch)
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
mainmod.sys, "argv",
["graphify", "extract", str(corpus), "--out", str(out_dir)],
)
try:
mainmod.main()
except SystemExit as exc:
assert exc.code in (None, 0), f"unexpected exit code {exc.code}"
graph = out_dir / "graphify-out" / "graph.json"
assert graph.exists(), "code-only extract must write graph.json without a key"
import json
assert len(json.loads(graph.read_text()).get("nodes", [])) > 0
def test_extract_without_key_still_errors_when_docs_present(
monkeypatch, tmp_path, capsys
):
"""Key requirement still fires when semantic work is needed.
A corpus with a Markdown doc needs LLM semantic extraction, so a keyless
extract must exit 1 with clear guidance (#1122).
"""
corpus = _make_corpus(tmp_path) # includes a Markdown doc
out_dir = tmp_path / "out"
_clear_backend_keys(monkeypatch)
# Patch detect_backend too so ambient AWS/ollama env can't slip through.
monkeypatch.setattr("graphify.llm.detect_backend", lambda: None)
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
mainmod.sys, "argv",
["graphify", "extract", str(corpus), "--out", str(out_dir)],
)
with pytest.raises(SystemExit) as exc_info:
mainmod.main()
assert exc_info.value.code == 1
err = capsys.readouterr().err
assert "no LLM API key found" in err
assert "code-only corpus needs no key" in err
assert not (out_dir / "graphify-out" / "graph.json").exists()
+155
View File
@@ -161,6 +161,44 @@ def test_hook_skips_head_on_exe():
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
def test_install_embeds_pinned_interpreter(tmp_path):
"""Hook scripts must embed sys.executable so the hook works without the
graphify launcher on PATH (uv tool / pipx isolation, #1127).
When graphify is installed via `uv tool install graphifyy` or `pipx install
graphifyy`, the interpreter lives in an isolated venv and the launcher is in
~/.local/bin. GUI git clients and CI runners often run with a minimal PATH
that omits that directory, so `command -v graphify` fails, the python3/python
fallbacks cannot import graphify (wrong venv), and the hook silently exits 0.
Pinning sys.executable at install time makes the hook work regardless of PATH.
"""
import re, sys
repo = _make_git_repo(tmp_path)
install(repo)
commit_hook = (repo / ".git" / "hooks" / "post-commit").read_text()
checkout_hook = (repo / ".git" / "hooks" / "post-checkout").read_text()
# Compute the sanitized value the same way install() does.
expected = sys.executable if not re.search(r"[^a-zA-Z0-9/_.@:\\-]", sys.executable) else ""
if expected:
assert expected in commit_hook, "sanitized sys.executable missing from post-commit"
assert expected in checkout_hook, "sanitized sys.executable missing from post-checkout"
# The placeholder must be fully substituted -- no __PINNED_PYTHON__ left.
assert "__PINNED_PYTHON__" not in commit_hook, "placeholder not substituted in post-commit"
assert "__PINNED_PYTHON__" not in checkout_hook, "placeholder not substituted in post-checkout"
def test_install_fallback_is_loud_not_silent(tmp_path):
"""The detection fallback must emit a message to stderr rather than bare exit 0.
A silent no-op (the pre-fix behaviour) leaves the user with no indication
that the hook ran but found nothing, making the bug extremely hard to diagnose.
"""
from graphify.hooks import _PYTHON_DETECT
assert "could not locate" in _PYTHON_DETECT, (
"fallback branch must print a diagnostic message; bare 'exit 0' is silent and unhelpful"
)
def test_hook_check_no_additionalContext(tmp_path):
"""graphify hook-check must not emit additionalContext — Codex Desktop rejects it."""
import sys
@@ -178,3 +216,120 @@ def test_hook_check_no_additionalContext(tmp_path):
assert result.returncode == 0
assert result.stdout == ""
assert result.stderr == ""
# ── #1161: background rebuild must not rely on nohup (missing on Git for Windows) ──
import ast # noqa: E402
import re # noqa: E402
from graphify.hooks import ( # noqa: E402
_HOOK_SCRIPT,
_CHECKOUT_SCRIPT,
_REBUILD_BODY_COMMIT,
_REBUILD_BODY_CHECKOUT,
_detached_launch,
)
_HOOK_SCRIPTS = [("post-commit", _HOOK_SCRIPT), ("post-checkout", _CHECKOUT_SCRIPT)]
@pytest.mark.parametrize("name,script", _HOOK_SCRIPTS)
def test_hooks_do_not_use_nohup(name, script):
"""Git for Windows' bundled shell ships no `nohup`/`setsid`, so the old
`nohup ... &` launch died with 'nohup: command not found' and the rebuild
silently never ran (#1161). The generated hooks must not reference either."""
assert "nohup" not in script, f"{name} still references nohup (#1161)"
assert "setsid" not in script, f"{name} still references setsid (#1161)"
assert "disown" not in script, f"{name} still uses disown (#1161)"
@pytest.mark.parametrize("name,script", _HOOK_SCRIPTS)
def test_hooks_use_cross_platform_detach(name, script):
"""The replacement detaches via Python: start_new_session on POSIX and
DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP on Windows (#1161)."""
assert "subprocess.Popen" in script
assert "start_new_session=True" in script, f"{name} missing POSIX detach"
assert "0x00000008" in script, f"{name} missing Windows DETACHED_PROCESS flag"
assert "0x00000200" in script, f"{name} missing CREATE_NEW_PROCESS_GROUP flag"
def _launcher_payload(script: str) -> str:
"""Extract the `python -c "<payload>"` the hook hands to GRAPHIFY_PYTHON.
The launcher is the only `-c` invocation whose body begins with
`import os, subprocess, sys` (the interpreter-detection probes in
_PYTHON_DETECT use `-c "import graphify"`)."""
m = re.search(r'-c "(import os, subprocess, sys.*?)"\n', script, re.DOTALL)
assert m, "launcher payload not found"
return m.group(1)
@pytest.mark.parametrize("name,script", _HOOK_SCRIPTS)
def test_launcher_payload_is_shell_quote_safe(name, script):
"""The launcher is carried inside a shell double-quoted `-c "..."` argument,
so it must contain no characters the shell would interpret there: an
unescaped double-quote, $, backtick or backslash would corrupt the hook."""
payload = _launcher_payload(script)
for bad in ('"', "$", "`", "\\"):
assert bad not in payload, f"{name} launcher payload contains unsafe {bad!r}"
@pytest.mark.parametrize("name,script", _HOOK_SCRIPTS)
def test_launcher_and_rebuild_body_are_valid_python(name, script):
"""Both the launcher and the rebuild body it re-executes must parse, so a
quoting slip can't ship a hook that crashes the moment git fires it."""
payload = _launcher_payload(script)
ast.parse(payload) # launcher itself
inner = re.search(r"_src = '''(.*?)'''", payload, re.DOTALL)
assert inner, f"{name}: embedded rebuild body not found"
ast.parse(inner.group(1)) # the detached child's source
def test_rebuild_bodies_are_shell_quote_safe():
"""The shared rebuild bodies are embedded verbatim into the launcher, so they
too must avoid characters unsafe inside a shell double-quoted argument."""
for body in (_REBUILD_BODY_COMMIT, _REBUILD_BODY_CHECKOUT):
for bad in ('"', "$", "`", "\\"):
assert bad not in body
assert "'''" not in body # would terminate the launcher's _src literal
@pytest.mark.parametrize(
"name,body",
[("post-commit", _REBUILD_BODY_COMMIT), ("post-checkout", _REBUILD_BODY_CHECKOUT)],
)
def test_rebuild_bodies_read_graphify_root(name, body):
"""The rebuild must honour the persisted scan root rather than hardcoding the
repo top (#1173). Both bodies read graphify-out/.graphify_root and pass the
recovered root to _rebuild_code instead of the bare Path('.')."""
assert "graphify-out/.graphify_root" in body, f"{name} ignores .graphify_root (#1173)"
# The recovered root is what gets rebuilt, not a hardcoded cwd.
assert "_rebuild_code(_root" in body, f"{name} does not pass the recovered root"
# Quote-safe inside the shell-double-quoted launcher: single quotes only.
assert "read_text(encoding='utf-8')" in body, f"{name} root read is not single-quoted"
def test_rebuild_bodies_with_graphify_root_are_valid_python():
"""The .graphify_root snippet must parse so a quoting slip can't ship a hook
that crashes the moment git fires it (#1173)."""
for body in (_REBUILD_BODY_COMMIT, _REBUILD_BODY_CHECKOUT):
ast.parse(body)
def test_detached_launch_targets_graphify_python():
"""The launcher must run via the resolved $GRAPHIFY_PYTHON, not a bare
`python`, so it uses the same interpreter the detection block selected."""
snippet = _detached_launch(_REBUILD_BODY_COMMIT)
assert snippet.startswith('"$GRAPHIFY_PYTHON" -c "')
assert "nohup" not in snippet
def test_installed_hooks_contain_no_nohup(tmp_path):
"""End-to-end: the files written to .git/hooks must be nohup-free (#1161)."""
repo = _make_git_repo(tmp_path)
install(repo)
for name in ("post-commit", "post-checkout"):
text = (repo / ".git" / "hooks" / name).read_text(encoding="utf-8")
assert "nohup" not in text, f"installed {name} still references nohup"
assert "start_new_session=True" in text
+345
View File
@@ -0,0 +1,345 @@
"""Tests for image-vision support across the direct extraction backends.
Covers the structured-message split (text vs raster image), the per-backend
payload rendering (Anthropic base64 blocks, OpenAI/Gemini image_url data URIs,
Bedrock raw-bytes Converse blocks, the claude-cli Read-tool path), and the vision-capability gating that sends pixels only to
backends whose model can see them.
Every backend is mocked (fake SDK module / subprocess), so the suite runs on CI
with no API keys, no network, and no `claude` binary.
"""
from __future__ import annotations
import json
import sys
import types
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from graphify import llm
# A 1x1 PNG is unnecessary — the renderers never decode pixels, they only base64
# the bytes — so any non-empty byte string stands in for image content.
_PNG_BYTES = b"\x89PNG\r\n\x1a\nFAKEPIXELDATA"
_NODE_JSON = json.dumps({
"nodes": [{"id": "x", "label": "L", "file_type": "image", "source_file": "a.png"}],
"edges": [],
"hyperedges": [],
})
def _make_corpus(tmp_path):
"""A corpus with one raster image, one svg (text), and one markdown doc."""
(tmp_path / "sub").mkdir()
img = tmp_path / "sub" / "diagram.png"
img.write_bytes(_PNG_BYTES)
svg = tmp_path / "icon.svg"
svg.write_text("<svg><rect/></svg>")
doc = tmp_path / "README.md"
doc.write_text("# Title\nbody")
return img, svg, doc
# ── pure helpers ──────────────────────────────────────────────────────────────
def test_pdf_routed_through_pypdf_not_readtext(tmp_path, monkeypatch):
# A PDF is binary; reading it as text yields garbage (the bug). It must be
# routed through the pypdf extractor, and the raw bytes must never reach the
# prompt.
pdf = tmp_path / "paper.pdf"
pdf.write_bytes(b"%PDF-1.4 RAWBINARYGARBAGE\x00\xff")
import graphify.detect as detect
monkeypatch.setattr(detect, "extract_pdf_text", lambda p: "EXTRACTED PDF TEXT")
out = llm._read_files([pdf], tmp_path)
assert "EXTRACTED PDF TEXT" in out
assert "RAWBINARYGARBAGE" not in out
def test_pdf_is_not_treated_as_vision_image(tmp_path):
pdf = tmp_path / "paper.pdf"
pdf.write_bytes(b"%PDF-1.4")
text_files, image_files = llm._partition_semantic_files([pdf])
assert text_files == [pdf] and image_files == []
def test_non_pdf_still_read_as_plain_text(tmp_path):
md = tmp_path / "a.md"
md.write_text("# hello")
assert "# hello" in llm._file_to_text(md)
def test_partition_splits_raster_from_text(tmp_path):
img, svg, doc = _make_corpus(tmp_path)
text_files, image_files = llm._partition_semantic_files([doc, img, svg])
assert image_files == [img]
# svg is XML markup, so it stays on the text side (read as source, not pixels)
assert set(text_files) == {doc, svg}
def test_build_image_refs_sets_rel_media_and_bytes(tmp_path):
img, _, _ = _make_corpus(tmp_path)
(ref,) = llm._build_image_refs([img], tmp_path)
assert ref.rel == "sub/diagram.png"
assert ref.media_type == "image/png"
assert ref.raw == _PNG_BYTES
assert ref.b64 # non-empty base64
assert ref.bedrock_format == "png"
def test_build_image_refs_drops_oversized(tmp_path, monkeypatch):
big = tmp_path / "big.jpg"
big.write_bytes(b"x" * 64)
monkeypatch.setattr(llm, "_MAX_IMAGE_BYTES", 8)
(ref,) = llm._build_image_refs([big], tmp_path)
assert ref.raw is None # too large -> reference node only, no pixels
assert ref.media_type == "image/jpeg"
def test_path_backend_skips_byte_read_and_size_cap(tmp_path, monkeypatch):
# Path-based backends (claude-cli) read the file themselves, so
# _build_image_refs(read_bytes=False) loads no bytes and applies no size cap.
big = tmp_path / "huge.png"
big.write_bytes(b"x" * 64)
monkeypatch.setattr(llm, "_MAX_IMAGE_BYTES", 8)
(ref,) = llm._build_image_refs([big], tmp_path, read_bytes=False)
assert ref.raw is None # never read
assert ref.rel == "huge.png" and ref.path.name == "huge.png" # path still usable
def test_claude_cli_passes_oversized_image_by_path(tmp_path, monkeypatch):
# An image over the inline base64 cap must still reach claude-cli by path —
# opus reads it via the Read tool, no size limit on that route.
big = tmp_path / "huge.png"
big.write_bytes(b"x" * 100)
monkeypatch.setattr(llm, "_MAX_IMAGE_BYTES", 8)
refs = llm._build_image_refs([big], tmp_path, read_bytes=False)
envelope = {"result": _NODE_JSON, "usage": {"output_tokens": 1}, "stop_reason": "end_turn"}
seen: dict = {}
def fake_run(args, **kw):
seen["input"] = kw.get("input", "")
return MagicMock(returncode=0, stdout=json.dumps(envelope), stderr="")
monkeypatch.setattr(llm, "_response_is_hollow", lambda r, p: False)
with patch("shutil.which", return_value="/fake/claude"), \
patch("subprocess.run", side_effect=fake_run):
llm._call_claude_cli("CORPUS", images=refs)
assert str(refs[0].path) in seen["input"]
def test_capability_flags(monkeypatch):
for b in ("claude", "claude-cli", "openai", "gemini", "bedrock", "kimi"):
assert llm._backend_supports_vision(b), b
assert not llm._backend_supports_vision("deepseek")
# ollama is opt-in via env (default model is text-only)
monkeypatch.delenv("GRAPHIFY_OLLAMA_VISION", raising=False)
assert not llm._backend_supports_vision("ollama")
monkeypatch.setenv("GRAPHIFY_OLLAMA_VISION", "1")
assert llm._backend_supports_vision("ollama")
def test_image_token_estimate_is_flat(tmp_path):
img, _, _ = _make_corpus(tmp_path)
assert llm._estimate_file_tokens(img) == llm._IMAGE_TOKEN_ESTIMATE
def test_chunk_packing_caps_images_per_chunk(tmp_path):
# Many images + a huge token budget must still cap images per chunk so a
# single request never exceeds provider image limits.
imgs = []
for i in range(llm._MAX_IMAGES_PER_CHUNK * 2 + 3):
p = tmp_path / f"img{i:03d}.png"
p.write_bytes(_PNG_BYTES)
imgs.append(p)
chunks = llm._pack_chunks_by_tokens(imgs, token_budget=10_000_000)
assert len(chunks) >= 3 # would be 1 chunk without the cap
for chunk in chunks:
n_imgs = sum(1 for p in chunk if llm._is_vision_image(p))
assert n_imgs <= llm._MAX_IMAGES_PER_CHUNK
# ── content builders ──────────────────────────────────────────────────────────
def test_anthropic_content_has_base64_block(tmp_path):
img, _, _ = _make_corpus(tmp_path)
refs = llm._build_image_refs([img], tmp_path)
content = llm._anthropic_content("CORPUS", refs)
assert isinstance(content, list)
assert content[0]["type"] == "image"
assert content[0]["source"] == {
"type": "base64", "media_type": "image/png", "data": refs[0].b64,
}
assert content[-1]["type"] == "text" and "CORPUS" in content[-1]["text"]
def test_openai_content_has_data_uri(tmp_path):
img, _, _ = _make_corpus(tmp_path)
refs = llm._build_image_refs([img], tmp_path)
content = llm._openai_content("CORPUS", refs)
assert content[0]["type"] == "text"
assert content[1]["type"] == "image_url"
assert content[1]["image_url"]["url"] == f"data:image/png;base64,{refs[0].b64}"
def test_bedrock_content_uses_raw_bytes(tmp_path):
img, _, _ = _make_corpus(tmp_path)
refs = llm._build_image_refs([img], tmp_path)
content = llm._bedrock_content("CORPUS", refs)
assert content[0]["image"]["format"] == "png"
# Converse takes raw bytes, NOT base64 (the SDK encodes on the wire)
assert content[0]["image"]["source"]["bytes"] == _PNG_BYTES
assert content[-1]["text"] and "CORPUS" in content[-1]["text"] # text block carries the corpus
def test_builders_fall_back_to_string_without_pixels(tmp_path):
img, _, _ = _make_corpus(tmp_path)
stripped = llm._strip_pixels(llm._build_image_refs([img], tmp_path))
# No pixels -> Anthropic/OpenAI render a plain string carrying the note
ac = llm._anthropic_content("CORPUS", stripped)
oc = llm._openai_content("CORPUS", stripped)
assert isinstance(ac, str) and "sub/diagram.png" in ac
assert isinstance(oc, str) and "sub/diagram.png" in oc
def test_no_images_is_byte_identical(tmp_path):
# With no image refs, the user content must be exactly the text blob.
assert llm._anthropic_content("PLAIN", []) == "PLAIN"
assert llm._openai_content("PLAIN", []) == "PLAIN"
# ── fake SDK modules ──────────────────────────────────────────────────────────
def _fake_anthropic(monkeypatch, captured):
class _Messages:
def create(self, **kw):
captured.update(kw)
return SimpleNamespace(
content=[SimpleNamespace(text=_NODE_JSON)],
usage=SimpleNamespace(input_tokens=5, output_tokens=7),
stop_reason="end_turn",
)
mod = types.ModuleType("anthropic")
mod.Anthropic = lambda **kw: SimpleNamespace(messages=_Messages())
monkeypatch.setitem(sys.modules, "anthropic", mod)
def _fake_openai(monkeypatch, captured):
class _Completions:
def create(self, **kw):
captured.update(kw)
return SimpleNamespace(
choices=[SimpleNamespace(
message=SimpleNamespace(content=_NODE_JSON), finish_reason="stop")],
usage=SimpleNamespace(prompt_tokens=3, completion_tokens=4),
)
mod = types.ModuleType("openai")
mod.OpenAI = lambda **kw: SimpleNamespace(chat=SimpleNamespace(completions=_Completions()))
monkeypatch.setitem(sys.modules, "openai", mod)
def _fake_boto3(monkeypatch, captured):
class _Client:
def converse(self, **kw):
captured.update(kw)
return {
"output": {"message": {"content": [{"text": _NODE_JSON}]}},
"usage": {"inputTokens": 1, "outputTokens": 2},
"stopReason": "end_turn",
}
boto3 = types.ModuleType("boto3")
boto3.Session = lambda **kw: SimpleNamespace(client=lambda svc: _Client())
monkeypatch.setitem(sys.modules, "boto3", boto3)
botocore = types.ModuleType("botocore")
exc = types.ModuleType("botocore.exceptions")
exc.ClientError = type("ClientError", (Exception,), {})
botocore.exceptions = exc
monkeypatch.setitem(sys.modules, "botocore", botocore)
monkeypatch.setitem(sys.modules, "botocore.exceptions", exc)
# ── backend payload shape (mocked) ────────────────────────────────────────────
def test_call_claude_sends_image_block(tmp_path, monkeypatch):
img, _, _ = _make_corpus(tmp_path)
refs = llm._build_image_refs([img], tmp_path)
captured: dict = {}
_fake_anthropic(monkeypatch, captured)
llm._call_claude("k", "claude-sonnet-4-6", "CORPUS", images=refs)
content = captured["messages"][0]["content"]
assert any(b.get("type") == "image" for b in content)
def test_call_openai_compat_sends_image_url(tmp_path, monkeypatch):
img, _, _ = _make_corpus(tmp_path)
refs = llm._build_image_refs([img], tmp_path)
captured: dict = {}
_fake_openai(monkeypatch, captured)
llm._call_openai_compat("http://x", "k", "gpt", "CORPUS", images=refs)
content = captured["messages"][1]["content"]
assert any(p.get("type") == "image_url" for p in content)
def test_call_openai_compat_text_only_without_images(monkeypatch):
captured: dict = {}
_fake_openai(monkeypatch, captured)
llm._call_openai_compat("http://x", "k", "gpt", "CORPUS", images=[])
assert captured["messages"][1]["content"] == "CORPUS"
def test_call_bedrock_sends_raw_image_bytes(tmp_path, monkeypatch):
img, _, _ = _make_corpus(tmp_path)
refs = llm._build_image_refs([img], tmp_path)
captured: dict = {}
_fake_boto3(monkeypatch, captured)
llm._call_bedrock("model", "CORPUS", images=refs)
content = captured["messages"][0]["content"]
img_block = next(b for b in content if "image" in b)
assert img_block["image"]["source"]["bytes"] == _PNG_BYTES
# ── CLI backends (mocked subprocess) ──────────────────────────────────────────
def test_claude_cli_adds_dir_and_read_instruction(tmp_path, monkeypatch):
img, _, _ = _make_corpus(tmp_path)
refs = llm._build_image_refs([img], tmp_path)
envelope = {"result": _NODE_JSON, "usage": {"output_tokens": 1}, "stop_reason": "end_turn"}
seen: dict = {}
def fake_run(args, **kw):
seen["args"] = args
seen["input"] = kw.get("input", "")
return MagicMock(returncode=0, stdout=json.dumps(envelope), stderr="")
monkeypatch.setattr(llm, "_response_is_hollow", lambda raw, parsed: False)
with patch("shutil.which", return_value="/fake/claude"), \
patch("subprocess.run", side_effect=fake_run):
llm._call_claude_cli("CORPUS", images=refs)
assert "--add-dir" in seen["args"]
assert str(refs[0].path.parent) in seen["args"]
# the prompt sent on stdin tells the model to Read the image path
assert "Read tool" in seen["input"] and str(refs[0].path) in seen["input"]
# ── dispatch-level vision gating ──────────────────────────────────────────────
def test_extract_files_direct_gates_pixels_by_capability(tmp_path, monkeypatch):
img, _, doc = _make_corpus(tmp_path)
captured: dict = {}
_fake_openai(monkeypatch, captured)
# vision backend (openai) -> content is a list carrying an image_url block
monkeypatch.setenv("OPENAI_API_KEY", "k")
llm.extract_files_direct([doc, img], backend="openai", root=tmp_path)
assert isinstance(captured["messages"][1]["content"], list)
# non-vision backend (deepseek) -> pixels stripped, content is a plain string
captured.clear()
monkeypatch.setenv("DEEPSEEK_API_KEY", "k")
llm.extract_files_direct([doc, img], backend="deepseek", root=tmp_path)
content = captured["messages"][1]["content"]
assert isinstance(content, str) and "sub/diagram.png" in content
+76 -9
View File
@@ -8,7 +8,8 @@ import pytest
PLATFORMS = {
"claude": (".claude/skills/graphify/SKILL.md",),
"codex": (".agents/skills/graphify/SKILL.md",),
"codebuddy": (".codebuddy/skills/graphify/SKILL.md",),
"codex": (".codex/skills/graphify/SKILL.md",),
"opencode": (".config/opencode/skills/graphify/SKILL.md",),
"kilo": (
".config/kilo/skills/graphify/SKILL.md",
@@ -39,9 +40,14 @@ def test_install_default_claude(tmp_path):
assert (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_codebuddy(tmp_path):
_install(tmp_path, "codebuddy")
assert (tmp_path / ".codebuddy" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_codex(tmp_path):
_install(tmp_path, "codex")
assert (tmp_path / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
assert (tmp_path / ".codex" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_opencode(tmp_path):
@@ -87,10 +93,10 @@ def test_install_project_codex_writes_skill_and_agents(tmp_path, monkeypatch):
monkeypatch.setattr(sys, "argv", ["graphify", "install", "--project", "--platform", "codex"])
with patch("graphify.__main__.Path.home", return_value=home):
main()
assert (project / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
assert (project / ".codex" / "skills" / "graphify" / "SKILL.md").exists()
assert (project / "AGENTS.md").exists()
assert (project / ".codex" / "hooks.json").exists()
assert not (home / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
assert not (home / ".codex" / "skills" / "graphify" / "SKILL.md").exists()
def test_claude_subcommand_project_install_and_uninstall_are_project_scoped(tmp_path, monkeypatch):
@@ -124,14 +130,14 @@ def test_codex_subcommand_project_install_and_uninstall_are_project_scoped(tmp_p
home = tmp_path / "home"
project = tmp_path / "project"
project.mkdir()
user_skill = home / ".agents" / "skills" / "graphify" / "SKILL.md"
user_skill = home / ".codex" / "skills" / "graphify" / "SKILL.md"
user_skill.parent.mkdir(parents=True)
user_skill.write_text("user skill")
monkeypatch.chdir(project)
with patch("graphify.__main__.Path.home", return_value=home):
monkeypatch.setattr(sys, "argv", ["graphify", "codex", "install", "--project"])
main()
assert (project / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
assert (project / ".codex" / "skills" / "graphify" / "SKILL.md").exists()
assert (project / "AGENTS.md").exists()
assert (project / ".codex" / "hooks.json").exists()
assert user_skill.exists()
@@ -140,7 +146,7 @@ def test_codex_subcommand_project_install_and_uninstall_are_project_scoped(tmp_p
main()
assert user_skill.exists()
assert not (project / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
assert not (project / ".codex" / "skills" / "graphify" / "SKILL.md").exists()
assert not (project / "AGENTS.md").exists()
hooks_path = project / ".codex" / "hooks.json"
assert hooks_path.exists()
@@ -334,12 +340,73 @@ def test_codex_install_does_not_write_claude_md(tmp_path):
assert not (tmp_path / ".claude" / "CLAUDE.md").exists()
# --- CodeBuddy CODEBUDDY.md + hook install/uninstall tests ---
def test_codebuddy_install_writes_codebuddy_md(tmp_path):
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
md = tmp_path / "CODEBUDDY.md"
assert md.exists()
assert "graphify-out/GRAPH_REPORT.md" in md.read_text()
def test_codebuddy_install_writes_hook(tmp_path):
import json as _json
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
settings = _json.loads((tmp_path / ".codebuddy" / "settings.json").read_text())
hooks = settings["hooks"]["PreToolUse"]
assert any("graphify" in str(h) for h in hooks)
def test_codebuddy_install_idempotent(tmp_path):
from graphify.__main__ import codebuddy_install
codebuddy_install(tmp_path)
codebuddy_install(tmp_path)
md = tmp_path / "CODEBUDDY.md"
assert md.read_text().count("## graphify") == 1
def test_codebuddy_install_merges_existing_codebuddy_md(tmp_path):
from graphify.__main__ import codebuddy_install
(tmp_path / "CODEBUDDY.md").write_text("# My project rules\n")
codebuddy_install(tmp_path)
content = (tmp_path / "CODEBUDDY.md").read_text()
assert "# My project rules" in content
assert "graphify-out/GRAPH_REPORT.md" in content
def test_codebuddy_uninstall_removes_section(tmp_path):
from graphify.__main__ import codebuddy_install, codebuddy_uninstall
codebuddy_install(tmp_path)
codebuddy_uninstall(tmp_path)
md = tmp_path / "CODEBUDDY.md"
assert not md.exists()
def test_codebuddy_uninstall_removes_hook(tmp_path):
import json as _json
from graphify.__main__ import codebuddy_install, codebuddy_uninstall
codebuddy_install(tmp_path)
codebuddy_uninstall(tmp_path)
settings_path = tmp_path / ".codebuddy" / "settings.json"
if settings_path.exists():
settings = _json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert not any("graphify" in str(h) for h in hooks)
def test_codebuddy_uninstall_noop_if_not_installed(tmp_path):
from graphify.__main__ import codebuddy_uninstall
codebuddy_uninstall(tmp_path) # should not raise
def test_uninstall_project_removes_project_skill_only(tmp_path, monkeypatch):
from graphify.__main__ import main
home = tmp_path / "home"
project = tmp_path / "project"
project.mkdir()
user_skill = home / ".agents" / "skills" / "graphify" / "SKILL.md"
user_skill = home / ".codex" / "skills" / "graphify" / "SKILL.md"
user_skill.parent.mkdir(parents=True)
user_skill.write_text("user skill")
monkeypatch.chdir(project)
@@ -349,7 +416,7 @@ def test_uninstall_project_removes_project_skill_only(tmp_path, monkeypatch):
monkeypatch.setattr(sys, "argv", ["graphify", "uninstall", "--project", "--platform", "codex"])
main()
assert user_skill.exists()
assert not (project / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
assert not (project / ".codex" / "skills" / "graphify" / "SKILL.md").exists()
assert not (project / "AGENTS.md").exists()
+39
View File
@@ -231,3 +231,42 @@ def test_kiro_install_upgrades_stale_steering(tmp_path, monkeypatch):
assert "read it before answering architecture questions" not in after
_assert_query_first(after, ".kiro/steering/graphify.md")
assert "inclusion: always" in after # frontmatter preserved
def test_kiro_install_ships_references_sidecar_and_version_stamp(tmp_path, monkeypatch):
"""_kiro_install routes through _copy_skill_file so the references/ sidecar
and .graphify_version stamp are written alongside SKILL.md (#1142).
Previously it used a bare write_text that bypassed the shared helper."""
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
refs_dir = Path(mainmod.__file__).parent / "skills" / "kiro" / "references"
if not refs_dir.exists():
pytest.skip("kiro references bundle not present in this checkout")
mainmod._kiro_install(tmp_path)
skill_dir = tmp_path / ".kiro" / "skills" / "graphify"
# SKILL.md present
assert (skill_dir / "SKILL.md").exists()
# references/ sidecar installed with at least one fragment
refs_dst = skill_dir / "references"
assert refs_dst.is_dir(), "references/ sidecar must be installed (#1142)"
assert any(refs_dst.iterdir()), "references/ must not be empty"
# .graphify_version stamp written
version_file = skill_dir / ".graphify_version"
assert version_file.exists(), ".graphify_version stamp must be written (#1142)"
assert version_file.read_text(encoding="utf-8") == mainmod.__version__
# no references.tmp leftover
assert not (skill_dir / "references.tmp").exists()
# steering file still written
assert (tmp_path / ".kiro" / "steering" / "graphify.md").exists()
# uninstall removes skill dir, version stamp, references/, and steering file
mainmod._kiro_uninstall(tmp_path)
assert not skill_dir.exists(), "uninstall must remove skill dir including references/ (#1142)"
assert not (tmp_path / ".kiro" / "steering" / "graphify.md").exists()
+76 -1
View File
@@ -8,7 +8,7 @@ from graphify.extract import (
extract_swift, extract_go, extract_julia, extract_js, extract_fortran,
extract_groovy, extract_sln, extract_csproj, extract_razor,
extract_dm, extract_dmi, extract_dmm, extract_dmf,
extract_powershell,
extract_powershell, extract_apex,
)
FIXTURES = Path(__file__).parent / "fixtures"
@@ -1553,3 +1553,78 @@ def test_razor_no_dangling_edges():
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids
# ---------------Salesforce Apex (.cls / .trigger)----------------------
def test_apex_class_extraction():
r = extract_apex(FIXTURES / "sample.cls")
labels = _labels(r)
assert "AccountService" in labels
def test_apex_enum_extraction():
r = extract_apex(FIXTURES / "sample.cls")
labels = _labels(r)
assert "AccountStatus" in labels
def test_apex_interface_extraction():
r = extract_apex(FIXTURES / "sample.cls")
labels = _labels(r)
assert "Notifiable" in labels
def test_apex_method_extraction():
r = extract_apex(FIXTURES / "sample.cls")
labels = _labels(r)
assert any("getAccounts" in l for l in labels)
assert any("updateAccountsAsync" in l for l in labels)
assert any("createAccounts" in l for l in labels)
assert any("deleteOldAccounts" in l for l in labels)
def test_apex_contains_and_method_relations():
r = extract_apex(FIXTURES / "sample.cls")
relations = _relations(r)
assert "contains" in relations
assert "method" in relations
def test_apex_soql_uses_edge():
r = extract_apex(FIXTURES / "sample.cls")
relations = _relations(r)
assert "uses" in relations
labels = _labels(r)
assert "Account" in labels
def test_apex_dml_uses_edge():
r = extract_apex(FIXTURES / "sample.cls")
dml_labels = {n["label"] for n in r["nodes"] if n["label"] in ("insert", "update", "delete", "upsert")}
assert len(dml_labels) > 0
def test_apex_file_node_present():
r = extract_apex(FIXTURES / "sample.cls")
labels = _labels(r)
assert "sample.cls" in labels
def test_apex_trigger_extraction():
r = extract_apex(FIXTURES / "sample.trigger")
labels = _labels(r)
assert "sample.trigger" in labels
assert "AccountTrigger" in labels
def test_apex_trigger_uses_sobject():
r = extract_apex(FIXTURES / "sample.trigger")
relations = _relations(r)
assert "uses" in relations
labels = _labels(r)
assert "Account" in labels
def test_apex_missing_file_returns_empty():
r = extract_apex(Path("nonexistent.cls"))
assert r["nodes"] == []
assert r["edges"] == []
def test_apex_no_dangling_edges():
for fixture in ("sample.cls", "sample.trigger"):
r = extract_apex(FIXTURES / fixture)
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"dangling source in {fixture}: {e}"
assert e["target"] in node_ids, f"dangling target in {fixture}: {e}"
+80
View File
@@ -15,6 +15,9 @@ def _clear_backend_env(monkeypatch):
"MOONSHOT_API_KEY",
"ANTHROPIC_API_KEY",
"OPENAI_API_KEY",
"DEEPSEEK_API_KEY",
"AZURE_OPENAI_API_KEY",
"AZURE_OPENAI_ENDPOINT",
):
monkeypatch.delenv(env_key, raising=False)
@@ -513,3 +516,80 @@ def test_adaptive_retry_bisects_on_hollow_ollama_response(tmp_path):
"full chunk came back hollow"
)
assert calls["n"] == 3 # 1 hollow + 2 successful halves
# ---------------------------------------------------------------------------
# Azure backend
# ---------------------------------------------------------------------------
def _install_fake_azure_openai(monkeypatch, fake_resp):
"""Inject a stub openai module with AzureOpenAI so _call_azure and
_azure_client can run without the real SDK installed."""
import sys
import types
captured: dict = {}
class _FakeAzureOpenAI:
def __init__(self, *_, **kwargs):
captured["init_kwargs"] = kwargs
self.chat = self
self.completions = self
def create(self, **kwargs):
captured["create_kwargs"] = kwargs
return fake_resp
fake_module = types.ModuleType("openai")
fake_module.AzureOpenAI = _FakeAzureOpenAI
monkeypatch.setitem(sys.modules, "openai", fake_module)
return captured
def test_call_azure_uses_correct_client_params_and_max_completion_tokens(monkeypatch):
monkeypatch.setenv("AZURE_OPENAI_API_VERSION", "2024-08-01-preview")
monkeypatch.delenv("GRAPHIFY_API_TIMEOUT", raising=False)
fake_resp = _fake_openai_response(
'{"nodes":[{"id":"a"}],"edges":[],"hyperedges":[]}',
finish_reason="stop",
prompt_tokens=100,
completion_tokens=50,
)
captured = _install_fake_azure_openai(monkeypatch, fake_resp)
result = llm._call_azure(
api_key="test-key",
endpoint="https://my-resource.openai.azure.com/",
model="gpt-4o",
user_message="test",
)
assert captured["init_kwargs"].get("azure_endpoint") == "https://my-resource.openai.azure.com/"
assert captured["init_kwargs"].get("api_version") == "2024-08-01-preview"
assert "max_completion_tokens" in captured["create_kwargs"], "must use max_completion_tokens not max_tokens"
assert "max_tokens" not in captured["create_kwargs"], "deprecated max_tokens must not be sent"
assert result["nodes"] == [{"id": "a"}]
def test_detect_backend_returns_azure_when_both_vars_set(monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("AZURE_OPENAI_API_KEY", "azure-key")
monkeypatch.setenv("AZURE_OPENAI_ENDPOINT", "https://my-resource.openai.azure.com/")
assert llm.detect_backend() == "azure"
assert llm._get_backend_api_key("azure") == "azure-key"
def test_detect_backend_azure_requires_endpoint_not_just_key(monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("AZURE_OPENAI_API_KEY", "azure-key")
# AZURE_OPENAI_ENDPOINT already cleared by _clear_backend_env
assert llm.detect_backend() != "azure"
def test_estimate_cost_azure_no_keyerror():
cost = llm.estimate_cost("azure", 1_000_000, 500_000)
assert cost == pytest.approx(2.50 + 5.00) # 1M in * $2.50/M + 0.5M out * $10.00/M
+275
View File
@@ -0,0 +1,275 @@
import sys
from unittest.mock import MagicMock, patch
import pytest
from pathlib import Path
from graphify.pg_introspect import introspect_postgres
from graphify.validate import validate_extraction
# ---------------------------------------------------------------------------
# Shared mock infrastructure
# ---------------------------------------------------------------------------
def _make_mock_psycopg(tables, views, routines, fks,
host="myhost", dbname="mydb",
connect_raises=None):
"""Return a mock psycopg module wired to the provided catalog data.
``routines`` rows must be 5-tuples: (schema, name, rtype, body, ext_lang).
``fks`` rows must be 7-tuples:
(constraint_name, t_schema, t_name, [cols], r_schema, r_name, [r_cols])
``connect_raises``, if set, is an exception *instance* raised by connect().
"""
class MockCursor:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def execute(self, query, params=None):
self.query = query
def fetchall(self):
q = self.query.strip().lower()
if "information_schema.tables" in q:
return tables
elif "information_schema.views" in q:
return views
elif "information_schema.routines" in q:
return routines
elif "information_schema.referential_constraints" in q:
return fks
return []
class MockConnection:
def execute(self, query):
pass
def cursor(self):
return MockCursor()
def close(self):
pass
@property
def info(self):
info_mock = MagicMock()
info_mock.dsn = f"host={host} dbname={dbname} user=myuser password=secret"
return info_mock
mock_psycopg = MagicMock()
if connect_raises is not None:
mock_psycopg.connect.side_effect = connect_raises
# Make the exception type available as an attribute so the module can
# reference psycopg.OperationalError in the except clause.
mock_psycopg.OperationalError = type(connect_raises)
else:
mock_psycopg.connect.return_value = MockConnection()
mock_psycopg.OperationalError = Exception # unused path but must exist
mock_psycopg.conninfo.conninfo_to_dict.return_value = {
"host": host,
"dbname": dbname,
}
return mock_psycopg
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _q(schema: str, name: str) -> str:
"""Return the label form that tree-sitter produces for a quoted identifier.
pg_introspect emits CREATE TABLE "schema"."name" — tree-sitter reads the
object_reference text verbatim (quotes included), so the node label is
'"schema"."name"', not 'schema.name'.
"""
return f'"{schema}"."{name}"'
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
def test_pg_introspect_success():
"""Baseline: tables, views, routines, and a single-column FK all survive."""
mock_tables = [
("public", "users", "BASE TABLE"),
("public", "orders", "BASE TABLE"),
]
mock_views = [
("public", "active_users", "SELECT * FROM public.users WHERE active = true"),
]
# 5-tuple: schema, name, rtype, body, ext_lang
mock_routines = [
("public", "calculate_total", "FUNCTION", "SELECT 42;", "SQL"),
("public", "do_nothing", "PROCEDURE", None, "PLPGSQL"),
]
# 7-tuple: constraint_name, t_schema, t_name, cols[], r_schema, r_name, r_cols[]
mock_fks = [
("fk_orders_user_id", "public", "orders", ["user_id"], "public", "users", ["id"]),
]
mock_psycopg = _make_mock_psycopg(mock_tables, mock_views, mock_routines, mock_fks)
with patch.dict("sys.modules", {"psycopg": mock_psycopg}):
res = introspect_postgres("postgresql://myuser:mypassword@myhost/mydb")
# 1. validate_extraction must pass
errors = validate_extraction(res)
assert errors == [], f"Validation errors: {errors}"
# 2. source_file must be the sanitized virtual path (no credentials)
expected_source = "postgresql:/myhost/mydb"
for node in res["nodes"]:
assert node["source_file"] == expected_source
for edge in res["edges"]:
assert edge["source_file"] == expected_source
# 3. Expected node labels. pg_introspect double-quotes identifiers in DDL,
# so tree-sitter returns the raw quoted text as the object_reference.
node_labels = {n["label"] for n in res["nodes"]}
assert _q("public", "users") in node_labels, f"users missing; got {node_labels}"
assert _q("public", "orders") in node_labels, f"orders missing; got {node_labels}"
# Views keep the schema-qualified label (quoted schema, unquoted body)
assert _q("public", "active_users") in node_labels, f"active_users missing; got {node_labels}"
# Functions: label is "<quoted-sig>()"
assert f'{_q("public", "calculate_total")}()' in node_labels, f"calculate_total() missing; got {node_labels}"
assert f'{_q("public", "do_nothing")}()' in node_labels, f"do_nothing() missing; got {node_labels}"
# 4. File node (label = dbname)
file_nodes = [n for n in res["nodes"] if n["file_type"] == "code" and n["label"] == "mydb"]
assert len(file_nodes) == 1
# 5. FK references edge: orders → users, exactly once
users_nid = next(n["id"] for n in res["nodes"] if n["label"] == _q("public", "users"))
orders_nid = next(n["id"] for n in res["nodes"] if n["label"] == _q("public", "orders"))
ref_edges = [
e for e in res["edges"]
if e["source"] == orders_nid and e["target"] == users_nid and e["relation"] == "references"
]
assert len(ref_edges) == 1, f"Expected exactly 1 references edge, got {len(ref_edges)}"
def test_pg_introspect_quoted_identifiers():
"""Reserved-word and special-character table names must survive DDL round-trip.
'order' is a SQL reserved word; 'user-data' contains a hyphen — both would
produce invalid DDL without quoting, causing tree-sitter to silently drop
those tables and any FK touching them.
"""
mock_tables = [
("public", "order", "BASE TABLE"), # reserved word
("public", "user-data", "BASE TABLE"), # hyphen
]
mock_views = []
mock_routines = []
# FK: user-data.owner_id → order.id
mock_fks = [
("fk_userdata_order", "public", "user-data", ["owner_id"], "public", "order", ["id"]),
]
mock_psycopg = _make_mock_psycopg(mock_tables, mock_views, mock_routines, mock_fks)
with patch.dict("sys.modules", {"psycopg": mock_psycopg}):
res = introspect_postgres("postgresql://myuser:secret@myhost/mydb")
errors = validate_extraction(res)
assert errors == [], f"Validation errors: {errors}"
node_labels = {n["label"] for n in res["nodes"]}
# Both tables must appear as nodes (quoted form expected from tree-sitter)
assert _q("public", "order") in node_labels, \
f"'order' table missing; labels={node_labels}"
assert _q("public", "user-data") in node_labels, \
f"'user-data' table missing; labels={node_labels}"
# FK references edge must exist
ref_edges = [e for e in res["edges"] if e["relation"] == "references"]
assert len(ref_edges) >= 1, "Expected at least one references edge for the FK"
def test_pg_introspect_composite_fk():
"""A 2-column composite FK must produce exactly ONE references edge, not two.
The old code emitted one ADD CONSTRAINT per row of the FK query (one row
per key column), causing duplicate edges for composite keys.
"""
mock_tables = [
("public", "products", "BASE TABLE"),
("public", "order_items", "BASE TABLE"),
]
mock_views = []
mock_routines = []
# Single composite FK: order_items(order_id, product_id) → products(order_id, product_id)
mock_fks = [
(
"fk_order_items_composite",
"public", "order_items",
["order_id", "product_id"],
"public", "products",
["order_id", "product_id"],
),
]
mock_psycopg = _make_mock_psycopg(mock_tables, mock_views, mock_routines, mock_fks)
with patch.dict("sys.modules", {"psycopg": mock_psycopg}):
res = introspect_postgres("postgresql://myuser:secret@myhost/mydb")
errors = validate_extraction(res)
assert errors == [], f"Validation errors: {errors}"
products_nid = next(
n["id"] for n in res["nodes"] if n["label"] == _q("public", "products")
)
order_items_nid = next(
n["id"] for n in res["nodes"] if n["label"] == _q("public", "order_items")
)
ref_edges = [
e for e in res["edges"]
if e["source"] == order_items_nid
and e["target"] == products_nid
and e["relation"] == "references"
]
assert len(ref_edges) == 1, (
f"Expected exactly 1 references edge for composite FK, got {len(ref_edges)}"
)
def test_pg_introspect_connection_error():
"""A psycopg.OperationalError must be re-raised as ConnectionError with a
sanitized message (no DSN/credentials) and no stack-trace noise."""
class FakeOperationalError(Exception):
pass
raw_error = FakeOperationalError(
'connection to server at "myhost" (127.0.0.1), port 5432 failed: '
'FATAL: password authentication failed for user "myuser"\n'
"DETAIL: Connection matched pg_hba.conf line 1: …"
)
mock_psycopg = _make_mock_psycopg([], [], [], [], connect_raises=raw_error)
with patch.dict("sys.modules", {"psycopg": mock_psycopg}):
with pytest.raises(ConnectionError) as exc_info:
introspect_postgres("postgresql://myuser:secret@myhost/mydb")
msg = str(exc_info.value)
assert "could not connect to PostgreSQL" in msg
# Credentials must not appear in the surfaced message
assert "secret" not in msg
# Only the first line of the OperationalError should be present (no DETAIL)
assert "DETAIL" not in msg
def test_pg_introspect_import_error():
"""If psycopg is missing, introspect_postgres raises ImportError."""
with patch.dict("sys.modules", {"psycopg": None}):
with pytest.raises(ImportError, match="psycopg is required"):
introspect_postgres("postgresql://localhost/db")
+178
View File
@@ -0,0 +1,178 @@
"""Tests for graphify.querylog."""
import json
import os
import pytest
from pathlib import Path
from graphify.querylog import log_query, nodes_from_result
# ---------------------------------------------------------------------------
# nodes_from_result
# ---------------------------------------------------------------------------
def test_nodes_from_result_parses_header():
result = "Traversal: BFS depth=2 | Start: ['foo'] | 7 nodes found\n\nNODE foo"
assert nodes_from_result(result) == 7
def test_nodes_from_result_singular():
assert nodes_from_result("1 node found") == 1
def test_nodes_from_result_missing():
assert nodes_from_result("no match here") is None
def test_nodes_from_result_empty():
assert nodes_from_result("") is None
# ---------------------------------------------------------------------------
# log_query — basic write
# ---------------------------------------------------------------------------
def test_log_query_writes_jsonl(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
log_query(kind="query", question="what is X", corpus="/some/graph.json",
result="3 nodes found\nNODE a", duration_ms=12.5, mode="bfs", depth=2)
lines = log_file.read_text().splitlines()
assert len(lines) == 1
rec = json.loads(lines[0])
assert rec["kind"] == "query"
assert rec["question"] == "what is X"
assert rec["corpus"] == "/some/graph.json"
assert rec["nodes_returned"] == 3
assert rec["result_chars"] > 0
assert rec["duration_ms"] == pytest.approx(12.5, abs=0.01)
assert rec["mode"] == "bfs"
assert "ts" in rec
def test_log_query_appends(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
log_query(kind="query", question="q1", corpus="/g.json")
log_query(kind="query", question="q2", corpus="/g.json")
lines = log_file.read_text().splitlines()
assert len(lines) == 2
assert json.loads(lines[0])["question"] == "q1"
assert json.loads(lines[1])["question"] == "q2"
# ---------------------------------------------------------------------------
# opt-out / opt-in
# ---------------------------------------------------------------------------
def test_disable_env(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.setenv("GRAPHIFY_QUERY_LOG_DISABLE", "1")
log_query(kind="query", question="q", corpus="/g.json")
assert not log_file.exists()
def test_disable_env_true(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.setenv("GRAPHIFY_QUERY_LOG_DISABLE", "true")
log_query(kind="query", question="q", corpus="/g.json")
assert not log_file.exists()
def test_responses_not_logged_by_default(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_RESPONSES", raising=False)
log_query(kind="query", question="q", corpus="/g.json", result="NODE foo")
rec = json.loads(log_file.read_text())
assert "response" not in rec
def test_responses_optin(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.setenv("GRAPHIFY_QUERY_LOG_RESPONSES", "1")
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
log_query(kind="query", question="q", corpus="/g.json", result="NODE foo bar")
rec = json.loads(log_file.read_text())
assert rec["response"] == "NODE foo bar"
# ---------------------------------------------------------------------------
# robustness — never raises
# ---------------------------------------------------------------------------
def test_log_never_raises(tmp_path, monkeypatch):
# Point at a directory — open() for append will fail
bad_path = tmp_path / "is_a_dir"
bad_path.mkdir()
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(bad_path))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
# Must not raise
log_query(kind="query", question="q", corpus="/g.json")
def test_log_creates_parent_dirs(tmp_path, monkeypatch):
log_file = tmp_path / "deep" / "nested" / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
log_query(kind="query", question="q", corpus="/g.json")
assert log_file.exists()
# ---------------------------------------------------------------------------
# field coverage
# ---------------------------------------------------------------------------
def test_nodes_returned_inferred_from_result(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
log_query(kind="query", question="q", corpus="/g.json",
result="5 nodes found\nNODE a\nNODE b")
rec = json.loads(log_file.read_text())
assert rec["nodes_returned"] == 5
def test_explicit_nodes_returned_takes_precedence(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
log_query(kind="path", question="A -> B", corpus="/g.json", nodes_returned=3)
rec = json.loads(log_file.read_text())
assert rec["nodes_returned"] == 3
def test_kind_mcp_query(tmp_path, monkeypatch):
log_file = tmp_path / "q.log"
monkeypatch.setenv("GRAPHIFY_QUERY_LOG", str(log_file))
monkeypatch.delenv("GRAPHIFY_QUERY_LOG_DISABLE", raising=False)
log_query(kind="mcp_query", question="q", corpus="/g.json")
rec = json.loads(log_file.read_text())
assert rec["kind"] == "mcp_query"
+31
View File
@@ -87,6 +87,37 @@ def test_score_nodes_ignores_trailing_punctuation():
assert scored[0][1] == "n1"
def test_score_nodes_multiword_exact_label_outranks_superset():
"""A multi-word query equal to a whole label must resolve uniquely.
Regression for the `graphify path` "No path found" bug: every node sharing
the query's token set scored identically (no single token equals a
multi-word label, so the per-token exact tier never fired), the tie broke by
arbitrary node-id sort, and a wrong/disconnected endpoint was chosen. The
full-query tier in _score_nodes must make the exact label win strictly.
"""
G = nx.Graph()
# Reproduce the real graph: norm_label keeps punctuation (strip_diacritics +
# lower, NOT tokenized), so the ':' survives. A tokenized query can never
# equal that, which is exactly why the first-cut fix was a no-op for
# punctuated labels. The exact node must still win via the label's tokenized
# form.
def _add(nid, label, src):
G.add_node(nid, label=label, norm_label=label.lower(),
source_file=src, community=0)
_add("exact", "UOCE: Dehumidifier Driver", "uoce_dehumidifier.yaml")
_add("super", "UOCE: Dehumidifier Driver State Machine", "uoce_dehumidifier.yaml")
_add("decoy", "Dehumidifier Driver Helper", "uoce_dehumidifier.yaml")
# CLI resolves endpoints as [t.lower() for t in label.split()].
scored = _score_nodes(G, [t.lower() for t in "UOCE: Dehumidifier Driver".split()])
# Resolves uniquely to the exact label, strictly ahead of the superset.
assert scored[0][1] == "exact"
assert scored[0][0] > scored[1][0], "exact label must strictly outrank superset/token-bag matches"
def test_find_node_ignores_trailing_punctuation():
G = _make_graph()
assert _find_node(G, "extract?") == ["n1"]
+232
View File
@@ -0,0 +1,232 @@
"""Tests for the Streamable HTTP transport on the MCP server (issue #1143).
These exercise the ASGI wiring in-process (no uvicorn, no real socket) via
Starlette's TestClient, so they stay fast and offline. The stdio path is
unchanged and covered elsewhere.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
pytest.importorskip("mcp")
pytest.importorskip("starlette")
from starlette.testclient import TestClient # noqa: E402
from graphify import serve as serve_mod # noqa: E402
SAMPLE_GRAPH = {
"directed": True,
"nodes": [
{"id": "a", "label": "Alpha", "community": 0},
{"id": "b", "label": "Beta", "community": 0},
],
"edges": [
{"source": "a", "target": "b", "relation": "calls", "confidence": "EXTRACTED"},
],
}
_INIT_BODY = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": {"name": "test", "version": "0"},
},
}
_MCP_HEADERS = {
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
}
def _graph_file(tmp_path: Path) -> str:
p = tmp_path / "graph.json"
p.write_text(json.dumps(SAMPLE_GRAPH), encoding="utf-8")
return str(p)
def _client(app) -> TestClient:
# Default host is 127.0.0.1, so the DNS-rebinding guard only accepts that
# Host header (TestClient otherwise sends the disallowed "testserver").
return TestClient(app, base_url="http://127.0.0.1")
def test_app_builds_and_initialize_succeeds(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), json_response=True)
with _client(app) as client:
resp = client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY)
assert resp.status_code == 200
# json_response=True returns a single JSON-RPC envelope.
payload = resp.json()
assert payload["jsonrpc"] == "2.0"
assert payload["result"]["serverInfo"]["name"] == "graphify"
def test_unknown_path_is_404(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), json_response=True)
with _client(app) as client:
resp = client.post("/nope", headers=_MCP_HEADERS, json=_INIT_BODY)
assert resp.status_code == 404
def test_api_key_missing_is_401(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), api_key="s3cret", json_response=True)
with _client(app) as client:
resp = client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY)
assert resp.status_code == 401
assert resp.json()["error"] == "unauthorized"
def test_api_key_wrong_is_401(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), api_key="s3cret", json_response=True)
with _client(app) as client:
resp = client.post(
"/mcp",
headers={**_MCP_HEADERS, "Authorization": "Bearer nope"},
json=_INIT_BODY,
)
assert resp.status_code == 401
def test_api_key_bearer_ok(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), api_key="s3cret", json_response=True)
with _client(app) as client:
resp = client.post(
"/mcp",
headers={**_MCP_HEADERS, "Authorization": "Bearer s3cret"},
json=_INIT_BODY,
)
assert resp.status_code == 200
assert resp.json()["result"]["serverInfo"]["name"] == "graphify"
def test_api_key_x_api_key_header_ok(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), api_key="s3cret", json_response=True)
with _client(app) as client:
resp = client.post(
"/mcp",
headers={**_MCP_HEADERS, "X-API-Key": "s3cret"},
json=_INIT_BODY,
)
assert resp.status_code == 200
def test_blank_api_key_means_no_auth(tmp_path):
# An empty/whitespace key must normalize to "no auth", not a key of "".
app = serve_mod._build_http_app(_graph_file(tmp_path), api_key=" ", json_response=True)
with _client(app) as client:
resp = client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY)
assert resp.status_code == 200
def test_api_key_bearer_scheme_case_insensitive(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), api_key="s3cret", json_response=True)
with _client(app) as client:
resp = client.post(
"/mcp",
headers={**_MCP_HEADERS, "Authorization": "bearer s3cret"},
json=_INIT_BODY,
)
assert resp.status_code == 200
def test_custom_mount_path(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), path="/graph", json_response=True)
with _client(app) as client:
ok = client.post("/graph", headers=_MCP_HEADERS, json=_INIT_BODY)
assert ok.status_code == 200
missing = client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY)
assert missing.status_code == 404
def test_tools_list_over_http(tmp_path):
"""A full initialize -> tools/list round trip works over the HTTP transport."""
app = serve_mod._build_http_app(_graph_file(tmp_path), json_response=True)
with _client(app) as client:
init = client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY)
assert init.status_code == 200
session_id = init.headers.get("mcp-session-id")
assert session_id, "stateful transport should return a session id"
notify_headers = {**_MCP_HEADERS, "mcp-session-id": session_id}
client.post(
"/mcp",
headers=notify_headers,
json={"jsonrpc": "2.0", "method": "notifications/initialized"},
)
resp = client.post(
"/mcp",
headers=notify_headers,
json={"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}},
)
assert resp.status_code == 200
names = {t["name"] for t in resp.json()["result"]["tools"]}
assert {"query_graph", "get_node", "graph_stats"} <= names
def test_stateless_mode_initialize(tmp_path):
app = serve_mod._build_http_app(_graph_file(tmp_path), stateless=True, json_response=True)
with _client(app) as client:
resp = client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY)
assert resp.status_code == 200
def test_stateless_with_timeout_does_not_raise(tmp_path):
# session_timeout must be forced to None in stateless mode (the SDK raises
# RuntimeError otherwise). Building + a request should just work.
app = serve_mod._build_http_app(
_graph_file(tmp_path), stateless=True, session_timeout=3600, json_response=True
)
with _client(app) as client:
assert client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY).status_code == 200
def test_session_timeout_zero_disables(tmp_path):
# 0 / non-positive must disable reaping without tripping the SDK's validation.
app = serve_mod._build_http_app(_graph_file(tmp_path), session_timeout=0, json_response=True)
with _client(app) as client:
assert client.post("/mcp", headers=_MCP_HEADERS, json=_INIT_BODY).status_code == 200
# --- CLI argument parsing -------------------------------------------------
def test_cli_defaults_to_stdio(monkeypatch):
calls = {}
monkeypatch.setattr(serve_mod, "serve", lambda gp: calls.setdefault("stdio", gp))
monkeypatch.setattr(
serve_mod, "serve_http", lambda *a, **k: calls.setdefault("http", (a, k))
)
serve_mod._main(["graphify-out/graph.json"])
assert calls.get("stdio") == "graphify-out/graph.json"
assert "http" not in calls
def test_cli_http_passes_flags(monkeypatch):
captured = {}
monkeypatch.setattr(serve_mod, "serve", lambda gp: captured.setdefault("stdio", gp))
monkeypatch.setattr(
serve_mod, "serve_http", lambda gp, **k: captured.update(gp=gp, **k)
)
serve_mod._main([
"g.json", "--transport", "http", "--host", "0.0.0.0",
"--port", "9000", "--api-key", "k", "--stateless",
])
assert captured["gp"] == "g.json"
assert captured["host"] == "0.0.0.0"
assert captured["port"] == 9000
assert captured["api_key"] == "k"
assert captured["stateless"] is True
def test_cli_api_key_from_env(monkeypatch):
captured = {}
monkeypatch.setenv("GRAPHIFY_API_KEY", "from-env")
monkeypatch.setattr(serve_mod, "serve_http", lambda gp, **k: captured.update(**k))
serve_mod._main(["g.json", "--transport", "http"])
assert captured["api_key"] == "from-env"
+17 -9
View File
@@ -455,12 +455,13 @@ def test_monolith_roundtrip_passes_for_aider_and_devin():
assert problems == [], f"[{key}]\n" + "\n".join(problems)
def test_monoliths_change_only_the_enum_and_the_description():
"""The rendered monolith differs from v8 on exactly the enum + description lines.
def test_monoliths_change_only_the_enum_description_and_chunk_cleanup():
"""The rendered monolith differs from v8 on exactly the allowed lines.
Two changes are now in play for the monoliths: the file_type enum unified to
the six-value superset (the prose guidance line + the schema line) and the
frontmatter description unified across all platforms. Nothing else may differ.
Three changes are now in play for the monoliths: the file_type enum unified to
the six-value superset (the prose guidance line + the schema line), the
frontmatter description unified across all platforms, and the shell-agnostic
chunk-cleanup rewrite (#1172). Nothing else may differ.
"""
platforms = gen.load_platforms()
for key in ("aider", "devin"):
@@ -468,11 +469,12 @@ def test_monoliths_change_only_the_enum_and_the_description():
original = gen._normalise(gen._git_show(platforms[key].roundtrip_ref)).splitlines()
assert len(rendered) == len(original), f"[{key}] line count changed"
diff_idx = [i for i, (r, o) in enumerate(zip(rendered, original)) if r != o]
# Exactly three lines change: the prose enum guidance, the schema line,
# and the frontmatter description.
assert len(diff_idx) == 3, f"[{key}] expected 3 changed lines, got {len(diff_idx)}"
# Exactly four lines change: the prose enum guidance, the schema line,
# the frontmatter description, and the chunk-cleanup rewrite.
assert len(diff_idx) == 4, f"[{key}] expected 4 changed lines, got {len(diff_idx)}"
enum_changes = 0
desc_changes = 0
cleanup_changes = 0
for i in diff_idx:
line = rendered[i]
if gen.ENUM_VALUES in line or gen.ENUM_PROSE in line:
@@ -482,12 +484,18 @@ def test_monoliths_change_only_the_enum_and_the_description():
assert UNIFIED_DESCRIPTION in line, (
f"[{key}] description line is not the unified text: {line!r}"
)
elif gen._is_chunk_cleanup_line(line):
cleanup_changes += 1
# The unmatched-glob abort is fixed: the rm no longer carries the
# bare chunk glob, and a find ... -delete sweeps the chunks.
assert ".graphify_chunk_*.json" not in line.split("find", 1)[0]
else:
raise AssertionError(
f"[{key}] changed line {i} is neither enum nor description: {line!r}"
f"[{key}] changed line {i} is none of enum/description/cleanup: {line!r}"
)
assert enum_changes == 2, f"[{key}] expected 2 enum line changes, got {enum_changes}"
assert desc_changes == 1, f"[{key}] expected 1 description change, got {desc_changes}"
assert cleanup_changes == 1, f"[{key}] expected 1 cleanup change, got {cleanup_changes}"
# The six-value superset replaced the five-value enum in both files.
assert any(gen.ENUM_VALUES in line for line in rendered)
+158
View File
@@ -0,0 +1,158 @@
"""Tests for the Terraform/HCL extractor (graphify/extract.py, issue #187)."""
from __future__ import annotations
from pathlib import Path
from graphify.build import build_from_json
from graphify.extract import extract_terraform
def _write(tmp_path: Path, name: str, body: str) -> Path:
p = tmp_path / name
p.write_text(body, encoding="utf-8")
return p
def _labels(r) -> list[str]:
return [n["label"] for n in r["nodes"]]
def _rel_pairs(r, relation: str) -> set[tuple[str, str]]:
lab = {n["id"]: n["label"] for n in r["nodes"]}
return {
(lab.get(e["source"], e["source"]), lab.get(e["target"], e["target"]))
for e in r["edges"]
if e["relation"] == relation
}
SAMPLE = """\
# leading comment so the body is not children[0]
terraform {
required_providers { azurerm = { source = "hashicorp/azurerm" } }
}
variable "region" { default = "us-east-1" }
provider "aws" { region = var.region }
data "aws_ami" "ubuntu" { most_recent = true }
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
subnet_id = var.region
depends_on = [aws_security_group.sg]
}
resource "aws_security_group" "sg" { name = "sg" }
module "vpc" {
source = "./modules/vpc"
cidr = local.cidr
}
locals { cidr = "10.0.0.0/16" }
output "ip" { value = aws_instance.web.private_ip }
"""
def test_no_error_and_all_block_types_become_nodes(tmp_path):
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
assert r.get("error") is None
labels = set(_labels(r))
# one node per block type (the terraform{} settings block is intentionally skipped)
for expected in (
"var.region",
"provider.aws",
"data.aws_ami.ubuntu",
"aws_instance.web",
"aws_security_group.sg",
"module.vpc",
"local.cidr",
"output.ip",
):
assert expected in labels, f"missing node {expected!r}"
def test_reference_edges(tmp_path):
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
refs = _rel_pairs(r, "references")
assert ("provider.aws", "var.region") in refs
assert ("aws_instance.web", "data.aws_ami.ubuntu") in refs
assert ("aws_instance.web", "var.region") in refs
assert ("module.vpc", "local.cidr") in refs
assert ("output.ip", "aws_instance.web") in refs
def test_depends_on_edge(tmp_path):
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
assert ("aws_instance.web", "aws_security_group.sg") in _rel_pairs(r, "depends_on")
def test_file_contains_blocks(tmp_path):
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
contains = _rel_pairs(r, "contains")
assert ("main.tf", "aws_instance.web") in contains
assert ("main.tf", "var.region") in contains
def test_meta_heads_not_emitted(tmp_path):
# count.index / each.key / self.* / path.module are builtins, not references.
body = """\
resource "aws_instance" "web" {
count = 2
name = "web-${count.index}"
tags = each.value
dir = path.module
}
"""
r = extract_terraform(_write(tmp_path, "main.tf", body))
targets = {t for _, t in _rel_pairs(r, "references")}
assert not any(t.startswith(("count", "each", "path")) for t in targets)
def test_cross_file_references_resolve_after_merge(tmp_path):
# A resource defined in one file is referenced from another in the same
# directory; directory-scoped IDs must let the edge resolve at build time.
defn = """\
resource "azurerm_resource_group" "main" { name = "rg" }
"""
user = """\
resource "azurerm_network_interface" "nic" {
resource_group_name = azurerm_resource_group.main.name
}
"""
r_defn = extract_terraform(_write(tmp_path, "main.tf", defn))
r_user = extract_terraform(_write(tmp_path, "nic.tf", user))
# The cross-file edge target id equals the definition's node id.
rg_id = next(n["id"] for n in r_defn["nodes"] if n["label"] == "azurerm_resource_group.main")
nic_ref_targets = {e["target"] for e in r_user["edges"] if e["relation"] == "references"}
assert rg_id in nic_ref_targets
# And it survives a real merge: the edge is present (not dropped as dangling).
G = build_from_json(
{
"nodes": r_defn["nodes"] + r_user["nodes"],
"edges": r_defn["edges"] + r_user["edges"],
}
)
nic_id = next(n["id"] for n in r_user["nodes"] if n["label"] == "azurerm_network_interface.nic")
assert G.has_edge(nic_id, rg_id)
def test_empty_and_commentonly_files_are_safe(tmp_path):
assert extract_terraform(_write(tmp_path, "a.tf", "")).get("error") is None
r = extract_terraform(_write(tmp_path, "b.tf", "# just a comment\n"))
# only the file node, no crash
assert len(r["nodes"]) == 1
def test_tfvars_key_value_is_safe(tmp_path):
# .tfvars files contain only key=value assignments (no block structure),
# so extract_terraform produces zero block nodes — only the file node.
# This is the documented intended behaviour for .tfvars.
r = extract_terraform(_write(tmp_path, "terraform.tfvars", 'region = "us-east-1"\nenv = "prod"\n'))
assert r.get("error") is None
assert len(r["nodes"]) == 1 # only the file node, no variable nodes
+161
View File
@@ -141,6 +141,41 @@ def test_rebuild_lock_does_not_accumulate_pids_across_runs(tmp_path):
assert not lock_path.exists()
def test_graphify_root_preserves_relative_when_invoked_with_relative_path(tmp_path, monkeypatch):
"""#777: ``.graphify_root`` stores the user-supplied path (``.``), not the
resolved absolute, so a committed ``graphify-out/.graphify_root`` is
portable across clones and CI runners."""
from graphify.watch import _rebuild_code
corpus = tmp_path / "corpus"
corpus.mkdir()
(corpus / "lib.py").write_text("def f(): pass\n", encoding="utf-8")
monkeypatch.chdir(corpus)
assert _rebuild_code(Path("."), acquire_lock=False) is True
saved = (corpus / "graphify-out" / ".graphify_root").read_text(encoding="utf-8")
assert saved == ".", (
f".graphify_root must preserve the user-supplied path; got {saved!r}"
)
def test_graphify_root_preserves_absolute_when_user_supplied(tmp_path):
"""When the caller supplies an absolute path, ``.graphify_root`` stores
that absolute form verbatim — preserving explicit-absolute intent."""
from graphify.watch import _rebuild_code
corpus = tmp_path / "corpus"
corpus.mkdir()
(corpus / "lib.py").write_text("def f(): pass\n", encoding="utf-8")
assert _rebuild_code(corpus, acquire_lock=False) is True
saved = (corpus / "graphify-out" / ".graphify_root").read_text(encoding="utf-8")
assert saved == str(corpus), (
f"absolute caller path must be preserved as-is; got {saved!r}"
)
def test_rebuild_code_evicts_nodes_from_deleted_files(tmp_path):
"""#1007: graphify update (_rebuild_code with no changed_paths) must remove
nodes and edges from files deleted since the last run."""
@@ -172,6 +207,132 @@ def test_rebuild_code_evicts_nodes_from_deleted_files(tmp_path):
assert "login()" in node_labels_after, "nodes from surviving file must be kept"
def test_rebuild_code_evicts_removed_symbol_from_surviving_file(tmp_path):
"""#1116: graphify update (_rebuild_code with no changed_paths) must prune a
symbol removed from a file that still exists — and its inbound call edge —
without dropping genuine semantic nodes that share the surviving file."""
import json
from graphify.watch import _rebuild_code
corpus = tmp_path / "corpus"
corpus.mkdir()
(corpus / "a.py").write_text(
"def foo(): pass\ndef bar(): pass\n", encoding="utf-8"
)
(corpus / "b.py").write_text(
"from a import foo\n\ndef caller():\n foo()\n", encoding="utf-8"
)
assert _rebuild_code(corpus, acquire_lock=False) is True
graph_path = corpus / "graphify-out" / "graph.json"
data = json.loads(graph_path.read_text(encoding="utf-8"))
def labels(d):
return {n["label"] for n in d.get("nodes", [])}
def id_for(d, label):
return next(n["id"] for n in d.get("nodes", []) if n["label"] == label)
def edges(d):
return d.get("links", d.get("edges", []))
before = labels(data)
assert {"foo()", "bar()", "caller()"} <= before
foo_id = id_for(data, "foo()")
caller_id = id_for(data, "caller()")
assert any(
{e.get("source"), e.get("target")} == {caller_id, foo_id}
for e in edges(data)
), "cross-file caller->foo call edge must exist before removal"
# Pre-seed a semantic node on the surviving a.py (no AST id, no _origin
# marker). A naive "evict every re-extracted file's nodes by source_file"
# fix would wrongly delete this; the identity-based fix must keep it.
data["nodes"].append({
"id": "a_authconcept",
"label": "AuthConcept",
"file_type": "concept",
"source_file": "a.py",
})
graph_path.write_text(json.dumps(data), encoding="utf-8")
# Remove foo() from a.py (keep bar); leave b.py untouched.
(corpus / "a.py").write_text("def bar(): pass\n", encoding="utf-8")
assert _rebuild_code(corpus, acquire_lock=False, force=True) is True
after_data = json.loads(graph_path.read_text(encoding="utf-8"))
after = labels(after_data)
assert "foo()" not in after, "removed symbol must be pruned from surviving file"
assert not any(
e.get("source") == foo_id or e.get("target") == foo_id
for e in edges(after_data)
), "dangling edge to the removed symbol must be dropped"
assert "bar()" in after, "surviving symbol in the same file must be kept"
assert "caller()" in after, "unchanged file's nodes must be kept"
assert "AuthConcept" in after, "semantic node on a surviving file must not be evicted"
def test_rebuild_code_preupgrade_marker_less_node_one_cycle_lag(tmp_path):
"""#1118 backward-compat: a graph.json built before #1116 has no `_origin`
markers. On the first `graphify update` after upgrading, a symbol removed
from a surviving file is NOT pruned that cycle — its old node carries no
marker, so the new drop-rule skips it. This is a deliberate one-cycle lag
(no data loss); it self-heals once the node has been stamped `_origin="ast"`
(which a full re-extraction does for every surviving symbol)."""
import json
from graphify.watch import _rebuild_code
corpus = tmp_path / "corpus"
corpus.mkdir()
(corpus / "a.py").write_text("def bar(): pass\n", encoding="utf-8")
assert _rebuild_code(corpus, acquire_lock=False) is True
graph_path = corpus / "graphify-out" / "graph.json"
data = json.loads(graph_path.read_text(encoding="utf-8"))
def labels(d):
return {n["label"] for n in d.get("nodes", [])}
# Simulate a pre-#1116 graph: strip every `_origin` marker, then inject a
# stale AST node for a symbol no longer present in a.py's source — also
# marker-less, exactly as a pre-upgrade graph would carry it.
for n in data["nodes"]:
n.pop("_origin", None)
data["nodes"].append({
"id": "a_foo",
"label": "foo()",
"file_type": "function",
"source_file": "a.py",
})
graph_path.write_text(json.dumps(data), encoding="utf-8")
# First update after "upgrade" (full rebuild, no changed_paths): the stale
# node has no marker, so the drop-rule skips it and it survives this cycle.
assert _rebuild_code(corpus, acquire_lock=False, force=True) is True
after = json.loads(graph_path.read_text(encoding="utf-8"))
assert "foo()" in labels(after), (
"pre-upgrade marker-less stale node must survive the first update — "
"documented one-cycle backward-compat lag (#1118)"
)
# Once stamped (a full re-extraction stamps every surviving symbol), the
# drop-rule applies on the next update and the stale node self-heals away.
for n in after["nodes"]:
if n["label"] == "foo()":
n["_origin"] = "ast"
graph_path.write_text(json.dumps(after), encoding="utf-8")
assert _rebuild_code(corpus, acquire_lock=False, force=True) is True
healed = json.loads(graph_path.read_text(encoding="utf-8"))
assert "foo()" not in labels(healed), (
"once carrying _origin=ast, the stale node is pruned on the next "
"update (self-heal)"
)
assert "bar()" in labels(healed), "surviving symbol must be kept throughout"
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
def test_rebuild_lock_non_blocking_does_not_clobber_holder(tmp_path):
"""GH-858: a non-blocking caller that fails to acquire the lock must not
@@ -684,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
```
@@ -520,7 +520,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -520,7 +520,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -801,7 +801,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json graphify-out/.graphify_incremental.json graphify-out/.graphify_transcripts.json graphify-out/.graphify_old.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_incremental.json graphify-out/.graphify_transcripts.json graphify-out/.graphify_old.json; find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -520,7 +520,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -522,7 +522,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -515,7 +515,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -522,7 +522,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -521,7 +521,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -519,7 +519,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -545,7 +545,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
+2 -1
View File
@@ -523,7 +523,8 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -93,13 +93,18 @@ from graphify.detect import save_manifest
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=deleted or None,
prune_sources=prune,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+1 -1
View File
@@ -684,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
```
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more