Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 03:06:43 +01:00
160 changed files with 6580 additions and 880 deletions

No files matched your search

+29
View File
@@ -4,6 +4,35 @@ Full release notes with details on each version: [GitHub Releases](https://githu
## Unreleased
## 0.8.43 (2026-06-19)
- Feat: package manifests are now parsed deterministically into a dependency graph. `apm.yml`, `pyproject.toml`, `go.mod`, and `pom.xml` each yield ONE canonical package node per package (keyed by name) plus `depends_on` edges, routed to the AST path so the LLM never sees them. Previously `apm.yml` was an LLM-handled document, so the same package got a different file-anchored id from its own manifest than from each dependent's dependency reference and split into duplicate nodes; a package referenced from N manifests is now a single hub node (#1377).
- Feat: markdown links now become graph edges. `extract_markdown` only emitted heading nodes + `contains` edges and never parsed link syntax, so a doc full of `[text](./other.md)` links (e.g. `index.md`, `table-of-contents.md`) had no edges to what it links and never became a hub. Inline links, reference-style links, and `[[wikilinks]]` are resolved relative to the source file (external URLs / in-page anchors / images skipped) and emitted as `references` edges, with targets resolved via the same node-id recipe so they merge onto the real doc node (#1376).
- Security: bumped vulnerable dependencies to patched versions — `pypdf` 6.11.0→6.13.3 (CVE-2026-48155/48156), `yt-dlp` 2026.3.17→2026.6.9, `pyjwt` 2.12.1→2.13.0, `cryptography` 48.0.0→49.0.0, `python-multipart` 0.0.28→0.0.32 — with lower-bound floors for the direct deps (`pypdf`, `yt-dlp`) so installs get the patched versions (#1375; thanks @hypnwtykvmpr).
- Fix: the semantic extract entry points (`extract_corpus_parallel`, `extract_files_direct`) crashed with `AttributeError` when passed `str` paths instead of `pathlib.Path`. Both now coerce `files = [Path(f) for f in files]` at entry (#1386).
- Fix: community labeling now recovers from a malformed-JSON batch by splitting it at the midpoint and retrying each half (mirroring the extract path), instead of logging-and-skipping it — which silently lost ~100 community names per failed batch on large graphs (#1280, #1278; thanks @CJdev232).
- Fix: `graphify hook install` no longer creates a literal backslash-named junk directory and reports false success when `core.hooksPath` (or `git rev-parse --git-path hooks`) is a Windows-style path under WSL. Drive-letter / embedded-backslash hooks paths are now rejected with a clear error (#1385).
- Refactor: node-ID normalization is unified into a single `graphify.ids` module. `extract._make_id`, `build._normalize_id`, `mcp_ingest._make_id`, and `symbol_resolution._bash_make_id` were four hand-synced copies of the same NFKC/casefold recipe — the root of the recurring ghost-node bug class (#811/#550/#1033/#1104). All four now delegate to one implementation guarded by contract + hypothesis property tests (#1378; thanks @danielnguyenfinhub).
## 0.8.42 (2026-06-18)
- Fix: large text documents are no longer silently truncated during semantic extraction. `_read_files` capped every file at 20,000 characters, so a Markdown/text/rST document longer than that had everything past the cap dropped — the model never saw it, and the packer/adaptive-retry path couldn't recover ("packing can't shrink one big file"). Oversized splittable-text files are now sliced at heading/paragraph boundaries into units that each fit the cap and together cover the whole file; every slice reports its parent file as `source_file`, so the graph is not fragmented per-slice. A single slice that still overflows the model's output is bisected and retried. Code files and PDFs are never sliced (they keep whole-symbol / page handling). (#1369)
- Fix: `/graphify --update` no longer deletes a changed file's freshly re-extracted nodes. The `0.8.41` `root=` fix (#1361) made `build_merge`'s prune actually match relative `source_file` values — which then matched the just-re-extracted nodes of *changed* files (still listed in `prune_sources`) and removed them, so an `--update` on a changed file could wipe its nodes. The update runbook now prunes only genuinely **deleted** files; changed files are reconciled by `build_merge`'s replace-on-re-extract (#1344). The full build also now passes `root=` to `build_from_json`, and the extraction-spec `source_file` is pinned to the verbatim path, so the full build and incremental updates never drift on node-key base. (#1366; thanks @RelywOo)
- Fix: Java `record` declarations are now modeled as first-class type nodes (they share `class_declaration`'s name/body/interfaces fields), and `new Foo(...)` constructor calls now produce a `calls` edge to the constructed type. Previously a record appeared only as its file node (degree 0) with no incoming edges, and body-level `new` usages were dropped because `object_creation_expression` wasn't a recognized call type and its callee lives in the `type` field rather than `name`. (#1373)
- Security fix: `.graphifyignore` and `.gitignore` are now **merged** per directory instead of `.graphifyignore` silently replacing that directory's `.gitignore`. Previously, adding a `.graphifyignore` (e.g. to exclude media) disabled the dir's `.gitignore` entirely, so a file excluded only by `.gitignore` — including neutrally-named secrets like `prod-dump.sql` or `customer-data.json` that the sensitive-file heuristic doesn't catch — got indexed into the graph, whose artifacts embed file contents and are routinely committed. `.gitignore` is read first and `.graphifyignore` last, so `.graphifyignore` patterns (including `!` negations) still win on conflict; adding one can only ever exclude more, never re-include a `.gitignore`-excluded file. (#1363)
## 0.8.41 (2026-06-17)
- Fix: OpenAI-compatible backends (`ollama`, `openai`, `deepseek`, `kimi`) now honour their configured `16384` output-token cap instead of silently falling back to `8192`. The dispatch read a `max_completion_tokens` config key that only `gemini` defines; the others set `max_tokens`, so their advertised cap was dead and deep-mode JSON truncated mid-string (recovered by the adaptive bisect, but noisy and slower). The dispatch now reads either key, and the `openai` config gained an explicit cap. `GRAPHIFY_MAX_OUTPUT_TOKENS` still overrides. (#1365)
- Fix: fuzzy dedup no longer over-merges distinct nodes in three cases. (1) Numbered/versioned siblings whose embedded digit runs differ as zero-padding-insensitive multisets (`ADR 0011` vs `ADR 0013`, `3.1 Product Goals` vs `1.1 Product Goals`, `40%+ …` vs `<20% …`) never merge. (2) `rationale`/`document` nodes are file-anchored like code (#1205's reasoning): near-identical docstring/heading boilerplate in parallel files no longer collapses across files, while same-file duplicates still merge. (3) Cross-file labels that share a long prefix but diverge in a distinguishing token (`testing-library jest-native` vs `react-native`) are scored on plain Jaro instead of Jaro-Winkler, so the leading-prefix bonus can no longer fabricate a merge; genuine cross-file duplicates still clear the bar on Jaro alone, and same-file near-duplicates keep Jaro-Winkler. Guards are mirrored into the `--dedup-llm` ambiguous-pair collection. (#1284 thanks @van4oza, #1243)
- Fix: Swift cross-file class relationships expressed through member calls and constructors now resolve to the receiver's real definition. A per-file type table (built from property/parameter declarations and constructor inference) types the receiver of `recv.method()` / `Type.staticMethod()` / `Singleton.shared.method()` / `self.prop.method()`, and property/field initializers (`let vm = VM()`) are now walked for constructor calls. Edges are emitted only when the receiver's type resolves to exactly one definition (preserving the #543/#1219 god-node guards) and are tagged `INFERRED`; the blanket member-call skip in the shared call pass is untouched (#1356).
- Fix: `/graphify <path> --update` now prunes stale nodes correctly. The update runbook called `build_merge(prune_sources=...)` without `root=`, so the absolute prune paths were never relativized to match the graph's relative `source_file` values — nothing was pruned and changed/deleted files left ghost nodes that compounded on every incremental run. The shared skill fragment now passes `root` (the native `graphify update` CLI was already correct) (#1361).
- Fix: `export obsidian` no longer writes an empty 32-byte `graph.canvas` on a populated graph. `to_canvas` built cards solely by iterating communities, so a graph with no community data (`--no-cluster` builds, or a missing analysis sidecar) produced the empty `{"nodes": [], "edges": []}` shell while the markdown notes rendered fine. It now falls back to one synthetic community covering every node (#1324).
- Fix: edges missing a `source_file` field (occasionally emitted by the semantic/LLM extractor, which `build` only normalized when the field was already present) are now backfilled from the edge's endpoint nodes in `build_from_json` and the `--no-cluster` raw-write path, so they no longer reach `graph.json` without a file reference or trip validation (#1279).
- Fix: every platform's query skill now ships **both** the vocab/IDF query-expansion step and the inline NetworkX fallback. Previously the two capabilities were split across `cli.md` / `cli-inline.md` so no platform got both — Claude had the superior expansion but no CLI-down fallback, while all other platforms had the fallback but the weaker raw-question matcher. The two fragments are merged into one unified `query` reference (and stub) shipped to all hosts; the `query_variant` enum and its coverage-audit exemption are removed (#1325; thanks @LeanderBlume).
- Fix: cross-file Java `implements`/`inherits`/`imports` edges no longer orphan onto bare "shadow" nodes when two packages define a same-named type. The referencing file's `import` statement now disambiguates by exact package (FQN) and re-points the edge to the real definition, dropping the orphan stub. Previously `_rewire_unique_stub_nodes` could only repair the globally-unique case, so same-named interfaces (common in large Java codebases — `Handler`, `Service`, interface+impl pairs) left the real definition isolated in its own community (#1318).
- Fix: Swift imports of the same module from multiple files now collapse to a single shared `type=module` node instead of N path-qualified duplicates. The import target is tagged `type=module` and exempted from id-disambiguation, so reverse traversal ("what imports CoreKit?") works; the `--no-cluster` writer also now dedupes nodes by id (and edges) to match the clustered `build_from_json` path. Builds on the v0.8.40 Swift-import fix (#1327, #1330; thanks @duncan-daydream).
## 0.8.40 (2026-06-16)
- Feat: custom OpenAI- and Anthropic-compatible endpoints via `OPENAI_BASE_URL`/`OPENAI_MODEL` and `ANTHROPIC_BASE_URL`/`ANTHROPIC_MODEL`. Point either backend at a self-hosted or proxy server (vLLM, llama.cpp, LM Studio, LiteLLM, gateways); defaults still resolve to `api.openai.com` / `api.anthropic.com`, and `GRAPHIFY_OPENAI_MODEL` keeps precedence over `OPENAI_MODEL`. Wired through both the extraction path (`_call_claude`) and community labeling (#1273).
+11 -2
View File
@@ -242,7 +242,8 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| 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` |
| Package manifests | `apm.yml` `pyproject.toml` `go.mod` `pom.xml` — one canonical package node per package (by name) plus `depends_on` edges, so a package referenced from many manifests is a single hub |
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` (markdown `[text](./other.md)` links and `[[wikilinks]]` become `references` edges between docs) |
| Office | `.docx .xlsx` (requires `uv tool install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `uv tool install graphifyy[google]`) |
| PDFs | `.pdf` |
@@ -304,7 +305,7 @@ See the [full command reference](#full-command-reference) below.
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.
**`.gitignore` is respected automatically.** graphify reads the `.gitignore` in each directory. If a `.graphifyignore` is also present, the two are **merged** — `.graphifyignore` patterns are evaluated last, so they win on conflicts (including `!` negations). Adding a `.graphifyignore` only ever excludes more; it never re-includes a file your `.gitignore` already excluded. Subdirectory scoping works the same way as git — an ignore file only affects its own subtree.
```
# .graphifyignore
@@ -470,6 +471,14 @@ The KV-cache window is auto-sized but may be too large for your GPU. Reduce it:
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
```
**`LLM returned invalid JSON` / `Unterminated string` warnings**
The model's JSON response hit its output-token limit and was cut off mid-string. graphify auto-recovers (it splits the chunk and re-extracts the halves, and an oversized single document is first sliced at heading/paragraph boundaries so the whole file is still covered), so these warnings are noisy but not data loss. To reduce the churn, raise the output cap or shrink each chunk's output:
```bash
GRAPHIFY_MAX_OUTPUT_TOKENS=16384 graphify extract . --mode deep # lift the cap
graphify extract . --mode deep --token-budget 4000 # smaller input chunks -> smaller output
```
With a cloud gateway like OpenRouter, prefer `--backend openai` (set `OPENAI_BASE_URL`) over the Ollama shim — it's a cleaner OpenAI-compatible path. If the model has its own max-output ceiling, lowering `--token-budget` is the reliable lever.
**Graph HTML is too large to open in a browser (>5000 nodes)**
Skip HTML generation and use the JSON directly:
```bash
+43 -4
View File
@@ -3524,10 +3524,18 @@ def main() -> None:
except TypeError:
G = _jg.node_link_graph(data)
graphs.append(G)
# nx.compose requires all graphs to be the same type. When input graphs
# come from different sources (e.g. an AST-only run vs a full LLM run) one
# may be a MultiGraph and another a Graph. Normalise everything to Graph
# (the graphify default) by converting MultiGraphs with nx.Graph().
def _to_simple(g: "_nx.Graph") -> "_nx.Graph":
if isinstance(g, _nx.MultiGraph):
return _nx.Graph(g)
return g
merged = _nx.Graph()
for G, gp in zip(graphs, graph_paths):
repo_tag = gp.parent.parent.name # graphify-out/../ → repo dir name
prefixed = _prefix(G, repo_tag)
prefixed = _to_simple(_prefix(G, repo_tag))
merged = _nx.compose(merged, prefixed)
try:
out_data = _jg.node_link_data(merged, edges="links")
@@ -4425,11 +4433,42 @@ def main() -> None:
if no_cluster:
# --no-cluster: dump the raw merged extraction as graph.json.
# No NetworkX, no community detection, no analysis sidecar.
# Dedupe parallel edges so counts match the clustered path (whose
# DiGraph collapses them) and stay deterministic across modes (#1317).
from graphify.build import dedupe_edges as _dedupe_edges
# Dedupe nodes (by id) and parallel edges so the raw output matches the
# clustered path (whose DiGraph collapses both) and stays deterministic
# across modes (#1317; node dedup also collapses shared Swift module
# anchors emitted per importing file, #1327).
from graphify.build import dedupe_edges as _dedupe_edges, dedupe_nodes as _dedupe_nodes
from graphify.export import backup_if_protected as _backup
if (
incremental_mode
and not code_files
and not semantic_files
and not deleted_files
and not pg_result.get("nodes")
and not pg_result.get("edges")
and not cargo_result.get("nodes")
and not cargo_result.get("edges")
):
print(
"[graphify extract] no incremental changes detected "
"(--no-cluster); outputs left untouched."
)
try:
_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)
sys.exit(0)
merged["nodes"] = _dedupe_nodes(merged["nodes"])
merged["edges"] = _dedupe_edges(merged["edges"])
# Backfill source_file from endpoint nodes — this raw path bypasses
# build_from_json's backfill, and semantic edges sometimes omit it (#1279).
_node_sf = {n.get("id"): n.get("source_file") for n in merged["nodes"]}
for _e in merged["edges"]:
if not _e.get("source_file"):
_e["source_file"] = (
_node_sf.get(_e.get("source")) or _node_sf.get(_e.get("target")) or ""
)
_backup(graphify_out)
graph_json_path.write_text(
json.dumps(merged, indent=2), encoding="utf-8"
+10 -5
View File
@@ -4,6 +4,7 @@ from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import unicodedata
import networkx as nx
@@ -45,18 +46,22 @@ def _format_location(data: dict) -> str:
def _bare_name(label: str) -> str:
"""Lowercased label with the callable decoration (trailing "()") removed."""
label = label.lower()
label = _normalize_label(label)
return label[:-2] if label.endswith("()") else label
def _normalize_label(label: str) -> str:
return unicodedata.normalize("NFC", label).casefold()
def resolve_seed(graph: nx.Graph, query: str) -> str | None:
if query in graph:
return query
query_lower = query.lower()
query_lower = _normalize_label(query)
exact_label_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if str(data.get("label", "")).lower() == query_lower
if _normalize_label(str(data.get("label", ""))) == query_lower
]
if len(exact_label_matches) == 1:
return exact_label_matches[0]
@@ -74,14 +79,14 @@ def resolve_seed(graph: nx.Graph, query: str) -> str | None:
exact_source_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if str(data.get("source_file", "")).lower() == query_lower
if _normalize_label(str(data.get("source_file", ""))) == query_lower
]
if len(exact_source_matches) == 1:
return exact_source_matches[0]
contains_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if query_lower in str(data.get("label", "")).lower()
if query_lower in _normalize_label(str(data.get("label", "")))
]
if len(contains_matches) == 1:
return contains_matches[0]
+66 -18
View File
@@ -28,6 +28,7 @@ import sys
import unicodedata
from pathlib import Path
import networkx as nx
from .ids import normalize_id as _normalize_id
from .validate import validate_extraction
@@ -51,20 +52,6 @@ _FILE_TYPE_SYNONYMS = {
}
def _normalize_id(s: str) -> str:
r"""Normalize an ID string the same way extract._make_id does.
Used to reconcile edge endpoints when the LLM generates IDs with slightly
different punctuation or casing than the AST extractor. Must stay in sync
with extract._make_id — NFKC normalization, \w with re.UNICODE, underscore
collapse, and casefold must all match (#811).
"""
s = unicodedata.normalize("NFKC", s)
cleaned = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
cleaned = re.sub(r"_+", "_", cleaned)
return cleaned.strip("_").casefold()
def _norm_source_file(p: str | None, root: str | None = None) -> str | None:
"""Normalize path separators and relativize absolute paths.
@@ -104,6 +91,25 @@ def edge_datas(G: nx.Graph, u: str, v: str) -> list[dict]:
return [raw]
def dedupe_nodes(nodes: list[dict]) -> list[dict]:
"""Collapse nodes sharing an ``id``, last-writer-wins on attributes.
Mirrors what ``build_from_json``'s ``G.add_node`` does implicitly (idempotent;
a later node overwrites an earlier one's attributes). The ``--no-cluster``
write path dumps the raw node list without building a graph, so same-id nodes
— e.g. a Swift ``type=module`` anchor emitted once per importing file (#1327)
— would otherwise appear as duplicates. Insertion order follows each id's
first appearance; the retained dict is the last one seen.
"""
by_id: dict = {}
for n in nodes:
nid = n.get("id")
if nid is None:
continue
by_id[nid] = n
return list(by_id.values())
def dedupe_edges(edges: list[dict]) -> list[dict]:
"""Collapse exact parallel edges by ``(source, target, relation)``, keeping the
first occurrence.
@@ -277,6 +283,15 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
if src not in node_set or tgt not in node_set:
continue # skip edges to external/stdlib nodes - expected, not an error
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
# Backfill source_file from the endpoint nodes (every node carries one).
# Semantic/LLM edges occasionally omit it, which downstream validation
# flags and leaves query results with no file reference (#1279).
if not attrs.get("source_file"):
attrs["source_file"] = (
G.nodes[src].get("source_file")
or G.nodes[tgt].get("source_file")
or ""
)
if "source_file" in attrs:
attrs["source_file"] = _norm_source_file(attrs["source_file"], _root)
# Drop cross-language INFERRED `calls` edges — same short names (render,
@@ -424,8 +439,11 @@ def build_merge(
) -> nx.Graph:
"""Load existing graph.json, merge new chunks into it, and save back.
Never replaces - only grows (or prunes deleted-file nodes via prune_sources).
Safe to call repeatedly: existing nodes and edges are preserved.
Re-extracted files REPLACE their prior contribution: any source_file present
in new_chunks is dropped from the loaded graph before merging, so a changed
file's stale nodes/edges don't accumulate. Files absent from new_chunks are
preserved unchanged; deleted files are removed via prune_sources.
Safe to call repeatedly.
root: if given, absolute source_file paths in new_chunks are made relative (#932).
"""
graph_path = Path(graph_path)
@@ -443,10 +461,40 @@ def build_merge(
links_key = "links" if "links" in data else "edges"
existing_nodes = list(data.get("nodes", []))
existing_edges = list(data.get(links_key, []))
base = [{"nodes": existing_nodes, "edges": existing_edges}]
had_graph = True
else:
existing_nodes = []
base = []
existing_edges = []
had_graph = False
# Re-extracted files REPLACE their prior contribution. Every source_file
# present in new_chunks is dropped from the loaded base before merging, so a
# CHANGED file's stale nodes/edges don't accumulate across incremental
# updates. Without this, build() merges old+new for the same file and only
# exact-duplicate edges collapse — edges/nodes that disappeared from the new
# version survive forever. Brand-new files aren't in base, so this is a no-op
# for them; genuinely deleted files are still handled via prune_sources.
# Matched in both raw and _norm_source_file form because new_chunks may carry
# absolute win32 paths while the stored graph keeps relative posix (#1007).
_replace_root = str(Path(root).resolve()) if root is not None else None
new_sources: set[str] = set()
for ch in new_chunks:
for n in ch.get("nodes", []):
sf = n.get("source_file")
if not sf:
continue
new_sources.add(sf)
norm = _norm_source_file(sf, _replace_root)
if norm:
new_sources.add(norm)
if new_sources:
def _kept(item: dict) -> bool:
sf = item.get("source_file")
return sf not in new_sources and _norm_source_file(sf, _replace_root) not in new_sources
existing_nodes = [n for n in existing_nodes if _kept(n)]
existing_edges = [e for e in existing_edges if _kept(e)]
base = [{"nodes": existing_nodes, "edges": existing_edges}] if had_graph else []
all_chunks = base + list(new_chunks)
G = build(all_chunks, directed=directed, dedup=dedup, dedup_llm_backend=dedup_llm_backend, root=root)
+79 -3
View File
@@ -10,7 +10,7 @@ import unicodedata
from collections import defaultdict
from graphify._minhash import MinHash, MinHashLSH
from rapidfuzz.distance import JaroWinkler
from rapidfuzz.distance import Jaro, JaroWinkler
# ── helpers ───────────────────────────────────────────────────────────────────
@@ -89,6 +89,52 @@ def _short_label_blocked(a: str, b: str, jw_score: float) -> bool:
return True
_DIGIT_RUN = re.compile(r"\d+")
def _numeric_tokens_differ(a: str, b: str) -> bool:
"""True when two labels carry different embedded numbers (#1284).
Long labels that differ only in their digit runs ("ADR 0011 §D5" vs
"ADR 0013 D4", "3.1 Product Goals" vs "1.1 Product Goals", "block3" vs
"block13", "40%+ retention" vs "<20% retention") are numbered/versioned
siblings, not duplicates -- but the long shared boilerplate keeps
Jaro-Winkler above _MERGE_THRESHOLD, and _is_variant_pair only covers
short trailing suffixes. Digit runs are compared as multisets with
leading zeros stripped, so zero-padding ("09" vs "9") does not count as
a difference. (String comparison, not int(): a pathological label with a
>4300-digit run would crash int() on Python's conversion limit.) Labels
with identical numbers, or none at all, are unaffected.
"""
if a == b:
return False
return sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(a)) != \
sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(b))
# file_type values whose identity is anchored to their source location, not
# their label text. Like code (#1205), these must not be label-merged across
# files: rationale = module/class docstrings, document = headings/positional
# content. `concept` is intentionally excluded -- it is the type meant to unify
# across files (protected from over-merge by the numeric/Jaro guards instead).
_FILE_ANCHORED_NONCODE = frozenset({"rationale", "document"})
def _crossfile_fileanchored_blocked(node: dict, neighbor: dict) -> bool:
"""Block label-based merging of file-anchored non-code nodes across files (#1284).
rationale/document nodes are docstring- and heading-derived and as
file-anchored as the code they describe (#1205's reasoning, one layer up):
parallel modules carry near-identical boilerplate ("Django app config for
apps.<name>. No business logic here...") that differs by one word and sails
past the JW threshold. Same-file duplicates of these types may still merge.
"""
if (node.get("file_type") not in _FILE_ANCHORED_NONCODE
and neighbor.get("file_type") not in _FILE_ANCHORED_NONCODE):
return False
return (node.get("source_file") or "") != (neighbor.get("source_file") or "")
# ── union-find ────────────────────────────────────────────────────────────────
class _UF:
@@ -270,7 +316,20 @@ def deduplicate_entities(
continue
neighbor_norm = norm_cache.get(neighbor_id) or _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
# Cross-file long labels score on plain Jaro (no prefix bonus).
# Jaro-Winkler's leading-prefix bonus lifts pairs that share a
# prefix but diverge in a distinguishing token ("testing-library
# jest-native" vs "react-native") past threshold, fabricating
# destructive cross-file merges; on Jaro alone they fall short
# while true cross-file duplicates still clear it (#1243). Same-file
# near-duplicates keep Jaro-Winkler (low-risk, and a mid-string
# stopword insertion needs the prefix bonus to merge); short labels
# keep Jaro-Winkler too (gated by _short_label_blocked).
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
if _xfile and max(len(norm_label), len(neighbor_norm)) >= 12:
score = Jaro.normalized_similarity(norm_label, neighbor_norm) * 100
else:
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
if _is_variant_pair(norm_label, neighbor_norm):
continue
@@ -283,6 +342,13 @@ def deduplicate_entities(
_lo, _hi = sorted((norm_label, neighbor_norm), key=len)
if _hi.startswith(_lo) and _hi != _lo:
continue
# Numbered/versioned siblings and cross-file file-anchored
# boilerplate (rationale/document) are decisively distinct
# regardless of score (#1284).
if _numeric_tokens_differ(norm_label, neighbor_norm):
continue
if _crossfile_fileanchored_blocked(node, neighbor):
continue
c1 = communities.get(node_id)
c2 = communities.get(neighbor_id)
@@ -407,7 +473,12 @@ def _llm_tiebreak(
if uf.find(node["id"]) == uf.find(neighbor["id"]):
continue
norm_j = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
# Mirror pass 2: plain Jaro for cross-file long labels (#1243).
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
if _xfile and max(len(norm_i), len(norm_j)) >= 12:
score = Jaro.normalized_similarity(norm_i, norm_j) * 100
else:
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
if _is_variant_pair(norm_i, norm_j):
continue
if _short_label_blocked(norm_i, norm_j, score):
@@ -415,6 +486,11 @@ def _llm_tiebreak(
_lo, _hi = sorted((norm_i, norm_j), key=len)
if _hi.startswith(_lo) and _hi != _lo:
continue
# Mirror pass 2: decisively-distinct pairs never reach the LLM (#1284).
if _numeric_tokens_differ(norm_i, norm_j):
continue
if _crossfile_fileanchored_blocked(node, neighbor):
continue
c1 = communities.get(node["id"])
c2 = communities.get(neighbor["id"])
if (c1 is not None and c2 is not None and c1 == c2
+25 -11
View File
@@ -26,7 +26,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', '.psm1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml', '.cls', '.trigger'}
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml', '.cls', '.trigger'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
@@ -383,6 +383,13 @@ def _shebang_file_type(path: Path) -> FileType | None:
def classify_file(path: Path) -> FileType | None:
# Package manifests (apm.yml, pyproject.toml, go.mod, pom.xml) are parsed
# deterministically, so route them to the AST path (CODE) rather than the LLM
# document path — otherwise apm.yml (a .yml "document") would be LLM-extracted
# and a package would split into duplicate file-anchored nodes (#1377).
from graphify.manifest_ingest import is_package_manifest_path
if is_package_manifest_path(path):
return FileType.CODE
# Compound extensions must be checked before simple suffix lookup
if path.name.lower().endswith(".blade.php"):
return FileType.CODE
@@ -757,16 +764,23 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
patterns: list[tuple[Path, str]] = []
for d in dirs:
# Prefer .graphifyignore; fall back to .gitignore so projects that already
# maintain a .gitignore get sensible defaults without duplicating it (#945).
ignore_file = d / ".graphifyignore"
if not ignore_file.exists():
ignore_file = d / ".gitignore"
if ignore_file.exists():
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = _parse_gitignore_line(raw)
if line:
patterns.append((d, line))
# Merge .gitignore and .graphifyignore for this dir (#1363). Previously
# the presence of a .graphifyignore made graphify skip that dir's
# .gitignore entirely, so a file excluded only by .gitignore (e.g. a
# neutrally-named secret like prod-dump.sql) silently got indexed into
# the graph — whose artifacts embed file contents and are often
# committed. .gitignore is read first and .graphifyignore last, so
# .graphifyignore patterns (including `!` negations) win on conflict via
# last-match-wins; adding a .graphifyignore can only ever exclude MORE,
# never re-include a .gitignore-excluded file (#945 kept: a project with
# only a .gitignore still gets sensible defaults).
for fname in (".gitignore", ".graphifyignore"):
ignore_file = d / fname
if ignore_file.exists():
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = _parse_gitignore_line(raw)
if line:
patterns.append((d, line))
return patterns
+7
View File
@@ -1127,6 +1127,13 @@ def to_canvas(
seen_names[base] = 0
node_filenames[node_id] = base
# Fallback: with no community data (e.g. --no-cluster builds or a missing
# analysis sidecar) the grid below produces nothing and the canvas is written
# as an empty 32-byte shell on an otherwise populated graph. Emit every node
# into one synthetic community so the canvas always reflects the graph (#1324).
if not communities and G.number_of_nodes() > 0:
communities = {0: [str(n) for n in G.nodes()]}
num_communities = len(communities)
cols = math.ceil(math.sqrt(num_communities)) if num_communities > 0 else 1
rows = math.ceil(num_communities / cols) if num_communities > 0 else 1
+1044 -47
View File
File diff suppressed because it is too large. Load diff
+162
View File
@@ -0,0 +1,162 @@
"""Intra-file slicing for oversized text documents (#1369).
The extraction packer (`_pack_chunks_by_tokens`) treats each file as atomic and
`_read_files` caps every file at ``_FILE_CHAR_CAP`` characters, so a document
larger than that cap had everything past the cap silently dropped — the model
never saw it, and nothing in the adaptive-retry path could recover it ("a single
file larger than the budget ... packing can't shrink one big file").
This module splits an oversized *splittable text* document (Markdown, plain
text, reStructuredText) into contiguous ``FileSlice`` units at heading /
paragraph / line boundaries so the whole file gets extracted across several
units. Every slice of a file reports the **parent file path** as its source, so
the resulting nodes are never fragmented per-slice — they merge by source_file
exactly as if the file had been extracted in one pass.
Only plain-text documents are sliced: code files need whole-symbol context, and
PDFs/images are read through their own extractors and have no char-offset model.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
# Plain-text document types where boundary-based slicing is meaningful and where
# `_file_to_text` is a straight ``read_text`` (so a char range matches the bytes
# the model is shown). Deliberately excludes code (.py, .ts, ...) and binary
# docs (.pdf) — those are never sliced.
_SPLITTABLE_TEXT_SUFFIXES = frozenset({".md", ".mdx", ".markdown", ".txt", ".rst"})
# Boundary preferences, strongest first. A Markdown heading (``\n#``) keeps a
# section with its title; a blank line keeps a paragraph intact; a bare newline
# avoids cutting mid-line. If none is found in the window we hard-cut.
_BOUNDARY_SEPARATORS = ("\n#", "\n\n", "\n")
@dataclass(frozen=True)
class FileSlice:
"""A contiguous ``[start, end)`` character range of a splittable text file.
``index``/``total`` are for logging only. ``path`` is the real file on disk;
the slice always reports ``path`` as its source so slices don't fragment the
graph.
"""
path: Path
start: int
end: int
index: int
total: int
# A unit of extraction work: either a whole file (``Path``) or one slice of one.
Unit = "Path | FileSlice"
def unit_path(unit: "Path | FileSlice") -> Path:
"""The on-disk path a unit belongs to (the parent file for a slice)."""
return unit.path if isinstance(unit, FileSlice) else unit
def is_splittable_text(path: Path) -> bool:
"""True for plain-text document types that may be sliced."""
return path.suffix.lower() in _SPLITTABLE_TEXT_SUFFIXES
def _best_cut(text: str, start: int, end: int) -> int:
"""Return a cut index in ``(start, end]`` at the strongest nearby boundary.
Searches the window ``text[start:end]`` for the latest heading, then blank
line, then newline, and returns the index just *after* it (a heading cuts
just *before* the ``#`` so the heading leads the next slice). Falls back to a
hard cut at ``end`` when the window has no usable boundary, which still makes
forward progress because ``end > start``.
"""
window = text[start:end]
for sep in _BOUNDARY_SEPARATORS:
idx = window.rfind(sep)
if idx > 0: # a boundary strictly inside the window (non-empty prev slice)
if sep == "\n#":
return start + idx + 1 # keep the newline with the previous slice
return start + idx + len(sep)
return end
def slice_boundaries(text: str, max_chars: int) -> list[tuple[int, int]]:
"""Contiguous ``(start, end)`` ranges covering all of ``text``, each ≤ max_chars.
Ranges are gap-free and non-overlapping, so concatenating the slices
reproduces ``text`` exactly — no content is dropped.
"""
n = len(text)
if n <= max_chars:
return [(0, n)]
bounds: list[tuple[int, int]] = []
pos = 0
while pos < n:
hard = min(pos + max_chars, n)
end = _best_cut(text, pos, hard) if hard < n else n
if end <= pos: # defensive: never stall
end = hard
bounds.append((pos, end))
pos = end
return bounds
def expand_oversized_files(
files: list[Path], max_chars: int
) -> list["Path | FileSlice"]:
"""Replace each oversized splittable-text file with a list of ``FileSlice``s.
Files at or below ``max_chars`` (and all non-splittable files) pass through
unchanged as ``Path``, so behaviour is identical for everything that already
fit. Unreadable files pass through untouched (the reader handles the error).
"""
out: list["Path | FileSlice"] = []
for f in files:
if not is_splittable_text(f):
out.append(f)
continue
try:
text = f.read_text(encoding="utf-8", errors="replace")
except OSError:
out.append(f)
continue
if len(text) <= max_chars:
out.append(f)
continue
ranges = slice_boundaries(text, max_chars)
total = len(ranges)
for i, (s, e) in enumerate(ranges):
out.append(FileSlice(path=f, start=s, end=e, index=i, total=total))
return out
def read_slice_text(fs: FileSlice) -> str:
"""Read just this slice's characters from its parent file."""
text = fs.path.read_text(encoding="utf-8", errors="replace")
return text[fs.start:fs.end]
def bisect_slice(fs: FileSlice) -> tuple[FileSlice, FileSlice] | None:
"""Split a slice into two halves at a newline near its midpoint, or None.
Used by the adaptive-retry path when a single slice still overflows the
model's output: halving it produces a smaller response. Returns None when the
slice is already too small to split meaningfully.
"""
if fs.end - fs.start <= 1:
return None
try:
text = fs.path.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
mid = (fs.start + fs.end) // 2
nl = text.find("\n", mid, fs.end)
cut = nl + 1 if (nl != -1 and fs.start < nl + 1 < fs.end) else mid
if not (fs.start < cut < fs.end):
return None
left = FileSlice(fs.path, fs.start, cut, fs.index, fs.total)
right = FileSlice(fs.path, cut, fs.end, fs.index, fs.total)
return left, right
+21
View File
@@ -284,6 +284,25 @@ def _git_root(path: Path) -> Path | None:
return None
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")
def _reject_windows_path(value: str, source: str) -> None:
"""Raise if a hooks path looks like a Windows absolute path (#1385).
On POSIX/WSL ``Path("C:\\Users\\...").is_absolute()`` is False, so an absolute
Windows hooks path gets joined under the repo root and mkdir'd as a literal
junk directory (backslashes and all), while install reports success and the
real ``.git/hooks`` gets nothing. Fail loudly instead so the user can fix it.
"""
if _WINDOWS_DRIVE_RE.match(value) or "\\" in value:
raise RuntimeError(
f"git hooks path from {source} looks like a Windows path: {value!r}. "
f"On WSL/POSIX this can't resolve to a real directory. Unset it with "
f"`git config --local --unset core.hooksPath`, or set a POSIX path."
)
def _hooks_dir(root: Path) -> Path:
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
try:
@@ -292,6 +311,7 @@ def _hooks_dir(root: Path) -> Path:
# configparser lowercases option names; git's hooksPath becomes hookspath
custom = cfg.get("core", "hookspath", fallback="").strip()
if custom:
_reject_windows_path(custom, "core.hooksPath")
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
@@ -331,6 +351,7 @@ def _hooks_dir(root: Path) -> Path:
# A valid hooks path can never contain newlines or NUL. Their presence
# means git echoed an unrecognised flag back (old git behaviour).
if res.returncode == 0 and raw and not any(c in raw for c in ("\n", "\r", "\x00")):
_reject_windows_path(raw, "git rev-parse --git-path hooks")
d = (root / raw).resolve()
d.mkdir(parents=True, exist_ok=True)
return d
+50
View File
@@ -0,0 +1,50 @@
"""Single source of truth for node-ID normalization.
Three independent producers must agree on node IDs or the graph splits a single
entity into disconnected ghost nodes:
1. The AST extractor (``extract._make_id``) — deterministic, per-language.
2. The semantic subagents (LLM) — follow the node-ID spec in the skill prompt.
3. The graph builder (``build._normalize_id``) — reconciles edge endpoints when
the LLM emits IDs with slightly different punctuation or casing than the AST.
Historically the normalization recipe was copy-pasted into ``extract._make_id``
and ``build._normalize_id`` and kept in sync only by mirrored docstrings, which
is exactly how the recurring ID-drift bug class crept in (#811 Unicode collapse,
#550 same-filename collisions, #1033 AST-vs-LLM file-node mismatch, #1104). This
module exists so the recipe lives in one place and the two callers can no longer
diverge.
The recipe: NFKC-normalize (so composed/decomposed Unicode forms collapse),
replace runs of non-word characters with a single underscore (``re.UNICODE`` so
CJK/Cyrillic/Arabic/accented-Latin letters survive instead of collapsing to a
per-file node), collapse repeated underscores, strip leading/trailing
underscores, and casefold.
"""
from __future__ import annotations
import re
import unicodedata
__all__ = ["normalize_id", "make_id"]
def normalize_id(s: str) -> str:
r"""Normalize a single ID string to its canonical form.
Idempotent: ``normalize_id(normalize_id(s)) == normalize_id(s)``.
"""
s = unicodedata.normalize("NFKC", s)
s = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
s = re.sub(r"_+", "_", s)
return s.strip("_").casefold()
def make_id(*parts: str) -> str:
"""Build a canonical node ID from one or more name parts.
Parts are joined with ``_`` (after stripping stray ``_``/``.`` edges from each
part) and then run through :func:`normalize_id`, so the result is identical to
what the builder produces from the joined string.
"""
return normalize_id("_".join(p.strip("_.") for p in parts if p))
+209 -55
View File
@@ -16,6 +16,14 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, replace
from pathlib import Path
from graphify.file_slice import (
FileSlice,
bisect_slice,
expand_oversized_files,
read_slice_text,
unit_path,
)
# `_read_files` truncates each file at this many characters before joining into
# the user message. Token estimates use the same cap so packing matches reality.
_FILE_CHAR_CAP = 20_000
@@ -100,6 +108,7 @@ BACKENDS: dict[str, dict] = {
"default_model": os.environ.get("OPENAI_MODEL", "gpt-4.1-mini"),
"env_key": "OPENAI_API_KEY",
"model_env_key": "GRAPHIFY_OPENAI_MODEL",
"max_tokens": 16384,
"pricing": {"input": 0.40, "output": 1.60}, # USD per 1M tokens
# Default (gpt-4.1-mini) accepts temperature=0. Reasoning models
# (o1/o3/o4/gpt-5) reject any explicit temperature and have it omitted
@@ -453,23 +462,33 @@ def _wrap_untrusted(rel: str, content: str) -> str:
)
def _read_files(paths: list[Path], root: Path) -> str:
"""Return file contents formatted for the extraction prompt.
def _read_files(units: "list[Path | FileSlice]", root: Path) -> str:
"""Return file/slice contents formatted for the extraction prompt.
Each file is wrapped in an <untrusted_source> delimiter block and known
Each unit is wrapped in an <untrusted_source> delimiter block and known
injection sentinels are defanged, so attacker-controlled source text cannot
be confused with the trusted system instructions (see issue #1210).
A ``FileSlice`` (one chunk of an oversized document, #1369) reports its
**parent file path** as ``rel`` so every slice of a file shares one
source_file and the graph isn't fragmented per-slice.
"""
parts: list[str] = []
for p in paths:
for u in units:
p = unit_path(u)
try:
rel = str(p.relative_to(root))
except ValueError:
rel = str(p)
try:
content = _file_to_text(p)
if isinstance(u, FileSlice):
content = read_slice_text(u)
else:
content = _file_to_text(p)
except OSError:
continue
# Whole files are still capped (covers non-splittable large files like
# code); slices are already bounded to the cap, so the cap is a no-op.
parts.append(_wrap_untrusted(rel, content[:_FILE_CHAR_CAP]))
return "\n\n".join(parts)
@@ -538,11 +557,17 @@ 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 _partition_semantic_files(
units: "list[Path | FileSlice]",
) -> tuple["list[Path | FileSlice]", list[Path]]:
"""Split a chunk into (text-like units, raster-image files).
A ``FileSlice`` is always text (only splittable text is sliced), so it never
lands in the image partition.
"""
text_units = [u for u in units if isinstance(u, FileSlice) or not _is_vision_image(u)]
image_files = [u for u in units if not isinstance(u, FileSlice) and _is_vision_image(u)]
return text_units, image_files
def _build_image_refs(image_files: list[Path], root: Path, *, read_bytes: bool = True) -> list[_ImageRef]:
@@ -721,7 +746,12 @@ def _parse_llm_json(raw: str) -> dict:
else:
stripped = after_fence.strip()
try:
return json.loads(stripped)
parsed = json.loads(stripped)
if isinstance(parsed, dict):
return parsed
# Top-level array/scalar (common LLM output) is not a usable graph
# fragment; fall through to the next strategy rather than returning a
# non-dict that callers will try to subscript (e.g. result["input_tokens"]).
except json.JSONDecodeError:
pass
# Strategy 2: extract the first balanced JSON object found anywhere in
@@ -751,7 +781,10 @@ def _parse_llm_json(raw: str) -> dict:
depth -= 1
if depth == 0:
try:
return json.loads(stripped[start : i + 1])
parsed = json.loads(stripped[start : i + 1])
if isinstance(parsed, dict):
return parsed
break
except json.JSONDecodeError:
break
print(
@@ -1270,7 +1303,12 @@ def extract_files_direct(
Returns dict with nodes, edges, hyperedges, input_tokens, output_tokens.
Raises ValueError for unknown backends or when no API key is configured.
Raises ImportError if SDK missing.
Accepts ``str`` paths as well as ``Path``; string entries are coerced up
front so downstream helpers (``_partition_semantic_files``, ``_read_files``,
``_build_image_refs``) can rely on ``Path`` semantics (#1386).
"""
files = [Path(f) for f in files]
if backend is None:
backend = detect_backend()
if backend is None:
@@ -1347,7 +1385,13 @@ def extract_files_direct(
user_msg,
temperature=_resolve_temperature(cfg.get("temperature", 0), mdl),
reasoning_effort=cfg.get("reasoning_effort"),
max_completion_tokens=_resolve_max_tokens(cfg.get("max_completion_tokens", 8192)),
# Honour max_completion_tokens (gemini) or the older max_tokens key
# (ollama/deepseek/kimi/openai) -- most openai-compat configs define the
# latter, so reading only max_completion_tokens silently capped their
# output at the 8192 fallback and truncated deep-mode JSON (#1365).
max_completion_tokens=_resolve_max_tokens(
cfg.get("max_completion_tokens") or cfg.get("max_tokens", 8192)
),
backend=backend,
deep_mode=deep_mode,
images=image_refs,
@@ -1355,15 +1399,26 @@ def extract_files_direct(
)
def _estimate_file_tokens(path: Path) -> int:
"""Estimate the prompt-token cost of a single file under `_read_files` rules.
def _estimate_file_tokens(unit: "Path | FileSlice") -> int:
"""Estimate the prompt-token cost of a file or slice under `_read_files` rules.
Uses tiktoken (`cl100k_base`) when available for accurate counts. Falls back
to the chars/4 heuristic if tiktoken is not installed. Both paths cap at
`_FILE_CHAR_CAP` to match `_read_files`'s truncation, plus a constant for
the `=== rel ===` separator. Returns 0 for unreadable paths so they don't
blow up packing.
the wrapper. Returns 0 for unreadable paths so they don't blow up packing.
"""
if isinstance(unit, FileSlice):
# A slice's size is its char range (already ≤ _FILE_CHAR_CAP). Use the
# tokenizer on its text when available, else the chars/4 heuristic.
if _TOKENIZER is None:
return (min(unit.end - unit.start, _FILE_CHAR_CAP) + _PER_FILE_OVERHEAD_CHARS) // _CHARS_PER_TOKEN
try:
content = read_slice_text(unit)[:_FILE_CHAR_CAP]
except OSError:
return 0
return len(_TOKENIZER.encode(content)) + (_PER_FILE_OVERHEAD_CHARS // _CHARS_PER_TOKEN)
path = unit
# 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):
@@ -1384,35 +1439,35 @@ def _estimate_file_tokens(path: Path) -> int:
def _pack_chunks_by_tokens(
files: list[Path],
files: "list[Path | FileSlice]",
token_budget: int,
) -> list[list[Path]]:
"""Greedily pack files into chunks that fit a token budget.
) -> "list[list[Path | FileSlice]]":
"""Greedily pack files/slices into chunks that fit a token budget.
Files are first grouped by parent directory so related artifacts share a
Units are first grouped by parent directory so related artifacts share a
chunk (cross-file edges are more likely to be extracted within a chunk
than across chunks). Within each directory, files are added one at a
time; a chunk is closed when adding the next file would exceed the
budget. A single file larger than the budget gets its own chunk and the
caller is expected to handle the API error if it actually overflows the
model's context window — packing can't shrink one big file.
than across chunks). Within each directory, units are added one at a
time; a chunk is closed when adding the next would exceed the budget.
Oversized splittable documents are pre-split into ``FileSlice`` units by
``expand_oversized_files`` before packing (#1369), so the old "one file
larger than the budget" case no longer silently drops content.
"""
if token_budget <= 0:
raise ValueError(f"token_budget must be positive, got {token_budget}")
by_dir: dict[Path, list[Path]] = {}
by_dir: dict[Path, "list[Path | FileSlice]"] = {}
for f in files:
by_dir.setdefault(f.parent, []).append(f)
by_dir.setdefault(unit_path(f).parent, []).append(f)
chunks: list[list[Path]] = []
current: list[Path] = []
chunks: "list[list[Path | FileSlice]]" = []
current: "list[Path | FileSlice]" = []
current_tokens = 0
current_images = 0
for directory in sorted(by_dir):
for path in by_dir[directory]:
cost = _estimate_file_tokens(path)
is_image = _is_vision_image(path)
for unit in by_dir[directory]:
cost = _estimate_file_tokens(unit)
is_image = not isinstance(unit, FileSlice) and _is_vision_image(unit)
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):
@@ -1420,7 +1475,7 @@ def _pack_chunks_by_tokens(
current = []
current_tokens = 0
current_images = 0
current.append(path)
current.append(unit)
current_tokens += cost
current_images += is_image
@@ -1497,9 +1552,35 @@ def _extract_with_adaptive_retry(
still failing at the cap, we surface the (likely empty) result with a
warning rather than infinite-loop.
A single-file chunk that overflows is unrecoverable here — we can't make
one file smaller than itself, so we return what we got and warn.
A single-file chunk that overflows is recoverable only when it's a slice of
a splittable document: the slice is bisected and retried (#1369). A whole
non-splittable file (e.g. one huge code file) can't be made smaller than
itself, so we return what we got and warn.
"""
def _merge_two(left_units, right_units) -> dict:
left = _extract_with_adaptive_retry(
left_units, backend, api_key, model, root, max_depth, _depth + 1, deep_mode=deep_mode
)
right = _extract_with_adaptive_retry(
right_units, backend, api_key, model, root, max_depth, _depth + 1, deep_mode=deep_mode
)
return {
"nodes": left.get("nodes", []) + right.get("nodes", []),
"edges": left.get("edges", []) + right.get("edges", []),
"hyperedges": left.get("hyperedges", []) + right.get("hyperedges", []),
"input_tokens": left.get("input_tokens", 0) + right.get("input_tokens", 0),
"output_tokens": left.get("output_tokens", 0) + right.get("output_tokens", 0),
"model": model,
"finish_reason": "stop",
}
def _split_lone_slice() -> "tuple[FileSlice, FileSlice] | None":
# When a single-unit chunk is a slice, bisect the slice so we can retry
# on a smaller range rather than give up (#1369).
if len(chunk) == 1 and isinstance(chunk[0], FileSlice) and _depth < max_depth:
return bisect_slice(chunk[0])
return None
try:
result = extract_files_direct(
chunk, backend=backend, api_key=api_key, model=model, root=root, deep_mode=deep_mode
@@ -1508,8 +1589,16 @@ def _extract_with_adaptive_retry(
if not _looks_like_context_exceeded(exc):
raise
if len(chunk) <= 1:
halves = _split_lone_slice()
if halves is not None:
print(
f"[graphify] slice of {unit_path(chunk[0])} exceeded context at "
f"depth {_depth}; splitting the slice and retrying",
file=sys.stderr,
)
return _merge_two([halves[0]], [halves[1]])
print(
f"[graphify] single-file chunk {chunk[0]} exceeds model context "
f"[graphify] single-file chunk {unit_path(chunk[0])} exceeds model context "
f"and cannot be split further: {exc}",
file=sys.stderr,
)
@@ -1547,8 +1636,16 @@ def _extract_with_adaptive_retry(
return result
if len(chunk) <= 1:
halves = _split_lone_slice()
if halves is not None:
print(
f"[graphify] slice of {unit_path(chunk[0])} truncated at depth {_depth}; "
f"splitting the slice and retrying",
file=sys.stderr,
)
return _merge_two([halves[0]], [halves[1]])
print(
f"[graphify] single-file chunk {chunk[0]} truncated at "
f"[graphify] single-file chunk {unit_path(chunk[0])} truncated at "
f"max_completion_tokens — partial result kept",
file=sys.stderr,
)
@@ -1636,7 +1733,15 @@ def extract_corpus_parallel(
Returns merged dict with nodes, edges, hyperedges, input_tokens,
output_tokens. Failed chunks are logged to stderr and skipped — one bad
chunk does not abort the run.
Accepts ``str`` paths as well as ``Path``; string entries are coerced up
front so packing/slicing helpers can rely on ``Path`` semantics (#1386).
"""
files = [Path(f) for f in files]
# Split oversized splittable documents into slices that cover the whole file
# before packing, so content past _FILE_CHAR_CAP is extracted instead of
# silently dropped (#1369). Files at/under the cap pass through unchanged.
files = expand_oversized_files(files, _FILE_CHAR_CAP)
if token_budget is not None:
chunks = _pack_chunks_by_tokens(files, token_budget=token_budget)
else:
@@ -2048,6 +2153,69 @@ def _parse_label_response(text: str, labeled_cids: list[int]) -> dict[int, str]:
return out
def _label_batch_with_retry(
batch_cids: list[int],
batch_lines: list[str],
*,
backend: str,
model: str | None,
depth: int = 0,
max_depth: int = 3,
) -> dict[int, str]:
"""Label a batch of communities, splitting in half and retrying on parse failure.
Mirrors `_extract_with_adaptive_retry`'s recovery shape for the labeling path
(#1278). When the LLM returns malformed JSON or a non-object payload, the
batch is split at the midpoint and each half is retried recursively. Recursion
is capped at ``max_depth`` to bound cost.
Returns ``{cid: name}`` for everything that could be labeled. When a batch
can't be split further (a single community, or ``depth >= max_depth``) and
still won't parse, the parse error is **re-raised**: ``label_communities``
catches it per batch and skips that batch (its communities stay unlabeled),
re-raising only if every batch fails. Any non-parse exception (network,
missing config, programming bug) propagates unchanged — those are never
split-retried.
"""
prompt = (
"You are naming clusters in a knowledge graph. For each community below, "
"return a concise 2-5 word plain-language name describing what it is about "
"(e.g. \"Order Management\", \"Payment Flow\", \"Auth Middleware\"). "
"Respond ONLY with a JSON object mapping the community id (as a string) to "
"its name - no prose, no markdown fences.\n\n" + "\n".join(batch_lines)
)
max_tokens = _resolve_max_tokens(min(64 + 24 * len(batch_cids), 8192))
call_kwargs: dict = {"backend": backend, "max_tokens": max_tokens}
if model is not None:
call_kwargs["model"] = model
try:
text = _call_llm(prompt, **call_kwargs)
return _parse_label_response(text, batch_cids)
except (json.JSONDecodeError, ValueError) as exc:
# Parse failure. If we can still split, retry each half on a smaller
# prompt (smaller output → less likely to truncate/mangle). At the base
# case (single community or max depth) re-raise so the caller skips it.
if len(batch_cids) <= 1 or depth >= max_depth:
print(
f"[graphify label] batch of {len(batch_cids)} still unparseable "
f"at depth {depth} (cids={batch_cids[:5]}"
f"{'...' if len(batch_cids) > 5 else ''}): {exc}",
file=sys.stderr,
)
raise
mid = len(batch_cids) // 2
left = _label_batch_with_retry(
batch_cids[:mid], batch_lines[:mid],
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
)
right = _label_batch_with_retry(
batch_cids[mid:], batch_lines[mid:],
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
)
return left | right
def label_communities(
G,
communities,
@@ -2092,24 +2260,10 @@ def label_communities(
end = min(start + batch_size, len(labeled_cids))
batch_lines = lines[start:end]
batch_cids = labeled_cids[start:end]
prompt = (
"You are naming clusters in a knowledge graph. For each community below, "
"return a concise 2-5 word plain-language name describing what it is about "
"(e.g. \"Order Management\", \"Payment Flow\", \"Auth Middleware\"). "
"Respond ONLY with a JSON object mapping the community id (as a string) to "
"its name - no prose, no markdown fences.\n\n" + "\n".join(batch_lines)
)
# 24 tok/community covers 2-5 word JSON entries including id, quotes,
# and punctuation. Cap at 8192 for 16k-context models. Wrapped in
# _resolve_max_tokens so GRAPHIFY_MAX_OUTPUT_TOKENS applies here too (#1200).
max_tokens = _resolve_max_tokens(min(64 + 24 * len(batch_cids), 8192))
try:
call_kwargs = {"backend": backend, "max_tokens": max_tokens}
if model is not None:
call_kwargs["model"] = model
text = _call_llm(prompt, **call_kwargs)
parsed = _parse_label_response(text, batch_cids)
parsed = _label_batch_with_retry(
batch_cids, batch_lines, backend=backend, model=model,
)
labels.update(parsed)
written += len(parsed)
except Exception as exc:
+247
View File
@@ -0,0 +1,247 @@
"""Deterministic package-manifest ingestion (#1377).
Package manifests (``apm.yml``, ``pyproject.toml``, ``go.mod``, ``pom.xml``)
declare a package and its dependencies. Left to the LLM document path, the same
package gets a different file-anchored node id from its own manifest than from
each dependent's dependency reference, so it splits into duplicate nodes. This
module parses manifests deterministically and emits ONE canonical package node
per package -- keyed by NAME via :func:`graphify.ids.make_id` -- plus
``depends_on`` edges, so a package referenced from N manifests collapses to a
single hub node (the dependency stub and the package's own definition node share
the canonical id and merge at build time).
Mirrors ``mcp_ingest``: recognized by filename, routed to the deterministic AST
path (never the LLM), so a manifest is extracted exactly once.
"""
from __future__ import annotations
import re
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
from graphify.ids import make_id
__all__ = ["is_package_manifest_path", "extract_package_manifest", "PACKAGE_MANIFEST_NAMES"]
# manifest filename (lowercased) -> ecosystem tag
PACKAGE_MANIFEST_NAMES: dict[str, str] = {
"apm.yml": "apm",
"apm.yaml": "apm",
"pyproject.toml": "python",
"go.mod": "go",
"pom.xml": "maven",
}
_MAX_MANIFEST_BYTES = 2_000_000 # 2 MB cap — manifests are small; this rejects junk
def is_package_manifest_path(path: Path) -> bool:
"""True if ``path`` is a recognized package manifest (by filename)."""
return path.name.lower() in PACKAGE_MANIFEST_NAMES
def _pkg_id(name: str) -> str:
"""Canonical package node id, keyed by package NAME so every reference to the
same package -- its own manifest and any dependent's dependency line -- maps
to one node."""
return make_id("pkg", name)
def extract_package_manifest(path: Path) -> dict[str, Any]:
"""Parse a package manifest into a canonical package node + ``depends_on`` edges."""
try:
if path.stat().st_size > _MAX_MANIFEST_BYTES:
return {"nodes": [], "edges": [], "error": "manifest too large to index"}
text = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return {"nodes": [], "edges": [], "error": f"manifest read error: {exc}"}
eco = PACKAGE_MANIFEST_NAMES[path.name.lower()]
try:
info = _PARSERS[eco](text)
except Exception as exc: # noqa: BLE001 — a malformed manifest must not abort extraction
return {"nodes": [], "edges": [], "error": f"manifest parse error: {exc}"}
if not info or not info.get("name"):
return {"nodes": [], "edges": []}
name = info["name"]
str_path = str(path)
pkg_nid = _pkg_id(name)
node: dict[str, Any] = {
"id": pkg_nid,
"label": name,
"file_type": "code", # valid schema type; `type` distinguishes packages
"type": "package",
"ecosystem": eco,
"source_file": str_path,
"source_location": "L1",
}
if info.get("version"):
node["version"] = info["version"]
nodes: list[dict] = [node]
edges: list[dict] = []
seen: set[str] = set()
for dep in info.get("deps", []):
if not dep:
continue
dep_nid = _pkg_id(dep)
if dep_nid == pkg_nid or dep_nid in seen:
continue
seen.add(dep_nid)
# The edge targets the dependency's canonical package id. If that package's
# own manifest is in the corpus, the edge resolves to its (single) node; if
# the dependency is external, build_from_json prunes the dangling edge. We
# deliberately do NOT emit a stub node — a stub with an empty source_file
# would risk clobbering the real node's source_file under id-dedup.
edges.append({
"source": pkg_nid,
"target": dep_nid,
"relation": "depends_on",
"context": "dependency",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str_path,
"source_location": "L1",
"weight": 1.0,
})
return {"nodes": nodes, "edges": edges}
# ── per-ecosystem parsers: text -> {"name", "version"?, "deps": [str]} | None ──
def _coerce_deps(value: Any) -> list[str]:
"""A dependency block may be a list of names or a name->spec map."""
if isinstance(value, dict):
return [str(k) for k in value]
if isinstance(value, list):
out: list[str] = []
for item in value:
if isinstance(item, str):
out.append(item)
elif isinstance(item, dict) and item:
out.append(str(next(iter(item))))
return out
return []
def _parse_apm(text: str) -> dict | None:
try:
import yaml
except ImportError:
return _parse_apm_fallback(text)
data = yaml.safe_load(text)
if not isinstance(data, dict):
return None
return {
"name": data.get("name"),
"version": data.get("version"),
"deps": _coerce_deps(data.get("dependencies")),
}
def _parse_apm_fallback(text: str) -> dict | None:
"""Minimal line parser for apm.yml when PyYAML is unavailable: a top-level
``name:`` plus a simple ``dependencies:`` block (list items or a name map)."""
name = None
deps: list[str] = []
in_deps = False
for line in text.splitlines():
if not in_deps:
m = re.match(r'^name:\s*["\']?([^"\'\s#]+)', line)
if m:
name = m.group(1)
continue
if re.match(r'^dependencies:\s*$', line):
in_deps = True
continue
if in_deps:
dm = (re.match(r'^\s*-\s*["\']?([^"\'\s#:]+)', line)
or re.match(r'^\s{2,}([A-Za-z0-9._/@-]+)\s*:', line))
if dm:
deps.append(dm.group(1))
elif re.match(r'^\S', line): # next top-level key ends the block
in_deps = False
return {"name": name, "version": None, "deps": deps} if name else None
def _pep508_name(spec: str) -> str:
"""`requests>=2.0` -> `requests`; `pkg[extra]==1; python_version<'3.9'` -> `pkg`."""
return re.split(r'[\s<>=!~;\[\(]', spec.strip(), maxsplit=1)[0]
def _parse_pyproject(text: str) -> dict | None:
try:
import tomllib as _toml
except ImportError:
try:
import tomli as _toml # type: ignore
except ImportError:
return None
data = _toml.loads(text)
proj = data.get("project", {}) if isinstance(data.get("project"), dict) else {}
poetry = (data.get("tool", {}) or {}).get("poetry", {}) if isinstance(data.get("tool"), dict) else {}
name = proj.get("name") or (poetry.get("name") if isinstance(poetry, dict) else None)
if not name:
return None
deps: list[str] = [_pep508_name(s) for s in (proj.get("dependencies") or []) if isinstance(s, str)]
if isinstance(poetry, dict):
for dep in (poetry.get("dependencies") or {}):
if str(dep).lower() != "python":
deps.append(str(dep))
return {"name": name, "version": proj.get("version") or (poetry.get("version") if isinstance(poetry, dict) else None), "deps": deps}
def _parse_gomod(text: str) -> dict | None:
name = None
deps: list[str] = []
in_block = False
for line in text.splitlines():
s = line.strip()
if name is None:
m = re.match(r'^module\s+(\S+)', s)
if m:
name = m.group(1)
continue
if re.match(r'^require\s*\(', s):
in_block = True
continue
if in_block:
if s.startswith(')'):
in_block = False
continue
dm = re.match(r'^(\S+)\s+v\S+', s)
if dm:
deps.append(dm.group(1))
else:
dm = re.match(r'^require\s+(\S+)\s+v\S+', s)
if dm:
deps.append(dm.group(1))
return {"name": name, "version": None, "deps": deps} if name else None
def _parse_pom(text: str) -> dict | None:
# Drop the default namespace so findtext/findall don't need the {uri} prefix.
text = re.sub(r'\sxmlns="[^"]*"', '', text, count=1)
root = ET.fromstring(text)
aid = root.findtext("artifactId")
gid = root.findtext("groupId")
if not aid:
return None
name = f"{gid}:{aid}" if gid else aid
deps: list[str] = []
for dep in root.findall(".//dependencies/dependency"):
da = dep.findtext("artifactId")
dg = dep.findtext("groupId")
if da:
deps.append(f"{dg}:{da}" if dg else da)
return {"name": name, "version": root.findtext("version"), "deps": deps}
_PARSERS = {
"apm": _parse_apm,
"python": _parse_pyproject,
"go": _parse_gomod,
"maven": _parse_pom,
}
+3 -6
View File
@@ -63,6 +63,7 @@ import unicodedata
from pathlib import Path
from typing import Any
from graphify.ids import make_id as _shared_make_id
from graphify.security import sanitize_label
@@ -376,12 +377,8 @@ def _add_edge(
def _make_id(*parts: str) -> str:
"""Build a stable node ID. Must match extract._make_id's normalisation rules."""
combined = "_".join(p.strip("_.") for p in parts if p)
combined = unicodedata.normalize("NFKC", combined)
cleaned = re.sub(r"[^\w]+", "_", combined, flags=re.UNICODE)
cleaned = re.sub(r"_+", "_", cleaned)
return cleaned.strip("_").casefold()
"""Build a stable node ID via the single shared recipe (#1378)."""
return _shared_make_id(*parts)
def _file_stem(path: Path) -> str:
+9 -3
View File
@@ -464,12 +464,18 @@ def _find_node(G: nx.Graph, label: str) -> list[str]:
for nid, d in G.nodes(data=True):
norm_label = d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower()
bare_label = norm_label.rstrip("()")
label_tokens = " ".join(_search_tokens(d.get("label") or ""))
nid_lower = nid.lower()
if term == norm_label or term == bare_label or term == nid_lower:
if term == norm_label or term == bare_label or term == label_tokens or term == nid_lower:
exact.append(nid)
elif norm_label.startswith(term) or bare_label.startswith(term) or nid_lower.startswith(term):
elif (
norm_label.startswith(term)
or bare_label.startswith(term)
or label_tokens.startswith(term)
or nid_lower.startswith(term)
):
prefix.append(nid)
elif term in norm_label:
elif term in norm_label or term in label_tokens:
substring.append(nid)
return exact + prefix + substring
+6 -3
View File
@@ -382,7 +382,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -435,7 +437,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -589,7 +592,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -592,7 +595,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -382,7 +382,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -435,7 +437,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -589,7 +592,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -592,7 +595,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -382,7 +382,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -435,7 +437,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -589,7 +592,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -592,7 +595,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -592,7 +595,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -377,7 +377,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -430,7 +432,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -584,7 +587,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -592,7 +595,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -383,7 +383,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -436,7 +438,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -590,7 +593,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -381,7 +381,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -434,7 +436,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -588,7 +591,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+6 -3
View File
@@ -407,7 +407,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -460,7 +462,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -614,7 +617,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
+7 -4
View File
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -586,13 +589,13 @@ Both are non-default subcommands. `--update` re-extracts only new or changed fil
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, run the query directly:
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```bash
graphify query "<question>"
```
Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. For that vocab-expansion step, the `--dfs` / `--budget` modes, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+206 -6
View File
@@ -1,6 +1,6 @@
# graphify reference: query, path, explain
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow.
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise.
Two traversal modes - choose based on the question:
@@ -9,9 +9,20 @@ Two traversal modes - choose based on the question:
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
@@ -51,12 +62,108 @@ If the list is empty, say so plainly and stop — do not proceed to traversal.
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
```
Answer using **only** what the graph output contains. Quote `source_location` when citing a specific fact. If the graph lacks enough information, say so - do not hallucinate edges.
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
mode = 'MODE' # 'bfs' or 'dfs'
terms = [t.lower() for t in question.split() if len(t) > 3]
# Find best-matching start nodes
scored = []
for nid, ndata in G.nodes(data=True):
label = ndata.get('label', '').lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
scored.sort(reverse=True)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
print('No matching nodes found for query terms:', terms)
sys.exit(0)
subgraph_nodes = set()
subgraph_edges = []
if mode == 'dfs':
# DFS: follow one path as deep as possible before backtracking.
# Depth-limited to 6 to avoid traversing the whole graph.
visited = set()
stack = [(n, 0) for n in reversed(start_nodes)]
while stack:
node, depth = stack.pop()
if node in visited or depth > 6:
continue
visited.add(node)
subgraph_nodes.add(node)
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, depth + 1))
subgraph_edges.append((node, neighbor))
else:
# BFS: explore all neighbors layer by layer up to depth 3.
frontier = set(start_nodes)
subgraph_nodes = set(start_nodes)
for _ in range(3):
next_frontier = set()
for n in frontier:
for neighbor in G.neighbors(n):
if neighbor not in subgraph_nodes:
next_frontier.add(neighbor)
subgraph_edges.append((n, neighbor))
subgraph_nodes.update(next_frontier)
frontier = next_frontier
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
token_budget = BUDGET # default 2000
char_budget = token_budget * 4
# Score each node by term overlap for ranked output
def relevance(nid):
label = G.nodes[nid].get('label', '').lower()
return sum(1 for t in terms if t in label)
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
for nid in ranked_nodes:
d = G.nodes[nid]
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
output = '\n'.join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
print(output)
"
```
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
@@ -70,13 +177,63 @@ Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with you
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
Replace `NODE_A` and `NODE_B` with the actual concept names. Then explain the path in plain language - what each hop means, why it's significant.
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
b_term = 'NODE_B'
def find_node(term):
term = term.lower()
scored = sorted(
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
return scored[0][1] if scored and scored[0][0] > 0 else None
src = find_node(a_term)
tgt = find_node(b_term)
if not src or not tgt:
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
sys.exit(0)
try:
path = nx.shortest_path(G, src, tgt)
print(f'Shortest path ({len(path)-1} hops):')
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
else:
print(f' {label}')
except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
"
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
After writing the explanation, save it back:
@@ -88,12 +245,55 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
term_lower = term.lower()
# Find best matching node
scored = sorted(
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
if not scored or scored[0][0] == 0:
print(f'No node matching {term!r}')
sys.exit(0)
nid = scored[0][1]
data_n = G.nodes[nid]
print(f'NODE: {data_n.get(\"label\", nid)}')
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
"
```
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
After writing the explanation, save it back:
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -25,5 +25,7 @@ Rules:
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the immediate parent directory + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent. `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
```
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -25,5 +25,7 @@ Rules:
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the immediate parent directory + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent. `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
```
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -25,5 +25,7 @@ Rules:
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the immediate parent directory + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent. `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
```
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -25,5 +25,7 @@ Rules:
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the immediate parent directory + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent. `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
```
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -61,7 +61,9 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
+61 -7
View File
@@ -20,6 +20,48 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)))
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
@@ -28,7 +70,7 @@ graphify query "QUESTION"
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches key terms in the question.
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
@@ -121,21 +163,27 @@ print(output)
"
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries:
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the user's verbatim question, `ANSWER` with your full answer text, and the node list with the labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
---
## For /graphify path
Find the shortest path between two named concepts in the graph.
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -197,7 +245,13 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it.
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
+11 -5
View File
@@ -93,18 +93,24 @@ 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
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
+7 -6
View File
@@ -10,6 +10,7 @@ from pathlib import Path
from collections.abc import Sequence
from typing import Any
from graphify.ids import make_id as _shared_make_id
from graphify.security import sanitize_metadata
@@ -357,12 +358,12 @@ def resolve_cross_file_raw_calls(
def _bash_make_id(*parts: str) -> str:
"""Exact copy of extract._make_id — kept here to avoid an import cycle."""
combined = "_".join(p.strip("_.") for p in parts if p)
combined = unicodedata.normalize("NFKC", combined)
cleaned = re.sub(r"[^\w]+", "_", combined, flags=re.UNICODE)
cleaned = re.sub(r"_+", "_", cleaned)
return cleaned.strip("_").casefold()
"""Bash symbol node ID via the single shared recipe (#1378).
Previously an inline copy to dodge an import cycle; ``graphify.ids`` is
dependency-free, so it can be imported directly.
"""
return _shared_make_id(*parts)
def _bash_file_stem(rel_path: Path) -> str:
+1 -1
View File
@@ -549,7 +549,7 @@ def emit_html(
) -> str:
# Escape </script> sequences so embedded JSON cannot break out of the
# <script> tag, and HTML-escape values that land in <title>/<h1>.
data_json = json.dumps(tree, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
data_json = json.dumps(tree, ensure_ascii=True, separators=(",", ":")).replace("</", "<\\/")
return _HTML_TEMPLATE.format(
title=_html.escape(title),
header=_html.escape(header),
+72 -11
View File
@@ -205,6 +205,36 @@ def _report_root_label(watch_path: Path) -> str:
return Path.cwd().name if watch_path == Path(".") else str(watch_path)
def _is_relative_to(path: Path, root: Path) -> bool:
try:
path.relative_to(root)
return True
except ValueError:
return False
def _changed_path_candidates(raw: Path, *, change_root: Path, watch_root: Path) -> list[Path]:
"""Return plausible absolute locations for a hook-provided changed path.
Git hooks pass paths relative to the repository root. Watch callers may
also pass paths relative to the watched root. Keep both interpretations so
a graph rooted at ``src`` accepts ``src/app.py`` and ``app.py``.
"""
if raw.is_absolute():
return [raw.resolve()]
candidates: list[Path] = []
seen: set[str] = set()
for base in (change_root, watch_root):
cand = (base / raw).resolve()
key = os.fspath(cand)
if key in seen:
continue
seen.add(key)
candidates.append(cand)
return candidates
def _relativize_source_files(payload: dict, root: Path) -> None:
for bucket in ("nodes", "edges", "hyperedges"):
for item in payload.get(bucket, []):
@@ -477,18 +507,47 @@ def _rebuild_code(
# extract only changed-and-still-existing files. Deleted paths are
# tracked separately so their stale nodes can be evicted below.
deleted_paths: set[str] = set()
def _add_deleted_source(path: Path) -> None:
for root in (project_root, watch_root):
deleted_paths.add(_nsf(str(path), str(root)) or str(path))
if changed_paths is not None:
code_set = {p.resolve() for p in code_files}
wanted: list[Path] = []
change_root = Path.cwd().resolve()
for raw in changed_paths:
cand = (watch_root / raw).resolve() if not raw.is_absolute() else raw.resolve()
if cand.exists() and cand in code_set:
wanted.append(cand)
else:
# File was deleted, renamed away, or filtered out by detect
# (e.g. .gitignore, vendored). Either way, evict any
# preserved nodes that still claim this source path.
deleted_paths.add(_nsf(str(cand), str(project_root)) or str(cand))
candidates = _changed_path_candidates(
raw,
change_root=change_root,
watch_root=watch_root,
)
tracked = next((cand for cand in candidates if cand.exists() and cand in code_set), None)
if tracked is not None:
if tracked not in wanted:
wanted.append(tracked)
continue
existing_in_root = next(
(
cand for cand in candidates
if cand.exists() and _is_relative_to(cand, watch_root)
),
None,
)
if existing_in_root is not None:
# The path exists under the watched root but detect filtered
# it out. Evict any stale nodes that still claim it.
_add_deleted_source(existing_in_root)
continue
deleted_in_root = next(
(cand for cand in candidates if _is_relative_to(cand, watch_root)),
None,
)
if deleted_in_root is not None:
# File was deleted or renamed away inside the watched root.
# Evict preserved nodes that still claim this source path.
_add_deleted_source(deleted_in_root)
if not wanted and not deleted_paths:
print("[graphify watch] No tracked code files in change set - skipping rebuild.")
return True
@@ -522,7 +581,8 @@ def _rebuild_code(
evict_sources: set[str] = set(deleted_paths)
if changed_paths is not None:
for p in extract_targets:
evict_sources.add(_nsf(str(p), str(project_root)) or str(p))
for root in (project_root, watch_root):
evict_sources.add(_nsf(str(p), str(root)) or str(p))
else:
# Full re-extraction: reconcile against current code files to
# evict nodes from files deleted since the last run (#1007).
@@ -587,9 +647,10 @@ def _rebuild_code(
# Dedupe parallel edges (the clustered path's DiGraph collapses them implicitly);
# without it, --no-cluster + repeated `update` accumulate duplicates and edge
# counts diverge across build modes (#1317).
from graphify.build import dedupe_edges as _dedupe_edges
from graphify.build import dedupe_edges as _dedupe_edges, dedupe_nodes as _dedupe_nodes
candidate_graph_data = {
**{k: v for k, v in result.items() if k != "edges"},
**{k: v for k, v in result.items() if k not in ("edges", "nodes")},
"nodes": _dedupe_nodes(result.get("nodes", [])),
"links": _dedupe_edges(result.get("edges", [])),
}
candidate_graph_text = _json_text(candidate_graph_data)
+4 -4
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.8.40"
version = "0.8.43"
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" }
@@ -51,14 +51,14 @@ Issues = "https://github.com/safishamsi/graphify/issues"
mcp = ["mcp"]
neo4j = ["neo4j"]
falkordb = ["falkordb"]
pdf = ["pypdf", "markdownify"]
pdf = ["pypdf>=6.12.0", "markdownify"]
watch = ["watchdog"]
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"]
video = ["faster-whisper; python_version >= '3.11'", "yt-dlp>=2026.6.9"]
kimi = ["openai", "tiktoken"]
ollama = ["openai"]
bedrock = ["boto3"]
@@ -72,7 +72,7 @@ sql = ["tree-sitter-sql"]
# avoids breaking the default `uv tool install graphifyy` for everyone (#1104).
dm = ["tree-sitter-dm"]
terraform = ["tree-sitter-hcl"]
all = ["mcp", "neo4j", "falkordb", "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"]
all = ["mcp", "neo4j", "falkordb", "pypdf>=6.12.0", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper; python_version >= '3.11'", "yt-dlp>=2026.6.9", "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"
+13
View File
@@ -0,0 +1,13 @@
@{
RootModule = 'MyModule.psm1'
ModuleVersion = '1.0.0'
GUID = 'aaaabbbb-cccc-dddd-eeee-ffffffffffff'
Author = 'Test Author'
Description = 'A sample module manifest for graphify tests.'
NestedModules = @('Helpers.psm1', 'Logger.psm1')
RequiredModules = @(
'PSReadLine',
@{ ModuleName = 'Pester'; ModuleVersion = '5.0' }
)
FunctionsToExport = @('Get-Data', 'Process-Items')
}
+10
View File
@@ -0,0 +1,10 @@
Import-Module Foo
Import-Module -Name Bar.psm1
. ./Shared.psm1
. .\Utils.ps1
function Invoke-Main {
Import-Module InnerMod
. ./InnerShared.psm1
Get-Data
}
+21
View File
@@ -145,6 +145,27 @@ def test_resolve_seed_decorated_query_matches_bare_label():
assert resolve_seed(graph, "Foo()") == "a"
def test_resolve_seed_matches_unicode_normalized_label():
import unicodedata
from graphify.affected import resolve_seed
graph = nx.DiGraph()
graph.add_node("a", label="Auditoría", source_file="pkg/auditoria.py")
assert resolve_seed(graph, unicodedata.normalize("NFD", "Auditoría")) == "a"
def test_resolve_seed_preserves_distinct_accents():
from graphify.affected import resolve_seed
graph = nx.DiGraph()
graph.add_node("a", label="resume", source_file="pkg/resume.py")
graph.add_node("b", label="résumé", source_file="pkg/resume_accented.py")
assert resolve_seed(graph, "resume") == "a"
def test_resolve_seed_bare_name_tie_still_returns_none():
from graphify.affected import resolve_seed
+119
View File
@@ -0,0 +1,119 @@
from __future__ import annotations
from pathlib import Path
import pytest
from graphify.extract import (
extract,
_api_normalize_path,
_api_verbs_compatible,
_api_path_is_specific,
)
# ── path normalization (unit) ───────────────────────────────────────────────
def test_param_styles_normalize_equal():
# Flask, FastAPI/Spring, Express/React, and a JS template literal must all
# canonicalize to the same path so a client matches its route.
forms = [
"/api/users/<int:id>", # Flask
"/api/users/{id}", # FastAPI / Spring
"/api/users/:id", # Express / React
"/api/users/${id}", # JS template
"/api/users/42", # concrete numeric id
"https://host/api/users/7?x=1#f", # scheme/host/query/fragment stripped
]
norms = {_api_normalize_path(f) for f in forms}
assert norms == {"/api/users/{}"}
def test_specificity_guard():
assert not _api_path_is_specific("/")
assert not _api_path_is_specific("/{}")
assert _api_path_is_specific("/api/users/{}")
def test_verb_compatibility():
assert _api_verbs_compatible("GET", "GET")
assert _api_verbs_compatible("ANY", "POST") # fetch/route default
assert not _api_verbs_compatible("GET", "POST")
# ── end-to-end resolution ───────────────────────────────────────────────────
def _write(p: Path, text: str) -> Path:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text, encoding="utf-8")
return p
def _api_edges(result: dict) -> set[tuple[str, str]]:
by_id = {n["id"]: n.get("label", "") for n in result["nodes"]}
return {
(by_id.get(e["source"], ""), by_id.get(e["target"], ""))
for e in result["edges"]
if e.get("resolution") == "api_contract"
}
def _two_service_fixture(base: Path):
_write(base / "frontend/src/api.ts",
"export async function loadUser(id: number) {\n"
" const res = await fetch(`/api/users/${id}`);\n"
" return res.json();\n"
"}\n\n"
"export async function createUser(data: any) {\n"
" return axios.post('/api/users', data);\n"
"}\n")
_write(base / "backend/app.py",
"from flask import Flask\napp = Flask(__name__)\n\n"
"@app.get('/api/users/<int:id>')\n"
"def get_user(id):\n return {'id': id}\n\n"
"@app.post('/api/users')\n"
"def create_user():\n return {'created': True}\n")
return sorted([p for p in base.rglob("*") if p.suffix in (".ts", ".py")])
def test_cross_language_api_edges_resolve(tmp_path, monkeypatch):
monkeypatch.setenv("GRAPHIFY_API_CONTRACT_EDGES", "1")
files = _two_service_fixture(tmp_path / "src")
result = extract(files, cache_root=tmp_path / "src")
edges = _api_edges(result)
assert ("loadUser()", "get_user()") in edges # GET /api/users/{}
assert ("createUser()", "create_user()") in edges # POST /api/users
def test_api_edges_off_by_default(tmp_path, monkeypatch):
monkeypatch.delenv("GRAPHIFY_API_CONTRACT_EDGES", raising=False)
files = _two_service_fixture(tmp_path / "src")
result = extract(files, cache_root=tmp_path / "src")
assert _api_edges(result) == set()
def test_same_file_call_and_route_not_linked(tmp_path, monkeypatch):
# A fetch and a route in the SAME file are not an API contract across services.
monkeypatch.setenv("GRAPHIFY_API_CONTRACT_EDGES", "1")
_write(tmp_path / "src/app.py",
"from flask import Flask\napp = Flask(__name__)\n\n"
"@app.get('/api/ping')\n"
"def ping():\n return 'ok'\n\n"
"def caller():\n return requests.get('/api/ping')\n")
files = sorted((tmp_path / "src").rglob("*.py"))
result = extract(files, cache_root=tmp_path / "src")
assert _api_edges(result) == set()
def test_ambiguous_route_path_not_linked(tmp_path, monkeypatch):
# Same path served by two different backend files -> ambiguous -> skip.
monkeypatch.setenv("GRAPHIFY_API_CONTRACT_EDGES", "1")
_write(tmp_path / "src/frontend/c.ts",
"function go() { return fetch('/api/data'); }\n")
_write(tmp_path / "src/svcA/a.py",
"@app.get('/api/data')\ndef a():\n return 1\n")
_write(tmp_path / "src/svcB/b.py",
"@app.get('/api/data')\ndef b():\n return 2\n")
files = sorted([p for p in (tmp_path / "src").rglob("*") if p.suffix in (".ts", ".py")])
result = extract(files, cache_root=tmp_path / "src")
assert _api_edges(result) == set()
+134 -1
View File
@@ -2,7 +2,7 @@ import json
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.build import build_from_json, build, build_merge, edge_data, edge_datas, dedupe_edges
from graphify.build import build_from_json, build, build_merge, edge_data, edge_datas, dedupe_edges, dedupe_nodes
FIXTURES = Path(__file__).parent / "fixtures"
@@ -32,6 +32,21 @@ def test_dedupe_edges_is_idempotent():
assert len(once) == 1
assert len(twice) == 1
def test_dedupe_nodes_collapses_by_id_last_wins():
# #1327: a shared module anchor is emitted once per importing file; the
# --no-cluster raw writer must collapse same-id node dicts (#1317).
nodes = [
{"id": "foundation", "label": "Foundation", "type": "module", "source_file": "A.swift"},
{"id": "akit", "label": "AKit", "file_type": "code"},
{"id": "foundation", "label": "Foundation", "type": "module", "source_file": "B.swift"},
]
out = dedupe_nodes(nodes)
ids = [n["id"] for n in out]
assert ids == ["foundation", "akit"] # first-appearance order
# last writer wins on attributes
assert next(n for n in out if n["id"] == "foundation")["source_file"] == "B.swift"
def load_extraction():
return json.loads((FIXTURES / "extraction.json").read_text())
@@ -93,6 +108,23 @@ def test_source_file_backslash_normalized():
assert sources == {"src/middleware/auth.py"}
def test_edge_missing_source_file_backfilled_from_node():
"""#1279: a semantic/LLM edge lacking source_file must inherit it from its
source node rather than reach graph.json with no file reference."""
extraction = {
"nodes": [
{"id": "n1", "label": "A", "file_type": "concept", "source_file": "docs/a.md"},
{"id": "n2", "label": "B", "file_type": "concept", "source_file": "docs/b.md"},
],
# No source_file on the edge (as LLM output sometimes omits it).
"edges": [{"source": "n1", "target": "n2", "relation": "relates_to", "confidence": "INFERRED"}],
"input_tokens": 0, "output_tokens": 0,
}
G = build_from_json(extraction)
sf = edge_data(G, "n1", "n2").get("source_file")
assert sf == "docs/a.md" # backfilled from the source node
def test_build_merges_multiple_extractions():
ext1 = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"}],
"edges": [], "input_tokens": 0, "output_tokens": 0}
@@ -534,6 +566,107 @@ def test_build_merge_prune_windows_backslash_paths(tmp_path):
assert "parse_date" not in node_labels, "node should be pruned even with backslash path"
def test_build_merge_replaces_changed_file_stale_edges(tmp_path):
"""Re-extracting a CHANGED file must REPLACE its prior nodes/edges, not
accumulate them. build_merge previously only grew the graph, so an edge that
disappeared from a file's new version survived forever (only exact-duplicate
edges collapsed). The new-chunk source_file may be an absolute win32 path
while the stored graph keeps relative posix — both forms must match."""
import networkx as nx
root = tmp_path / "corpus"
root.mkdir()
graph_path = tmp_path / "graph.json"
# First build: changed.md contributed A, B and edge A->B; keep.md is unrelated.
chunk0 = {"nodes": [
{"id": "A", "label": "A", "file_type": "document", "source_file": "changed.md"},
{"id": "B", "label": "B", "file_type": "document", "source_file": "changed.md"},
{"id": "K", "label": "K", "file_type": "document", "source_file": "keep.md"},
], "edges": [
{"source": "A", "target": "B", "relation": "references", "confidence": "EXTRACTED",
"source_file": "changed.md", "weight": 1.0},
{"source": "K", "target": "A", "relation": "references", "confidence": "EXTRACTED",
"source_file": "keep.md", "weight": 1.0},
]}
G0 = build([chunk0], dedup=False)
graph_path.write_text(json.dumps(nx.node_link_data(G0, edges="edges")), encoding="utf-8")
# changed.md edited: re-extraction now yields A, C and edge A->C (B dropped).
# source_file arrives as an absolute win32-style path (as detect emits on Windows).
abs_changed = str(root / "changed.md").replace("/", "\\")
new_chunk = {"nodes": [
{"id": "A", "label": "A", "file_type": "document", "source_file": abs_changed},
{"id": "C", "label": "C", "file_type": "document", "source_file": abs_changed},
], "edges": [
{"source": "A", "target": "C", "relation": "references", "confidence": "EXTRACTED",
"source_file": abs_changed, "weight": 1.0},
]}
G1 = build_merge([new_chunk], graph_path, dedup=False, root=root)
labels = {d["label"] for _, d in G1.nodes(data=True)}
edges = {(u, v) for u, v in G1.edges()}
# Stale contribution from the old version of changed.md is gone.
assert "B" not in labels, "stale node from changed file's old version must be dropped"
assert ("A", "B") not in edges and ("B", "A") not in edges, "stale edge must be dropped"
# Fresh contribution is present.
assert "C" in labels, "re-extracted node must be present"
assert ("A", "C") in edges, "re-extracted edge must be present"
# An unchanged file is untouched.
assert "K" in labels, "unchanged file's node must survive"
assert ("K", "A") in edges, "unchanged file's edge must survive"
def test_build_merge_root_collapses_convention_drift(tmp_path):
"""Skill contract: the extraction subagent must emit source_file as the
verbatim path from FILE_LIST AND the caller must pass root= (the build root).
Then build_merge canonicalizes the new chunk to the same relative base as the
stored graph, so re-extraction REPLACES the prior node (incl. stale nodes for
that file) instead of accumulating a duplicate. Without root, a drifted
relative base (e.g. a bare basename from a different run) mismatches and the
graph duplicates. Engine is unchanged — this pins the prompt/root contract."""
import networkx as nx
root = tmp_path
graph_path = tmp_path / "graphify-out" / "graph.json"
graph_path.parent.mkdir(parents=True)
# Stored graph: nested project-relative convention + a STALE node for the same
# file that the re-extraction no longer emits.
stored = {"nodes": [
{"id": "wiki_overview_overview", "label": "Overview", "file_type": "document",
"source_file": "docs/wiki/overview.md"},
{"id": "wiki_overview_stale", "label": "Stale", "file_type": "document",
"source_file": "docs/wiki/overview.md"},
], "edges": []}
G0 = build([stored], dedup=False)
saved = json.dumps(nx.node_link_data(G0, edges="edges"))
graph_path.write_text(saved, encoding="utf-8")
# BUG: --update drifted to a bare basename and no root was passed. Different
# base -> source_file replace misses -> stale + duplicate both survive.
drift = {"nodes": [
{"id": "overview_overview", "label": "Overview", "file_type": "document",
"source_file": "overview.md"},
], "edges": []}
G_bug = build_merge([drift], graph_path, dedup=False)
assert G_bug.number_of_nodes() == 3, "mismatched base must NOT replace -> stale+dup remain"
# FIX: subagent emits the verbatim path; caller passes root (the build root).
graph_path.write_text(saved, encoding="utf-8")
abs_overview = str(root / "docs" / "wiki" / "overview.md")
fixed = {"nodes": [
{"id": "wiki_overview_overview", "label": "Overview", "file_type": "document",
"source_file": abs_overview},
], "edges": []}
G_ok = build_merge([fixed], graph_path, prune_sources=None, dedup=False, root=root)
assert G_ok.number_of_nodes() == 1, "verbatim path + root must collapse to one node"
assert "wiki_overview_stale" not in G_ok, "stale node for the re-extracted file must be dropped"
assert G_ok.nodes["wiki_overview_overview"]["source_file"] == "docs/wiki/overview.md", \
"new chunk must be canonicalized to the stored relative base"
def test_build_merge_rejects_oversized_existing_graph(monkeypatch, tmp_path):
"""#F4: build_merge must refuse to read an existing graph.json that
exceeds the size cap, rather than json.loads-ing it into memory."""
+96
View File
@@ -268,3 +268,99 @@ def test_prefix_guard_fires_for_extension_pairs():
assert hi.startswith(lo) and hi != lo, (
f"Prefix guard should fire for ({a!r}, {b!r}) but did not"
)
# ── #1284: numbered siblings + cross-file file-anchored boilerplate ──────────
def test_numeric_tokens_differ_helper():
"""_numeric_tokens_differ compares digit runs as zero-padding-insensitive
multisets (#1284)."""
from graphify.dedup import _numeric_tokens_differ
assert _numeric_tokens_differ("adr 0011 d5 pipeline placement", "adr 0013 d4 pipeline placement")
assert _numeric_tokens_differ("3 1 product goals", "1 1 product goals")
assert _numeric_tokens_differ("code block3", "code block13")
assert not _numeric_tokens_differ("phase 09 overview", "phase 9 overview") # zero-padding
assert not _numeric_tokens_differ("module layout wave 3", "module layouts wave 3")
assert not _numeric_tokens_differ("graph extractor", "graph extractar") # digitless
def test_dedup_does_not_merge_numbered_siblings():
"""Long labels differing only in embedded numbers (ADR/section/issue ids)
must not merge — numbered siblings, not duplicates (#1284)."""
nodes = [
{"id": "n1", "label": "Pipeline placement — 4 call sites (ADR 0013 D4)",
"file_type": "document", "source_file": "docs/index-activity.md"},
{"id": "n2", "label": "Pipeline placement — 4 call sites (ADR 0011 §D5)",
"file_type": "document", "source_file": "docs/schema-matcher.md"},
]
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2
def test_dedup_does_not_merge_crossfile_rationale_boilerplate():
"""Rationale nodes are file-anchored like code (#1205): parallel modules'
boilerplate docstrings differing by one word must not merge (#1284)."""
boiler = ("Django app config for {}. No business logic here. "
"Domain services live in services.py and adapters in providers.")
nodes = [
{"id": "r1", "label": boiler.format("apps.platform.cards"),
"file_type": "rationale", "source_file": "apps/platform/cards/apps.py"},
{"id": "r2", "label": boiler.format("apps.platform.cores"),
"file_type": "rationale", "source_file": "apps/platform/cores/apps.py"},
]
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2
def test_dedup_does_not_merge_crossfile_document_headings():
"""Document nodes are file-anchored too: near-identical headings in different
files are distinct sections, not duplicates (#1284, extends the rationale guard)."""
nodes = [
{"id": "d1", "label": "Getting Started Installation Guide",
"file_type": "document", "source_file": "docs/a.md"},
{"id": "d2", "label": "Getting Started Installation Setup",
"file_type": "document", "source_file": "docs/b.md"},
]
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2
def test_dedup_still_merges_samefile_rationale_duplicates():
"""The file-anchored guard only blocks cross-file pairs — near-identical
rationale duplicates within one file still merge (#1284 non-regression)."""
nodes = [
{"id": "r1", "label": "Counts-only metrics export, a read-only aggregation service.",
"file_type": "rationale", "source_file": "apps/schemas/metrics.py"},
{"id": "r2", "label": "Counts-only metrics export, the read-only aggregation service.",
"file_type": "rationale", "source_file": "apps/schemas/metrics.py"},
]
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 1
# ── #1243: JaroWinkler prefix-bonus over-merge (cross-file) ──────────────────
def test_dedup_does_not_merge_crossfile_shared_prefix_divergence():
"""Cross-file labels sharing a long prefix but diverging in a distinguishing
token ("…jest native" vs "…react native") get JaroWinkler's prefix bonus past
threshold but are distinct entities; scoring them on plain Jaro blocks the
merge (#1243)."""
nodes = [
{"id": "p1", "label": "testing library jest native",
"file_type": "concept", "source_file": "pkg-a/package.json"},
{"id": "p2", "label": "testing library react native",
"file_type": "concept", "source_file": "pkg-b/package.json"},
]
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2
def test_dedup_still_merges_crossfile_true_duplicates():
"""The #1243 guard only drops the prefix bonus — a genuine cross-file
duplicate (high similarity on Jaro alone) must still merge."""
nodes = [
{"id": "g1", "label": "GraphExtractor", "file_type": "concept", "source_file": "a.md"},
{"id": "g2", "label": "Graph Extractor", "file_type": "concept", "source_file": "b.md"},
]
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 1
+30 -7
View File
@@ -15,6 +15,10 @@ def test_classify_powershell_module():
# #1315: .psm1 modules were never indexed (CODE_EXTENSIONS gap).
assert classify_file(Path("Utils.psm1")) == FileType.CODE
def test_classify_powershell_manifest():
# #1331: .psd1 manifests must be classified as CODE so the manifest extractor runs.
assert classify_file(Path("MyModule.psd1")) == FileType.CODE
def test_classify_markdown():
assert classify_file(Path("README.md")) == FileType.DOCUMENT
@@ -918,19 +922,38 @@ def test_gitignore_fallback_when_no_graphifyignore(tmp_path):
assert not any("generated" in f for f in code)
def test_graphifyignore_takes_precedence_over_gitignore(tmp_path):
"""When both exist, .graphifyignore is used and .gitignore is ignored (#945)."""
def test_graphifyignore_and_gitignore_are_merged(tmp_path):
"""When both exist, their patterns are MERGED — a file excluded only by
.gitignore stays excluded even though .graphifyignore says nothing about it
(#1363). Previously the presence of a .graphifyignore silently disabled the
dir's .gitignore, leaking gitignore-only secrets into the graph."""
(tmp_path / ".git").mkdir()
# .gitignore would exclude main.py; .graphifyignore excludes only other.py
(tmp_path / ".gitignore").write_text("main.py\n")
(tmp_path / ".graphifyignore").write_text("other.py\n")
(tmp_path / ".gitignore").write_text("main.py\n") # gitignore-only exclusion
(tmp_path / ".graphifyignore").write_text("other.py\n") # says nothing about main.py
(tmp_path / "main.py").write_text("x = 1")
(tmp_path / "other.py").write_text("x = 2")
(tmp_path / "keep.py").write_text("x = 3")
result = detect(tmp_path)
code = result["files"]["code"]
assert any("main.py" in f for f in code) # gitignore NOT applied
assert not any("other.py" in f for f in code) # graphifyignore IS applied
assert not any("main.py" in f for f in code) # gitignore STILL applied (merged)
assert not any("other.py" in f for f in code) # graphifyignore applied
assert any("keep.py" in f for f in code) # neither excludes it
def test_graphifyignore_negation_overrides_gitignore(tmp_path):
""".graphifyignore is evaluated after .gitignore, so a `!` negation in it can
re-include a file the .gitignore excluded (last-match-wins, #1363)."""
(tmp_path / ".git").mkdir()
(tmp_path / ".gitignore").write_text("*.py\n") # exclude all .py
(tmp_path / ".graphifyignore").write_text("!keep.py\n") # but rescue keep.py
(tmp_path / "main.py").write_text("x = 1")
(tmp_path / "keep.py").write_text("x = 2")
result = detect(tmp_path)
code = result["files"]["code"]
assert any("keep.py" in f for f in code) # rescued by graphifyignore negation
assert not any("main.py" in f for f in code) # still excluded
# Regression tests for #947 - .worktrees/ skipped and --exclude flag
+13
View File
@@ -180,6 +180,19 @@ def test_to_canvas_file_paths_relative_to_vault():
assert node["file"].endswith(".md")
def test_to_canvas_no_communities_still_populates():
"""#1324: empty communities (e.g. --no-cluster builds) on a populated graph
must NOT produce the 32-byte empty `{"nodes": [], "edges": []}` shell."""
G = make_graph()
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.canvas"
to_canvas(G, {}, str(out)) # no community data — the bug condition
data = json.loads(out.read_text())
assert len(data["nodes"]) >= G.number_of_nodes()
assert len(data["edges"]) >= 1
assert out.stat().st_size > 32
# ── Issue #834: backup_if_protected ──────────────────────────────────────────
def test_backup_no_graph_json(tmp_path):
+95
View File
@@ -0,0 +1,95 @@
"""Drift guard for the node-ID spec shown to LLM semantic subagents.
`tools/skillgen/fragments/references/shared/extraction-spec.md` (and the per-host
copies skillgen renders from it) tell the subagents how to build node IDs, with
worked examples like::
`src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`
Those examples are the LLM's ground truth, and they must reproduce exactly what
the AST extractor emits (`extract._file_stem` + `extract._make_id`) or the two
producers generate different IDs for the same symbol and the graph splits it into
disconnected ghost nodes — the bug class the prose itself warns about
(#811/#550/#1033/#1104).
The prose is hand-maintained, so it can silently drift from the code. This test
parses every example straight out of the shipped specs and asserts the real
functions reproduce each one. It fails if the spec examples are edited to a wrong
value, OR if the ID functions change so the documented examples no longer hold.
"""
import re
from pathlib import Path
import pytest
from graphify.extract import _file_stem, _make_id
REPO_ROOT = Path(__file__).resolve().parents[1]
# `path` + `entity` → `id` (arrow is U+2192). Backtick-delimited so prose around
# the examples never leaks in.
_EXAMPLE_RE = re.compile(r"`([^`]+)`\s*\+\s*`([^`]+)`\s*→\s*`([^`]+)`")
def _spec_files() -> list[Path]:
roots = [REPO_ROOT / "graphify" / "skills", REPO_ROOT / "tools" / "skillgen" / "fragments"]
files: list[Path] = []
for root in roots:
for p in root.rglob("extraction-spec.md"):
# build/ is a packaging artifact; expected/ is skillgen's own golden
# output and is already covered by `skillgen --check`.
if "/build/" in p.as_posix() or "/expected/" in p.as_posix():
continue
files.append(p)
return sorted(files)
def _examples() -> list[tuple[Path, str, str, str]]:
out: list[tuple[Path, str, str, str]] = []
for f in _spec_files():
text = f.read_text(encoding="utf-8")
for path, entity, expected in _EXAMPLE_RE.findall(text):
out.append((f, path, entity, expected))
return out
def _ast_symbol_id(path: str, entity: str) -> str:
"""Reproduce the symbol ID the AST extractor emits for a file + symbol, using
the real production helpers (not a re-implementation)."""
return _make_id(_file_stem(Path(path)), entity)
def test_spec_files_are_discoverable():
"""Guard the guard: if the spec moves or the example format changes so nothing
parses, fail loudly rather than passing vacuously."""
files = _spec_files()
assert files, "no extraction-spec.md files found — did the skills tree move?"
examples = _examples()
assert len(examples) >= 13, (
f"expected the documented node-ID examples across host specs, parsed only "
f"{len(examples)} — the example format may have changed"
)
@pytest.mark.parametrize(
"path,entity,expected",
[(p, e, x) for (_f, p, e, x) in _examples()],
ids=[f"{f.parent.parent.name}:{p}+{e}" for (f, p, e, x) in _examples()],
)
def test_spec_node_id_examples_match_ast_extractor(path, entity, expected):
got = _ast_symbol_id(path, entity)
assert got == expected, (
f"node-ID spec drift: spec says `{path}` + `{entity}` → `{expected}`, but "
f"extract._make_id(_file_stem(...), ...) produces `{got}`. Update the spec "
f"examples and the ID functions together."
)
def test_cautionary_wrong_forms_are_actually_wrong():
"""The canonical spec warns against the filename-only and full-path ID forms.
Lock those anti-examples to the code too, so the warning can't go stale."""
correct = _ast_symbol_id("src/auth/session.py", "ValidateToken")
assert correct == "auth_session_validatetoken"
# filename-only (drops the parent dir) and full-path (keeps every segment)
assert _make_id("session", "ValidateToken") != correct
assert _make_id("src", "auth", "session", "ValidateToken") != correct
+165
View File
@@ -0,0 +1,165 @@
from __future__ import annotations
from pathlib import Path
import pytest
from graphify import llm
from graphify.file_slice import (
FileSlice,
bisect_slice,
expand_oversized_files,
is_splittable_text,
read_slice_text,
slice_boundaries,
unit_path,
)
# ── slice_boundaries: coverage + bounds invariants ──────────────────────────
def test_slice_boundaries_small_text_is_one_range():
text = "short doc"
assert slice_boundaries(text, 100) == [(0, len(text))]
@pytest.mark.parametrize("max_chars", [50, 100, 500, 1000])
def test_slice_boundaries_full_coverage_and_bounds(max_chars):
text = ("# Heading\n\n" + "lorem ipsum " * 40 + "\n\n") * 20
bounds = slice_boundaries(text, max_chars)
# contiguous, gap-free, non-overlapping, covering the whole text
assert bounds[0][0] == 0
assert bounds[-1][1] == len(text)
for (s0, e0), (s1, e1) in zip(bounds, bounds[1:]):
assert e0 == s1
# concatenation reproduces the text exactly (no dropped content)
assert "".join(text[s:e] for s, e in bounds) == text
# every slice respects the budget
assert all((e - s) <= max_chars for s, e in bounds)
def test_slice_boundaries_single_huge_line_still_progresses():
# No newline at all → must hard-cut and still cover everything.
text = "x" * 5000
bounds = slice_boundaries(text, 1000)
assert "".join(text[s:e] for s, e in bounds) == text
assert all((e - s) <= 1000 for s, e in bounds)
def test_slice_boundaries_prefers_heading_boundary():
a = "# A\n" + "a" * 30 + "\n"
b = "# B\n" + "b" * 30 + "\n"
text = a + b
bounds = slice_boundaries(text, len(a) + 5) # forces a split near the A/B seam
# the second slice should start at the "# B" heading
second_start = bounds[1][0]
assert text[second_start:second_start + 3] == "# B"
# ── expand_oversized_files ──────────────────────────────────────────────────
def _write(p: Path, text: str) -> Path:
p.write_text(text, encoding="utf-8")
return p
def test_expand_small_file_stays_whole(tmp_path):
f = _write(tmp_path / "small.md", "# Tiny\n\nhi\n")
units = expand_oversized_files([f], max_chars=1000)
assert units == [f]
def test_expand_oversized_markdown_is_sliced_with_full_coverage(tmp_path):
text = ("# Section\n\n" + "word " * 200 + "\n\n") * 30
f = _write(tmp_path / "big.md", text)
units = expand_oversized_files([f], max_chars=2000)
slices = [u for u in units if isinstance(u, FileSlice)]
assert len(slices) >= 2
assert all(isinstance(u, FileSlice) for u in units)
# slices reconstruct the whole file
assert "".join(read_slice_text(s) for s in slices) == text
assert all((s.end - s.start) <= 2000 for s in slices)
# every slice points back at the parent file (anti-fragmentation)
assert all(s.path == f for s in slices)
assert slices[0].total == len(slices)
def test_expand_does_not_slice_code_even_when_oversized(tmp_path):
f = _write(tmp_path / "mod.py", "x = 1\n" * 6000) # >> max_chars but code
assert not is_splittable_text(f)
units = expand_oversized_files([f], max_chars=2000)
assert units == [f] # stays whole — code needs whole-symbol context
def test_expand_unreadable_file_passes_through(tmp_path):
missing = tmp_path / "nope.md"
units = expand_oversized_files([missing], max_chars=10)
assert units == [missing]
# ── anti-fragmentation: slices share one source_file in the prompt ──────────
def test_read_files_keys_every_slice_to_parent_path(tmp_path):
import re
text = ("# H\n\n" + "lorem " * 300 + "\n\n") * 20
f = _write(tmp_path / "doc.md", text)
units = expand_oversized_files([f], max_chars=llm._FILE_CHAR_CAP)
slices = [u for u in units if isinstance(u, FileSlice)]
assert len(slices) >= 2
prompt = llm._read_files(units, tmp_path)
rels = re.findall(r'<untrusted_source path="([^"]+)"', prompt)
# one block per slice, all pointing at the same parent path
assert rels == ["doc.md"] * len(slices)
# ── unit helpers, estimation, partition, packing ────────────────────────────
def test_unit_path_resolves_slice_and_path(tmp_path):
f = tmp_path / "a.md"
fs = FileSlice(path=f, start=0, end=5, index=0, total=1)
assert unit_path(fs) == f
assert unit_path(f) == f
def test_estimate_tokens_for_slice_scales_with_range(tmp_path):
f = _write(tmp_path / "a.md", "z" * 10_000)
small = FileSlice(f, 0, 100, 0, 2)
big = FileSlice(f, 0, 8000, 1, 2)
assert llm._estimate_file_tokens(small) < llm._estimate_file_tokens(big)
def test_partition_keeps_slices_as_text(tmp_path):
f = tmp_path / "a.md"
fs = FileSlice(f, 0, 5, 0, 1)
img = tmp_path / "pic.png"
text_units, image_files = llm._partition_semantic_files([fs, img])
assert fs in text_units
assert image_files == [img]
def test_pack_chunks_handles_slices(tmp_path):
text = ("# H\n\n" + "word " * 300 + "\n\n") * 20
f = _write(tmp_path / "big.md", text)
units = expand_oversized_files([f], max_chars=llm._FILE_CHAR_CAP)
chunks = llm._pack_chunks_by_tokens(units, token_budget=2000)
# all units land in some chunk; flattening recovers them all
flat = [u for ch in chunks for u in ch]
assert len(flat) == len(units)
# ── bisect_slice (adaptive-retry path) ──────────────────────────────────────
def test_bisect_slice_splits_at_newline(tmp_path):
f = _write(tmp_path / "a.md", "alpha\n" * 100)
fs = FileSlice(f, 0, 600, 0, 1)
halves = bisect_slice(fs)
assert halves is not None
left, right = halves
assert left.start == fs.start and right.end == fs.end
assert left.end == right.start # contiguous, no gap
assert fs.start < left.end < fs.end
def test_bisect_slice_returns_none_for_tiny(tmp_path):
f = _write(tmp_path / "a.md", "ab")
assert bisect_slice(FileSlice(f, 0, 1, 0, 1)) is None
+41
View File
@@ -333,3 +333,44 @@ def test_installed_hooks_contain_no_nohup(tmp_path):
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
# ── #1385: reject Windows-style hooks paths instead of creating a junk dir ───
def _set_hookspath(repo: Path, value: str) -> None:
subprocess.run(["git", "-C", str(repo), "config", "--local", "core.hooksPath", value],
check=True, capture_output=True)
@pytest.mark.parametrize("winpath", [
r"C:\Users\u\repo\.git\hooks",
r"c:/Users/u/.git/hooks",
r"D:\hooks",
r"some\back\slashed\path",
])
def test_windows_hookspath_rejected_no_junk_dir(tmp_path, winpath):
"""A Windows-style core.hooksPath must raise (loud failure), not silently
create a backslash-named junk directory and report success (#1385)."""
repo = _make_git_repo(tmp_path)
_set_hookspath(repo, winpath)
with pytest.raises(RuntimeError, match="Windows path"):
install(repo)
# no junk directory got created anywhere under the repo
junk = [p for p in repo.rglob("*") if "\\" in p.name or p.name.startswith(("C:", "c:", "D:"))]
assert junk == [], f"junk dir created: {junk}"
def test_posix_custom_hookspath_still_works(tmp_path):
"""A legitimate POSIX core.hooksPath (Husky-style) must still install."""
repo = _make_git_repo(tmp_path)
_set_hookspath(repo, ".husky")
msg = install(repo)
assert "post-commit" in msg
assert (repo / ".husky" / "post-commit").exists()
def test_default_hooks_dir_unaffected(tmp_path):
"""No core.hooksPath -> normal .git/hooks install, no rejection."""
repo = _make_git_repo(tmp_path)
install(repo)
assert (repo / ".git" / "hooks" / "post-commit").exists()
+119
View File
@@ -0,0 +1,119 @@
"""Drift guard for the node-ID normalization contract.
Three independent producers must agree on node IDs or the graph splits one entity
into disconnected ghost nodes: the AST extractor (``extract._make_id``), the
semantic subagents (the skill prompt's node-ID spec), and the graph builder
(``build._normalize_id``, which reconciles edge endpoints). The recipe used to be
copy-pasted into ``_make_id`` and ``_normalize_id`` and kept in sync only by
mirrored docstrings — exactly how the recurring ID-drift bug class crept in
(#811 Unicode collapse, #550 same-filename collisions, #1033 AST-vs-LLM file-node
mismatch, #1104).
Both callers now delegate to :mod:`graphify.ids`, so they share one
implementation and cannot diverge. These tests lock that contract: if a future
change re-forks the normalization (a new local helper, an inlined regex, a
dropped ``casefold``), they fail.
"""
import re
import pytest
from graphify.build import _normalize_id
from graphify.extract import _make_id
from graphify.ids import make_id, normalize_id
# Inputs that previously diverged or are easy to get wrong. The single-part form
# of `_make_id` must equal `_normalize_id` for every one of these.
CONTRACT_CASES = [
"Session_ValidateToken", # casing
"session.validate-token", # punctuation -> underscore
"foo__bar..baz", # repeated separators collapse
" Leading_Trailing__ ", # strip stray underscores/space
"A/B\\C", # path separators both directions
"MixedCASE", # #811: casefold
"café", # composed accented Latin (NFKC)
"café", # decomposed e + combining acute -> same as 'café'
"日本語クラス", # #811: CJK letters survive, not collapsed
"Кириллица", # Cyrillic survives
"naïve_Über", # mixed accented Latin
"x_c1", # must NOT be treated as a chunk suffix here
"__dunder__", # leading/trailing underscores stripped
"tab\tnewline\nspace ", # whitespace runs -> single underscore
]
@pytest.mark.parametrize("raw", CONTRACT_CASES)
def test_make_id_matches_normalize_id(raw):
"""The AST id-maker and the builder's reconciler must agree, char for char."""
assert _make_id(raw) == _normalize_id(raw), (
f"ID drift for {raw!r}: extract._make_id -> {_make_id(raw)!r} but "
f"build._normalize_id -> {_normalize_id(raw)!r}"
)
@pytest.mark.parametrize("raw", CONTRACT_CASES)
def test_normalize_id_is_idempotent(raw):
once = normalize_id(raw)
assert normalize_id(once) == once, f"normalize_id not idempotent for {raw!r}"
def test_make_id_joins_then_normalizes():
"""Multi-part make_id == normalize_id of the joined parts (the builder only
ever sees the joined string, so these must coincide)."""
parts = ("auth", "session.py", "ValidateToken")
assert make_id(*parts) == normalize_id("_".join(parts))
# Documented spec example.
assert make_id("src/auth/session.py".split("/")[-2], "session", "ValidateToken") == \
"auth_session_validatetoken"
def test_unicode_identifiers_do_not_collapse_to_empty():
"""#811: non-ASCII identifiers must yield distinct, non-empty IDs rather than
collapsing to a single per-file node."""
a = _make_id("クラスА")
b = _make_id("クラスB")
assert a and b and a != b
def test_normalized_ids_are_safe_node_ids():
"""Output is lowercase and contains no path/punctuation separators."""
for raw in CONTRACT_CASES:
out = normalize_id(raw)
assert out == out.casefold()
assert not re.search(r"[./\\\s]", out), f"unsafe char in id {out!r}"
assert not out.startswith("_") and not out.endswith("_")
def test_both_callers_share_one_implementation():
"""Guard against re-forking: the two public callers must resolve to the same
underlying function object as graphify.ids.normalize_id."""
# build._normalize_id is imported directly from graphify.ids.
assert _normalize_id is normalize_id
# extract._make_id wraps make_id; prove it round-trips through the shared core.
assert _make_id("Foo.Bar") == normalize_id("Foo.Bar")
# The other two live ID producers — MCP config ingestion and bash symbol
# resolution — must also resolve to the shared recipe, or the "single source
# of truth" leaks back into copy-pasted forks (#1378).
from graphify.mcp_ingest import _make_id as _mcp_make_id
from graphify.symbol_resolution import _bash_make_id
for fn in (_make_id, _mcp_make_id, _bash_make_id):
assert fn("Foo.Bar", "baz") == make_id("Foo.Bar", "baz")
assert fn("Ångström", "Ⅳ") == make_id("Ångström", "Ⅳ")
# Optional property-based fuzzing — hypothesis is a dev dependency. Skip cleanly
# if it is unavailable so the deterministic cases above still run everywhere.
hypothesis = pytest.importorskip("hypothesis")
from hypothesis import given # noqa: E402
from hypothesis import strategies as st # noqa: E402
@given(st.text())
def test_property_make_id_equals_normalize_id(s):
assert _make_id(s) == _normalize_id(s)
@given(st.text())
def test_property_normalize_id_idempotent(s):
once = normalize_id(s)
assert normalize_id(once) == once
+24
View File
@@ -72,3 +72,27 @@ def test_no_incremental_without_manifest(tmp_path):
# which pytest derives from the test name and contains "incremental".
assert "incremental update" not in r.stdout.lower()
assert "incremental scan" not in r.stdout.lower()
def test_extract_no_cluster_incremental_noop_preserves_existing_graph(tmp_path):
"""#1347: no-op incremental no-cluster extract must not overwrite graph.json."""
project = tmp_path / "project"
project.mkdir()
(project / "app.py").write_text(
"def alpha():\n return 1\n", encoding="utf-8"
)
first = _run(["extract", str(project), "--no-cluster"], tmp_path)
assert first.returncode == 0, first.stderr
graph_path = project / "graphify-out" / "graph.json"
before_text = graph_path.read_text(encoding="utf-8")
before = json.loads(before_text)
assert before.get("nodes"), "first run should produce a non-empty code graph"
second = _run(["extract", str(project), "--no-cluster"], tmp_path)
assert second.returncode == 0, second.stderr
after_text = graph_path.read_text(encoding="utf-8")
after = json.loads(after_text)
assert after.get("nodes"), "no-op incremental run must not empty the graph"
assert after_text == before_text
+171
View File
@@ -0,0 +1,171 @@
from __future__ import annotations
from pathlib import Path
from graphify.build import build_from_json
from graphify.extract import extract
def _write(path: Path, text: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
def _node_by_id(result: dict, nid: str) -> dict | None:
return next((n for n in result["nodes"] if n.get("id") == nid), None)
def test_java_cross_file_implements_resolves_to_real_def(tmp_path: Path):
# #1318: a cross-file `implements` must land on the real interface def, not a
# bare no-source shadow stub.
iface = _write(
tmp_path / "src/com/x/handler/AIResponseHandler.java",
"package com.x.handler;\npublic interface AIResponseHandler {}\n",
)
impl = _write(
tmp_path / "src/com/x/service/DifyAiServiceImpl.java",
"package com.x.service;\n"
"import com.x.handler.AIResponseHandler;\n"
"public class DifyAiServiceImpl implements AIResponseHandler {}\n",
)
result = extract([iface, impl], cache_root=tmp_path)
implements = [e for e in result["edges"] if e["relation"] == "implements"]
assert implements, "expected an implements edge"
for e in implements:
tgt = _node_by_id(result, e["target"])
assert tgt is not None, f"implements target {e['target']} is not a node"
# The target must be the real definition (has a source_file), not a shadow stub.
assert tgt.get("source_file"), f"implements landed on shadow stub {e['target']}"
assert "handler" in tgt["source_file"]
def test_java_ambiguous_implements_disambiguated_by_import(tmp_path: Path):
# #1318 core case: two interfaces with the SAME simple name in different
# packages. The importing file's `import` must pick the right one, and no
# orphan shadow node may remain.
a = _write(
tmp_path / "src/com/a/handler/AIResponseHandler.java",
"package com.a.handler;\npublic interface AIResponseHandler {}\n",
)
b = _write(
tmp_path / "src/com/b/handler/AIResponseHandler.java",
"package com.b.handler;\npublic interface AIResponseHandler {}\n",
)
impl = _write(
tmp_path / "src/com/x/service/Impl.java",
"package com.x.service;\n"
"import com.a.handler.AIResponseHandler;\n"
"public class Impl implements AIResponseHandler {}\n",
)
result = extract([a, b, impl], cache_root=tmp_path)
# No bare shadow stub for the interface should survive.
shadow = [
n for n in result["nodes"]
if n.get("label") == "AIResponseHandler" and not n.get("source_file")
]
assert not shadow, f"orphan shadow node(s) remain: {[n['id'] for n in shadow]}"
implements = [e for e in result["edges"] if e["relation"] == "implements"]
assert len(implements) == 1
tgt = _node_by_id(result, implements[0]["target"])
assert tgt is not None and tgt.get("source_file")
# Must resolve to the imported package (com/a), not com/b.
assert "com/a/handler" in tgt["source_file"]
assert "com/b/handler" not in tgt["source_file"]
def test_java_implements_edge_survives_build(tmp_path: Path):
# #1318: the re-pointed edge must connect real nodes after graph assembly,
# so the interface is not classified as an isolated community.
iface = _write(
tmp_path / "src/com/x/handler/Handler.java",
"package com.x.handler;\npublic interface Handler {}\n",
)
impl = _write(
tmp_path / "src/com/x/service/Svc.java",
"package com.x.service;\n"
"import com.x.handler.Handler;\n"
"public class Svc implements Handler {}\n",
)
result = extract([iface, impl], cache_root=tmp_path)
G = build_from_json(result, directed=True)
impl_edges = [
(u, v) for u, v, d in G.edges(data=True) if d.get("relation") == "implements"
]
assert impl_edges
# The interface node has an incoming implements edge (not isolated).
assert any(G.in_degree(v) >= 1 for _, v in impl_edges)
def _label_edges(result: dict, relations):
by_id = {n["id"]: n.get("label", "") for n in result["nodes"]}
return {
(by_id.get(e["source"], ""), e["relation"], by_id.get(e["target"], ""))
for e in result["edges"]
if e.get("relation") in relations
}
def test_java_record_becomes_type_node(tmp_path: Path):
# #1373: a Java `record` must produce a first-class type node (with a
# `contains` edge from its file), not be left as an isolated file node.
rec = _write(
tmp_path / "Foo.java",
"package com.app;\npublic record Foo(int x, String y) {}\n",
)
result = extract([rec], cache_root=tmp_path)
foo = [n for n in result["nodes"]
if n.get("label") == "Foo" and n.get("source_file")]
assert foo, "record Foo should be a type node, not just the file node"
contains = _label_edges(result, {"contains"})
assert ("Foo.java", "contains", "Foo") in contains
def test_java_record_implements_interface(tmp_path: Path):
# Records reuse class interface handling: `record Foo implements I` emits it.
iface = _write(tmp_path / "I.java", "package com.app;\npublic interface I {}\n")
rec = _write(
tmp_path / "Foo.java",
"package com.app;\npublic record Foo(int x) implements I {}\n",
)
result = extract([iface, rec], cache_root=tmp_path)
implements = [e for e in result["edges"] if e["relation"] == "implements"]
assert implements, "record implementing an interface should emit an implements edge"
def test_java_cross_file_constructor_call_resolves(tmp_path: Path):
# #1373: `new Foo(...)` in a method body must produce a cross-file edge to the
# Foo definition. Foo is NOT used as a return type here, so the edge can only
# come from the constructor call (object_creation_expression), not return-type
# handling.
foo = _write(
tmp_path / "Foo.java",
"package com.app;\npublic record Foo(int x, String y) {}\n",
)
caller = _write(
tmp_path / "Helper.java",
"package com.app;\n"
"public class Helper {\n"
" public void build() {\n"
" Object o = new Foo(1, \"a\");\n"
" System.out.println(o);\n"
" }\n"
"}\n",
)
result = extract([foo, caller], cache_root=tmp_path)
foo_id = next(n["id"] for n in result["nodes"]
if n.get("label") == "Foo" and n.get("source_file"))
call_targets = {
e["target"] for e in result["edges"]
if e.get("relation") in ("calls", "references")
}
assert foo_id in call_targets, "new Foo(...) should produce a calls/references edge to Foo"
# Survives graph construction (target is a real node).
g = build_from_json(result)
assert foo_id in set(g.nodes())
+73
View File
@@ -459,6 +459,79 @@ def test_pnpm_workspace_package_import_resolves_package_entry(tmp_path: Path):
assert _has_edge(result, "apps/web/src/page.ts", "packages/types/src/index.ts")
def test_npm_workspace_package_import_resolves_package_entry(tmp_path: Path):
_write(
tmp_path / "package.json",
json.dumps({"workspaces": ["apps/*", "packages/*"]}),
)
_write(
tmp_path / "packages/types/package.json",
json.dumps({"name": "@workspace/types", "exports": "./src/index.ts"}),
)
target = _write(
tmp_path / "packages/types/src/index.ts",
"export interface SomeDto { id: string }\n",
)
importer = _write(
tmp_path / "apps/web/src/page.ts",
"import type { SomeDto } from '@workspace/types'\nconst dto: SomeDto = { id: '1' }\n",
)
result = _extract_for([target, importer], tmp_path)
assert _has_edge(result, "apps/web/src/page.ts", "packages/types/src/index.ts")
def test_yarn_workspace_package_import_resolves_package_entry(tmp_path: Path):
_write(
tmp_path / "package.json",
json.dumps({"workspaces": {"packages": ["apps/*", "packages/*"]}}),
)
_write(
tmp_path / "packages/types/package.json",
json.dumps({"name": "@workspace/types", "exports": "./src/index.ts"}),
)
target = _write(
tmp_path / "packages/types/src/index.ts",
"export interface SomeDto { id: string }\n",
)
importer = _write(
tmp_path / "apps/web/src/page.ts",
"import type { SomeDto } from '@workspace/types'\nconst dto: SomeDto = { id: '1' }\n",
)
result = _extract_for([target, importer], tmp_path)
assert _has_edge(result, "apps/web/src/page.ts", "packages/types/src/index.ts")
def test_pnpm_workspace_takes_precedence_over_package_json_workspaces(tmp_path: Path):
_write(
tmp_path / "pnpm-workspace.yaml",
"packages:\n - 'apps/*'\n - 'packages/*'\n",
)
_write(
tmp_path / "package.json",
json.dumps({"workspaces": ["other/*"]}),
)
_write(
tmp_path / "packages/types/package.json",
json.dumps({"name": "@workspace/types", "exports": "./src/index.ts"}),
)
target = _write(
tmp_path / "packages/types/src/index.ts",
"export interface SomeDto { id: string }\n",
)
importer = _write(
tmp_path / "apps/web/src/page.ts",
"import type { SomeDto } from '@workspace/types'\nconst dto: SomeDto = { id: '1' }\n",
)
result = _extract_for([target, importer], tmp_path)
assert _has_edge(result, "apps/web/src/page.ts", "packages/types/src/index.ts")
def test_js_import_resolution_ignores_stale_importer_cache_when_target_appears(tmp_path: Path):
importer = _write(
tmp_path / "src/lib/page.ts",
+46
View File
@@ -0,0 +1,46 @@
"""Tests for graphify.llm._label_batch_with_retry — adaptive split-and-retry
on JSON parse failure during community labeling (#1278).
"""
from __future__ import annotations
import json
import re
from graphify import llm as llm_mod
def test_label_batch_recovers_via_split_on_invalid_json(monkeypatch):
"""Demonstrates the bug fix.
The full batch of 4 communities triggers malformed JSON from the LLM.
The helper splits in half (2+2) and retries each half. Both sub-batches
succeed. Every community ends up labeled — none silently dropped.
"""
batch_cids = [42, 99, 137, 201]
batch_lines = [
"Community 42: validate_token, get_session",
"Community 99: create_order, add_to_cart",
"Community 137: build_graph, cluster_nodes",
"Community 201: render_route, handle_request",
]
call_count = {"n": 0}
def fake_call_llm(prompt: str, **_kwargs) -> str:
"""First call (4 communities): returns broken JSON to trigger retry.
Subsequent calls (<=2 communities): return a clean JSON object
labeling whatever community IDs appear in the prompt.
"""
call_count["n"] += 1
cids_in_prompt = [int(m) for m in re.findall(r"Community (\d+):", prompt)]
if call_count["n"] == 1:
return "{this is not valid json, missing quotes"
return json.dumps({str(cid): f"Label {cid}" for cid in cids_in_prompt})
monkeypatch.setattr(llm_mod, "_call_llm", fake_call_llm)
result = llm_mod._label_batch_with_retry(
batch_cids, batch_lines, backend="gemini", model=None,
)
assert result == {42: "Label 42", 99: "Label 99", 137: "Label 137", 201: "Label 201"}
assert call_count["n"] >= 2
+206
View File
@@ -9,6 +9,7 @@ from graphify.extract import (
extract_groovy, extract_sln, extract_csproj, extract_razor,
extract_dm, extract_dmi, extract_dmm, extract_dmf,
extract_powershell, extract_apex, extract_verilog,
extract_powershell_manifest,
)
FIXTURES = Path(__file__).parent / "fixtures"
@@ -610,6 +611,9 @@ def test_swift_imports_survive_build():
node_ids = {n["id"] for n in r["nodes"]}
for e in import_edges:
assert e["target"] in node_ids # synthesized module node exists
# Imported modules are tagged type=module (anchor nodes, #1327/#1330).
module_labels = {n["label"] for n in r["nodes"] if n.get("type") == "module"}
assert {"Foundation", "UIKit"} <= module_labels
# No private bookkeeping key should leak into output edges.
assert all("_import_label" not in e for e in r["edges"])
# Edges must survive the build (which prunes edges with unknown endpoints).
@@ -1060,6 +1064,146 @@ def test_powershell_method_parameter_and_return_type_contexts():
assert ("Save", "void") in _edge_labels(r, "references", "return_type")
# ── PowerShell: Import-Module + dot-source (#1331) ───────────────────────────
def test_powershell_import_module_emits_edge():
"""Import-Module Foo at top level emits an imports_from edge."""
r = extract_powershell(FIXTURES / "sample_import.ps1")
assert "error" not in r
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("foo" in t for t in targets), f"Missing Import-Module Foo edge; targets={targets}"
def test_powershell_import_module_with_name_param():
"""Import-Module -Name Bar.psm1 resolves to module stem 'bar'."""
r = extract_powershell(FIXTURES / "sample_import.ps1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("bar" in t for t in targets), f"Missing Import-Module -Name Bar edge; targets={targets}"
def test_powershell_dot_source_forward_slash_emits_edge():
"""Dot-source `. ./Shared.psm1` emits an imports_from edge."""
r = extract_powershell(FIXTURES / "sample_import.ps1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("shared" in t for t in targets), f"Missing dot-source Shared edge; targets={targets}"
def test_powershell_dot_source_backslash_emits_edge():
"""Dot-source `. .\\Utils.ps1` (backslash path) emits an imports_from edge."""
r = extract_powershell(FIXTURES / "sample_import.ps1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("utils" in t for t in targets), f"Missing dot-source Utils edge; targets={targets}"
def test_powershell_import_module_inside_function_emits_edge():
"""Import-Module inside a function body still produces an imports_from edge."""
r = extract_powershell(FIXTURES / "sample_import.ps1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("innermod" in t for t in targets), (
f"Missing Import-Module InnerMod edge from function body; targets={targets}"
)
def test_powershell_import_module_not_a_raw_call():
"""Import-Module must not appear in raw_calls (it is an import, not a function call)."""
r = extract_powershell(FIXTURES / "sample_import.ps1")
import_module_calls = [
rc for rc in r.get("raw_calls", [])
if rc.get("callee", "").lower() == "import-module"
]
assert not import_module_calls, (
f"Import-Module appeared in raw_calls but should be emitted as import edge: {import_module_calls}"
)
def test_powershell_dot_source_inside_function_emits_edge():
"""Dot-source inside a function body still produces an imports_from edge."""
r = extract_powershell(FIXTURES / "sample_import.ps1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("innershared" in t for t in targets), (
f"Missing dot-source InnerShared edge from function body; targets={targets}"
)
# ── PowerShell manifest (.psd1) (#1331) ──────────────────────────────────────
def test_powershell_psd1_dispatched():
"""_get_extractor should route .psd1 to extract_powershell_manifest."""
from graphify.extract import _get_extractor
import tempfile, os
with tempfile.NamedTemporaryFile(suffix=".psd1", delete=False) as f:
f.write(b"@{ RootModule = 'X.psm1' }")
path = f.name
try:
assert _get_extractor(Path(path)) is extract_powershell_manifest
finally:
os.unlink(path)
def test_powershell_psd1_no_error():
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
assert "error" not in r
def test_powershell_psd1_has_file_node():
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
assert any("sample.psd1" in n["label"] for n in r["nodes"]), (
f"Missing file node for sample.psd1; nodes={[n['label'] for n in r['nodes']]}"
)
def test_powershell_psd1_root_module():
"""RootModule = 'MyModule.psm1' produces an imports_from edge to 'mymodule'."""
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("mymodule" in t for t in targets), (
f"Missing RootModule edge for MyModule; targets={targets}"
)
def test_powershell_psd1_nested_modules():
"""NestedModules = @('Helpers.psm1', 'Logger.psm1') produces edges for both."""
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("helpers" in t for t in targets), f"Missing NestedModules Helpers edge; targets={targets}"
assert any("logger" in t for t in targets), f"Missing NestedModules Logger edge; targets={targets}"
def test_powershell_psd1_required_modules_string():
"""RequiredModules string form 'PSReadLine' produces an imports_from edge."""
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("psreadline" in t for t in targets), (
f"Missing RequiredModules PSReadLine edge; targets={targets}"
)
def test_powershell_psd1_required_modules_hashtable():
"""RequiredModules hashtable form @{{ ModuleName='Pester' }} produces an imports_from edge."""
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("pester" in t for t in targets), (
f"Missing RequiredModules Pester (hashtable form) edge; targets={targets}"
)
def test_powershell_psd1_no_moduleversion_as_edge():
"""ModuleVersion values ('5.0', '1.0.0') must NOT appear as import targets."""
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert not any(t in targets for t in ("5_0", "1_0_0", "5.0", "1.0.0")), (
f"ModuleVersion string leaked into import targets: {targets}"
)
def test_powershell_psd1_no_dangling_edges():
"""All imports_from edge sources must exist in the node set."""
r = extract_powershell_manifest(FIXTURES / "sample.psd1")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source in edge: {e}"
# ── TypeScript dynamic imports ───────────────────────────────────────────────
def test_ts_dynamic_import_no_error():
@@ -1277,6 +1421,68 @@ def test_markdown_no_dangling_edges():
assert e["source"] in node_ids, f"Dangling source: {e}"
def _md_link_fixture(tmp_path):
"""A hub doc linking to sibling docs, plus those docs (#1376)."""
pkg = tmp_path / "packages" / "coding-standards-csharp"
pkg.mkdir(parents=True)
(pkg / "index.md").write_text(
"# C# Coding Standards\n\n"
"| Topic | Doc |\n| --- | --- |\n"
"| Repository | [C# Repository Standards](./repository.md) |\n"
"| HTTP Client | [C# HTTP Client Standards](http-client.md) |\n"
"| Unit Tests | [C# Unit Test Standards](unit-tests.md) |\n\n"
"See also [external](https://example.com/x) and ![logo](./logo.png).\n"
"Anchor: [section](./repository.md#setup).\n"
"Wikilink: [[http-client]].\n"
)
(pkg / "repository.md").write_text("# C# Repository Standards\nContent.\n")
(pkg / "http-client.md").write_text("# C# HTTP Client Standards\nContent.\n")
(pkg / "unit-tests.md").write_text("# C# Unit Test Standards\nContent.\n")
return pkg
def test_markdown_link_edges_emitted(tmp_path):
"""Inline/wikilink markdown links to sibling docs become references edges (#1376)."""
pkg = _md_link_fixture(tmp_path)
r = extract_markdown(pkg / "index.md")
refs = [e for e in r["edges"] if e["relation"] == "references"]
targets = {e["target"] for e in refs}
# repository, http-client, unit-tests — each exactly once (deduped despite
# the anchor link and wikilink pointing at repository/http-client again).
assert len(refs) == 3, f"expected 3 reference edges, got {refs}"
assert any("repository" in t for t in targets)
assert any("http_client" in t for t in targets)
assert any("unit_tests" in t for t in targets)
def test_markdown_link_skips_external_and_images(tmp_path):
"""External URLs, in-page anchors and images must not produce edges (#1376)."""
pkg = _md_link_fixture(tmp_path)
r = extract_markdown(pkg / "index.md")
refs = [e for e in r["edges"] if e["relation"] == "references"]
for e in refs:
assert "example.com" not in e["target"]
assert "logo" not in e["target"]
def test_markdown_link_edges_resolve_to_real_nodes(tmp_path):
"""End-to-end: after extract()'s ID remap, link targets are real doc nodes,
so the hub doc gains edges into existing nodes instead of ghost nodes (#1376)."""
from graphify.extract import extract
pkg = _md_link_fixture(tmp_path)
paths = sorted(pkg.glob("*.md"))
res = extract(paths, cache_root=tmp_path, parallel=False)
node_ids = {n["id"] for n in res["nodes"]}
refs = [e for e in res["edges"] if e["relation"] == "references"]
assert refs, "expected reference edges after full extract"
for e in refs:
assert e["target"] in node_ids, f"link target is a ghost node: {e}"
# index.md must connect to all three sibling docs.
index_id = next(n["id"] for n in res["nodes"] if n["label"] == "index.md")
index_refs = {e["target"] for e in refs if e["source"] == index_id}
assert len(index_refs) == 3, f"hub doc under-connected: {index_refs}"
# ── Groovy ───────────────────────────────────────────────────────────────────
+79
View File
@@ -82,6 +82,33 @@ def test_extract_files_direct_routes_gemini_through_openai_compat(tmp_path, monk
assert call.call_args.kwargs["max_completion_tokens"] == 16384
@pytest.mark.parametrize(
"backend, env_key",
[
("ollama", "OLLAMA_API_KEY"),
("deepseek", "DEEPSEEK_API_KEY"),
("openai", "OPENAI_API_KEY"),
("kimi", "MOONSHOT_API_KEY"),
],
)
def test_openai_compat_backends_resolve_full_output_cap(tmp_path, monkeypatch, backend, env_key):
# #1365: these configs define `max_tokens: 16384`, but the dispatch used to
# read only the `max_completion_tokens` key (which only gemini sets), so the
# output cap silently fell back to 8192 and truncated deep-mode JSON. The
# dispatch must resolve their configured 16384.
_clear_backend_env(monkeypatch)
monkeypatch.delenv("GRAPHIFY_MAX_OUTPUT_TOKENS", raising=False)
monkeypatch.setenv(env_key, "test-key")
source = tmp_path / "note.md"
source.write_text("# Architecture\n")
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
with patch("graphify.llm._call_openai_compat", return_value=result) as call:
llm.extract_files_direct([source], backend=backend, root=tmp_path)
assert call.call_args.kwargs["max_completion_tokens"] == 16384
def test_gemini_model_can_be_overridden_by_env(tmp_path, monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
@@ -105,6 +132,58 @@ def test_missing_gemini_key_names_both_supported_env_vars(monkeypatch):
assert "GEMINI_API_KEY or GOOGLE_API_KEY" in str(exc.value)
# ---------------------------------------------------------------------------
# #1386: public entry points accept str paths, not just pathlib.Path
# ---------------------------------------------------------------------------
def test_extract_files_direct_accepts_str_paths(tmp_path, monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
source = tmp_path / "note.md"
source.write_text("# Architecture\n\nThe runner emits a snapshot.\n")
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
# str path must not raise AttributeError: 'str' object has no attribute 'suffix'
with patch("graphify.llm._call_openai_compat", return_value=result):
assert llm.extract_files_direct([str(source)], backend="gemini", root=tmp_path) is result
def test_extract_corpus_parallel_accepts_str_and_mixed_paths(tmp_path, monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
f1 = tmp_path / "a.md"
f1.write_text("# A\n\nNode one.\n")
f2 = tmp_path / "b.md"
f2.write_text("# B\n\nNode two.\n")
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
with patch("graphify.llm._call_openai_compat", return_value=result):
# all-str, all-Path, and mixed must each pack + run without AttributeError
for files in ([str(f1), str(f2)], [f1, f2], [str(f1), f2]):
merged = llm.extract_corpus_parallel(
files, backend="gemini", root=tmp_path, max_concurrency=1
)
assert merged["failed_chunks"] == 0
def test_str_path_entry_points_handle_edge_cases(tmp_path, monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
with patch("graphify.llm._call_openai_compat", return_value=result):
# empty list: no chunks, nothing to extract, no crash
empty = llm.extract_corpus_parallel([], backend="gemini", root=tmp_path)
assert empty["nodes"] == [] and empty["failed_chunks"] == 0
# a Path subclass is still a Path and must pass through unchanged
class _SubPath(type(Path())): # concrete OS-specific Path subclass
pass
sub = _SubPath(tmp_path / "c.md")
sub.write_text("# C\n\nNode.\n")
assert llm.extract_files_direct([sub], backend="gemini", root=tmp_path) is result
# ---------------------------------------------------------------------------
# Adaptive retry: context-window overflow recovery
# ---------------------------------------------------------------------------
+114
View File
@@ -0,0 +1,114 @@
from __future__ import annotations
from pathlib import Path
from graphify.build import build_from_json
from graphify.detect import FileType, classify_file
from graphify.extract import extract
from graphify.manifest_ingest import (
extract_package_manifest,
is_package_manifest_path,
)
def _write(p: Path, text: str) -> Path:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text, encoding="utf-8")
return p
# ── routing: manifests are deterministic (CODE), not LLM documents ───────────
def test_manifests_classify_as_code_not_document(tmp_path):
for name in ("apm.yml", "pyproject.toml", "go.mod", "pom.xml"):
p = _write(tmp_path / name, "x")
assert is_package_manifest_path(p)
assert classify_file(p) is FileType.CODE, name
# a generic yaml stays a document
assert classify_file(_write(tmp_path / "config.yaml", "a: 1")) is FileType.DOCUMENT
# ── per-format parsing ───────────────────────────────────────────────────────
def _pkg_nodes(result):
return [n for n in result["nodes"] if n.get("type") == "package"]
def test_apm_parses_name_and_deps(tmp_path):
p = _write(tmp_path / "apm.yml",
"name: my-pkg\nversion: 1.2.3\ndependencies:\n - dep-a\n - dep-b\n")
r = extract_package_manifest(p)
pkg = _pkg_nodes(r)[0]
assert pkg["label"] == "my-pkg" and pkg["version"] == "1.2.3"
deps = {e["target"] for e in r["edges"] if e["relation"] == "depends_on"}
assert {"pkg_dep_a", "pkg_dep_b"} <= deps
def test_pyproject_parses_pep508_deps(tmp_path):
p = _write(tmp_path / "pyproject.toml",
'[project]\nname = "cool-lib"\nversion = "0.1"\n'
'dependencies = ["requests>=2.0", "rich[jupyter]==13.0", "tomli; python_version<\'3.11\'"]\n')
r = extract_package_manifest(p)
assert _pkg_nodes(r)[0]["label"] == "cool-lib"
deps = {e["target"] for e in r["edges"]}
assert {"pkg_requests", "pkg_rich", "pkg_tomli"} <= deps # versions/extras/markers stripped
def test_gomod_parses_module_and_requires(tmp_path):
p = _write(tmp_path / "go.mod",
"module example.com/me/app\n\ngo 1.22\n\nrequire (\n"
"\tgithub.com/x/y v1.2.3\n\tgithub.com/a/b v0.4.0\n)\n")
r = extract_package_manifest(p)
assert _pkg_nodes(r)[0]["label"] == "example.com/me/app"
deps = {e["target"] for e in r["edges"]}
assert "pkg_github_com_x_y" in deps and "pkg_github_com_a_b" in deps
def test_pom_parses_artifact_and_deps(tmp_path):
p = _write(tmp_path / "pom.xml",
'<project xmlns="http://maven.apache.org/POM/4.0.0">\n'
' <groupId>com.acme</groupId>\n <artifactId>widget</artifactId>\n <version>2.0</version>\n'
' <dependencies>\n <dependency><groupId>org.lib</groupId><artifactId>core</artifactId></dependency>\n'
' </dependencies>\n</project>\n')
r = extract_package_manifest(p)
assert _pkg_nodes(r)[0]["label"] == "com.acme:widget"
assert any(e["target"] == "pkg_org_lib_core" for e in r["edges"])
# ── #1377: a package referenced by N manifests is ONE node ───────────────────
def test_apm_dependency_collapses_to_single_canonical_node(tmp_path):
base = tmp_path / "packages"
_write(base / "core/apm.yml", "name: coding-standards-core\nversion: 1.0.4\n")
_write(base / "csharp/apm.yml",
"name: coding-standards-csharp\ndependencies:\n - coding-standards-core\n")
_write(base / "python/apm.yml",
'name: coding-standards-python\ndependencies:\n coding-standards-core: ">=1.0"\n')
files = sorted(base.rglob("apm.yml"))
result = extract(files, cache_root=tmp_path)
core = [n for n in result["nodes"]
if n.get("type") == "package" and n["label"] == "coding-standards-core"]
assert len(core) == 1, "core package must be a single canonical node"
assert core[0]["id"] == "pkg_coding_standards_core" and core[0]["source_file"]
g = build_from_json(result)
core_ids = [n for n, d in g.nodes(data=True) if d.get("label") == "coding-standards-core"]
dep_edges = [(u, v) for u, v, d in g.edges(data=True) if d.get("relation") == "depends_on"]
assert len(core_ids) == 1
assert len(dep_edges) == 2 # both dependents point at the one core node
def test_external_dependency_edge_pruned_not_orphaned(tmp_path):
# A dep whose manifest isn't in the corpus: the edge dangles and build prunes it.
p = _write(tmp_path / "apm.yml", "name: leaf\ndependencies:\n - some-external-pkg\n")
result = extract([p], cache_root=tmp_path)
g = build_from_json(result)
assert "pkg_some_external_pkg" not in set(g.nodes()) # no fabricated external node
assert [n for n, d in g.nodes(data=True) if d.get("label") == "leaf"]
def test_malformed_manifest_does_not_crash(tmp_path):
p = _write(tmp_path / "pom.xml", "<project><not closed")
r = extract_package_manifest(p) # parse error -> empty, no exception
assert r["nodes"] == [] and r["edges"] == []
+7
View File
@@ -123,6 +123,13 @@ def test_find_node_ignores_trailing_punctuation():
assert _find_node(G, "extract?") == ["n1"]
def test_find_node_matches_full_punctuated_unicode_label():
G = nx.Graph()
G.add_node("n1", label="Skill /auditar — Auditoría inquisitiva de enlaces")
assert _find_node(G, "Skill /auditar — Auditoría inquisitiva de enlaces") == ["n1"]
def test_query_terms_strips_search_punctuation():
assert _query_terms("what calls extract?") == ["what", "calls", "extract"]
+10 -8
View File
@@ -305,19 +305,21 @@ def test_codex_uses_compact_extraction_windows_uses_verbose():
assert "(compact)" not in windows_refs["extraction-spec.md"]
def test_cli_inline_query_stub_has_no_vocab_expansion():
"""cli-inline hosts get the NetworkX-fallback stub, not vocab-expansion."""
for key in ("codex", "windows"):
def test_every_platform_query_has_expansion_and_fallback():
"""#1325: the unified query reference ships BOTH the vocab-expansion step and
the inline NetworkX fallback to every platform (previously split so no host
got both — Claude had expansion but no fallback; the rest the reverse)."""
for key in ("claude", "codex", "windows", "opencode"):
core, refs = _platform_artifacts(key)
# The core stub points at the query reference without the vocab step.
assert "expand the question against the graph's own vocabulary" not in core
# Core stub mentions both the vocab-expansion step and the inline fallback.
assert "expand the question against the graph's own vocabulary" in core
assert "NetworkX traversal" in core
# The query reference carries the path/explain headings but not the
# claude-only vocab-expansion sub-headings.
# The query reference carries expansion, fallback, and path/explain.
q = refs["query.md"]
assert "Constrained query expansion" in q
assert "If the CLI is unavailable" in q
assert "## For /graphify path" in q
assert "## For /graphify explain" in q
assert "Constrained query expansion" not in q
def test_schema_singleton_passes_across_all_platforms():
+144
View File
@@ -0,0 +1,144 @@
from __future__ import annotations
from pathlib import Path
from graphify.build import build_from_json
from graphify.extract import extract
def _write(path: Path, text: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
def _label(result: dict, nid: str) -> str:
for n in result["nodes"]:
if n["id"] == nid:
return n.get("label", "")
return f"<{nid}>"
def _edge_labels(result: dict, relations=("calls", "references")) -> set[tuple[str, str, str]]:
"""Return {(source_label, relation, target_label)} for the given relations."""
out: set[tuple[str, str, str]] = set()
for e in result["edges"]:
if e.get("relation") in relations:
out.add((_label(result, e["source"]), e["relation"], _label(result, e["target"])))
return out
def _issue_fixture(base: Path) -> list[Path]:
"""The three cross-file patterns from #1356, plus a constructor-in-initializer."""
f1 = _write(base / "Models/SessionViewModel.swift",
"class SessionViewModel {\n func update() {}\n}\n")
f2 = _write(base / "Services/NetworkService.swift",
"class NetworkService {\n func fetch() {}\n}\n")
f3 = _write(base / "Core/SessionType.swift",
"enum SessionType {\n static func staticMethod() {}\n}\n")
f4 = _write(base / "Core/Singleton.swift",
"class Singleton {\n static let shared = Singleton()\n func method() {}\n}\n")
f5 = _write(base / "Views/HomeView.swift", (
"class HomeView {\n"
" let vm = SessionViewModel()\n"
" var svc: NetworkService\n\n"
" func go() {\n"
" vm.update()\n"
" SessionType.staticMethod()\n"
" Singleton.shared.method()\n"
" self.svc.fetch()\n"
" }\n"
"}\n"
))
return [f1, f2, f3, f4, f5]
def test_swift_cross_file_member_calls_resolve(tmp_path: Path):
# #1356: cross-file member calls (recv.method()), static/singleton calls, and
# a constructor-in-initializer must resolve to the receiver's real definition.
files = _issue_fixture(tmp_path / "src")
result = extract(files, cache_root=tmp_path / "cache")
edges = _edge_labels(result)
# Stage 1: constructor in a property initializer.
assert ("HomeView", "calls", "SessionViewModel") in edges
# Stage 2: receiver typed via the file's local type table.
assert (".go()", "calls", ".update()") in edges # vm.update()
assert (".go()", "calls", ".fetch()") in edges # self.svc.fetch()
# Stage 2: upper-cased receiver is itself a type.
assert (".go()", "calls", ".staticMethod()") in edges # SessionType.staticMethod()
assert (".go()", "calls", ".method()") in edges # Singleton.shared.method()
def test_swift_cross_file_member_calls_are_inferred_and_resolve_to_real_nodes(tmp_path: Path):
# The new edges must be INFERRED (type inference, not an explicit import) and
# land on real definition nodes so build_from_json keeps them.
files = _issue_fixture(tmp_path / "src")
result = extract(files, cache_root=tmp_path / "cache")
node_ids = {n["id"] for n in result["nodes"]}
src_by_id = {n["id"]: n.get("source_file") for n in result["nodes"]}
member_targets = {".update()", ".fetch()", ".staticMethod()", ".method()"}
seen_targets: set[str] = set()
for e in result["edges"]:
tgt_label = _label(result, e["target"])
if e.get("relation") == "calls" and tgt_label in member_targets:
assert e["confidence"] == "INFERRED"
assert e["confidence_score"] == 0.8
assert e["target"] in node_ids
assert src_by_id.get(e["target"]) # resolved to a real, source-backed def
seen_targets.add(tgt_label)
assert seen_targets == member_targets
# Edges survive graph construction (no dangling targets pruned).
g = build_from_json(result)
surviving = sum(
1 for _, _, d in g.edges(data=True)
if d.get("confidence") == "INFERRED" and d.get("relation") == "calls"
)
assert surviving >= 5
def test_swift_ambiguous_type_does_not_over_connect(tmp_path: Path):
# #543/#1219 guard: when the receiver's type name is defined in 2+ files the
# resolution must bail rather than fan a member call out to every candidate.
base = tmp_path / "src"
for sub in ("a", "b", "c"):
_write(base / sub / "Widget.swift", "class Widget {\n func update() {}\n}\n")
_write(base / "Caller.swift", (
"class Caller {\n"
" var w: Widget\n"
" func run() {\n"
" w.update()\n"
" unknown.update()\n"
" }\n"
"}\n"
))
files = sorted(base.rglob("*.swift"))
result = extract(files, cache_root=tmp_path / "cache")
inferred_calls = [
e for e in result["edges"]
if e.get("relation") == "calls" and e.get("confidence") == "INFERRED"
]
# Ambiguous `Widget` (3 defs) -> no member-call edge; unknown receiver -> none.
assert inferred_calls == []
def test_swift_unknown_receiver_emits_no_edge(tmp_path: Path):
# A lowercase receiver absent from the file's type table is never guessed.
base = tmp_path / "src"
_write(base / "Helper.swift", "class Helper {\n func help() {}\n}\n")
_write(base / "Caller.swift", (
"class Caller {\n"
" func run() {\n"
" mystery.help()\n"
" }\n"
"}\n"
))
files = sorted(base.rglob("*.swift"))
result = extract(files, cache_root=tmp_path / "cache")
edges = _edge_labels(result, relations=("calls",))
assert (".run()", "calls", ".help()") not in edges
+85
View File
@@ -0,0 +1,85 @@
from __future__ import annotations
from pathlib import Path
from graphify.build import build_from_json
from graphify.extract import extract
def _write(path: Path, text: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
def _module_nodes(result: dict, label: str) -> list[dict]:
return [
n for n in result["nodes"]
if n.get("type") == "module" and n.get("label") == label
]
def _import_edges(result: dict) -> list[dict]:
return [e for e in result["edges"] if e.get("relation") == "imports"]
def test_swift_import_resolves_to_module_node(tmp_path: Path):
# #1327: `import CoreKit` must anchor to a node, or build_from_json prunes
# the edge as a dangling/external reference.
core = _write(tmp_path / "Sources/CoreKit/CoreKit.swift", "public struct CoreKit {}\n")
feature = _write(
tmp_path / "Sources/FeatureKit/FeatureKit.swift",
"import CoreKit\n\npublic struct FeatureKit {}\n",
)
result = extract([core, feature], cache_root=tmp_path)
node_ids = {n["id"] for n in result["nodes"]}
imports = _import_edges(result)
assert imports
for e in imports:
assert e["target"] in node_ids
assert _module_nodes(result, "CoreKit")
def test_swift_same_module_imported_twice_collapses_to_one_node(tmp_path: Path):
# #1327: the same module imported from multiple files is ONE module, not N
# file-qualified duplicates — collision-disambiguation must exempt modules.
core = _write(tmp_path / "Sources/CoreKit/CoreKit.swift", "public struct CoreKit {}\n")
a = _write(
tmp_path / "Sources/AKit/AKit.swift",
"import CoreKit\n\npublic struct AKit {}\n",
)
b = _write(
tmp_path / "Sources/BKit/BKit.swift",
"import CoreKit\n\npublic struct BKit {}\n",
)
result = extract([core, a, b], cache_root=tmp_path)
# Each importing file contributes a module-node dict, but they must share a
# single id (NOT be split into path-qualified duplicates) so build_from_json
# collapses them into one shared node.
core_modules = _module_nodes(result, "CoreKit")
module_ids = {n["id"] for n in core_modules}
assert len(module_ids) == 1
# Both importers point at that single shared module id.
import_targets = {e["target"] for e in _import_edges(result)}
assert import_targets == module_ids
def test_swift_import_edges_survive_build(tmp_path: Path):
# #1327: edges must remain after graph assembly, deduped to one module node.
core = _write(tmp_path / "Sources/CoreKit/CoreKit.swift", "public struct CoreKit {}\n")
a = _write(tmp_path / "Sources/AKit/AKit.swift", "import CoreKit\n")
b = _write(tmp_path / "Sources/BKit/BKit.swift", "import CoreKit\n")
result = extract([core, a, b], cache_root=tmp_path)
G = build_from_json(result, directed=True)
import_edges = [
(u, v) for u, v, d in G.edges(data=True) if d.get("relation") == "imports"
]
assert len(import_edges) == 2
# Both edges land on the same CoreKit module node.
assert len({v for _, v in import_edges}) == 1
+34
View File
@@ -654,6 +654,40 @@ def test_rebuild_code_prunes_deleted_file_nodes(tmp_path):
os.chdir(cwd)
def test_rebuild_code_accepts_repo_relative_changed_path_for_subdir_root(tmp_path):
"""#1348: git-hook paths are repo-root-relative even when the graph root is a subdir."""
from graphify.watch import _rebuild_code
src = tmp_path / "src"
src.mkdir()
app = src / "app.py"
app.write_text("def old_name():\n return 1\n", encoding="utf-8")
cwd = os.getcwd()
try:
os.chdir(tmp_path)
assert _rebuild_code(Path("src"), no_cluster=True, acquire_lock=False) is True
graph_path = src / "graphify-out" / "graph.json"
before = json.loads(graph_path.read_text(encoding="utf-8"))
assert "old_name()" in {n.get("label") for n in before.get("nodes", [])}
app.write_text("def new_name():\n return 2\n", encoding="utf-8")
assert _rebuild_code(
Path("src"),
changed_paths=[Path("src/app.py")],
no_cluster=True,
acquire_lock=False,
force=True,
) is True
after = json.loads(graph_path.read_text(encoding="utf-8"))
labels = {n.get("label") for n in after.get("nodes", [])}
assert "old_name()" not in labels
assert "new_name()" in labels
finally:
os.chdir(cwd)
# --- #1059: pending-changes queue prevents commit drops under lock contention ---
@@ -382,7 +382,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -435,7 +437,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -589,7 +592,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -592,7 +595,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
@@ -382,7 +382,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -435,7 +437,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -589,7 +592,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
@@ -385,7 +385,9 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH')
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -438,7 +440,8 @@ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(en
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH')
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -592,7 +595,7 @@ When `graphify-out/graph.json` already exists and the user asks a question about
graphify query "<question>"
```
If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more