Compare commits

...
Author SHA1 Message Date
safishamsiandClaude Opus 4.8 ef4450d9c2 docs(changelog): fold 11 more fixes into 0.9.73
Solidity free functions (#3906), VB.NET qualified calls (#3909), Astro
frontmatter-only AST pass (#3902), surprise bonus/reason alignment (#3934),
exclude-hubs stranded-neighbour (#3933), graph-DB push index (#3957),
label retry keep-named (#3956), stale-hook status (#3951), virtual-workspace
Cargo.toml skip (#3930), and symlinked-instructions install/uninstall
handling (#3950/#3953).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-30 20:52:57 +01:00
berce c228df205e fix(install): name the symlink target when writing CLAUDE.md (#3805)
When ~/.claude/CLAUDE.md is a symlink, the registration block is written
into the file it points to, but install only printed the link path, so a
rules file elsewhere changed without any mention. Print `link -> target`
for symlinks on install and on the project-scoped removal path.

(cherry picked from commit f05abb2b25)
2026-09-30 20:41:10 +01:00
berce b30a40a171 fix(install): keep a symlinked instructions file on uninstall
When removing the graphify section leaves an instructions file empty,
uninstall deletes it. If the file is a symlink, only the link was deleted
and the graphify section stayed in the file it points to. Now uninstall
writes through the symlink instead, so the target is cleaned and the
link stays.

Applies to .claude/CLAUDE.md, CLAUDE.md, GEMINI.md, AGENTS.md,
CODEBUDDY.md and .github/copilot-instructions.md.

(cherry picked from commit cf260b5163)
2026-09-30 20:41:10 +01:00
Aditya kumar singh c5c4ee6bfd fix(manifest): treat virtual-workspace-root Cargo.toml as skipped by design (#3910)
(cherry picked from commit 89b4e4e147)
2026-09-30 20:41:10 +01:00
berce 81bb5280c0 fix(hooks): report hooks written by an older release as out of date (#3771)
Upgrading the package never touches hooks already on disk, so repos
initialised before a hook fix (such as the #2253 console-window launcher)
keep running the old script while `graphify hook status` says
"installed". Status now compares the installed graphify block with the
current template, ignoring the two per-install values (the pinned
interpreter and the viz limit export), and tells the user to run
`graphify hook install`, which already rewrites the block in place.

(cherry picked from commit 2e43d53ffa)
2026-09-30 20:41:10 +01:00
VikramLex 18d834f771 fix(label): keep labels already named when a nested retry fails to parse
_label_batch_with_retry retried the ids a truncated reply left out (#3671)
inside the try that guards the batch's own parse. A retry that still would
not parse therefore landed in this batch's except branch, which re-split the
whole batch, asking the backend again for ids it had already named, and when
that failed the same way the error discarded every name of the batch, the
ones already parsed included. Likewise, once a parse failure split a batch,
one half failing at the base case discarded the names the other half got.

Parse the batch's own reply inside the try, then retry the missing ids (all
of them after a parse failure, the plain #1278 split) outside it, one half at
a time: a half that still won't parse is recorded and the other half still
runs. A batch re-raises only when none of it could be named, so
label_communities still skips a batch that yields nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 24055dabfc)
2026-09-30 20:41:10 +01:00
Yi-111-a bab648b0c3 fix(export): index (label, id) before the graph DB push upsert loop
`push_to_falkordb` and `push_to_neo4j` upsert every node with
`MERGE (n:<Label> {id: $id}) SET n += $props`, which matches on (label, id).
Neither path created an index on that pattern first, so the engine had to
scan every node already carrying the label to decide whether the node is
already there. Each upsert then costs O(nodes with that label) and a full push
degrades to O(n^2): on the graph in #3804 (167,428 nodes / 209,215 edges
across 6 labels) throughput collapsed from ~10,000 node upserts/60s to
~100 upserts/300s partway through, with the database at ~97% CPU.

Create one index per distinct label up front, before the upsert loop. The
label set is derived exactly as the push loops derive it, so every label a
MERGE matches against is covered. Neo4j uses IF NOT EXISTS to stay idempotent
across re-pushes; FalkorDB's CREATE INDEX has no such clause, so a re-push
against an already-indexed graph is tolerated rather than failing an
otherwise valid push.

Refs #3804

Co-Authored-By: opencode space-bunny-free <noreply@opencode.ai>
(cherry picked from commit a3275e2c97)
2026-09-30 20:41:10 +01:00
neo1777 480115033d fix(cluster): keep hub-only neighbours with their hub under --exclude-hubs
With exclude_hubs_percentile set, excluded hubs are removed from the
graph that gets partitioned. A node whose only neighbours are hubs (e.g.
a local symbol of a hub file, or a dependency entry of a manifest) is
then isolated in that subgraph and came back as a singleton community,
while the hub itself was reattached by majority vote. Every such node
ended up cut off from the only node it connects to, and the community
count inflated with singletons.

Such nodes are now held out of the partition and placed after the hubs
are reattached, with the same majority vote the hubs use; since all of
their neighbours are hubs and every hub is placed by then, the vote
always has a winner. A self-loop does not count as a neighbour. True
isolates, and nodes whose only edge is a self-loop, are unchanged.

Follow-up to #919, where --exclude-hubs was introduced. The cluster()
docstring now says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 39a24a0626)
2026-09-30 20:41:10 +01:00
Kevin f9a6893844 fix(extract): parse only Astro frontmatter and scripts in the AST pass
extract_astro fed the whole .astro file to the JS grammar. The template is
not JS, so every page reported a syntax error (usually at line 1-2) and
symbols tree-sitter could not recover past the template were dropped.

Blank everything outside the frontmatter and JS <script> bodies (keeping
newlines so locations still match, as _vue_mask_non_script does) and parse
with the TS grammar, Astro's default. Scripts with a non-JS type
(application/ld+json, ...) are blanked too. The existing regex import
rescue is unchanged.

Fixes #2788. Covers the unmasked-script half of #3337.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit fe07657fe1)
2026-09-30 20:41:10 +01:00
neo1777 a20c272d46 fix(analyze): make the cross-repo/directory surprise bonus match its reason
_top_level_dir() returned the whole path when it had no "/", so two
files at the scan root (a flat folder of notes, or README.md and
setup.py) got different "top-level dirs". Every such cross-file edge
(other than suppressed INFERRED calls/uses) received +2 and the reason
"connects across different repos/directories" in surprising_connections,
which is false.

- A path without "/" now maps to the scan root ("."). "." rather than ""
  keeps root files distinct from an absolute path outside the scan root,
  whose first component is "".
- Backslashes and a leading "./" are normalized first: build_from_json
  converts backslashes but keeps "./", and serve.py's _load_graph() and
  API callers can skip build_from_json altogether.
- The comparison key is (node "repo", top-level dir). merge-graphs and
  global add keep source_file repo-relative and tag nodes with "repo",
  so two repos can share directory names; single-repo graphs have no
  "repo" and are unaffected. On merged graphs a cross-repo edge now gets
  the bonus whenever the repos differ; before, it depended on whether
  the top-level directory names happened to differ.

Tests: the flat case (fails on d6eaa8a), merged graphs, backslash and
"./" paths, plus pins for what must not change (root vs subdirectory,
root vs out-of-root absolute path).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 05d6410535)
2026-09-30 20:41:10 +01:00
rajatnagda45 4dc58d17a7 fix(vbnet): resolve type/module-qualified calls to their target method
The invocation resolver only fired for self/unqualified receivers (Me, the
enclosing type, or a bare name). A call qualified by a type or module name —
Helpers.Log(), the idiomatic way to reach a shared Module Sub — matched
nothing and produced no edge at all, so the caller was disconnected from the
method it invoked.

Map each declared type/module's short name to its owner key, and resolve a
qualified call against the receiver's owner (falling back to raw_calls for
cross-file partial-type merging). A call through a value receiver (a local
variable) still has no known owner and is left unresolved rather than
guessed (fail-closed).

(cherry picked from commit 1297c18f50)
2026-09-30 20:41:10 +01:00
rajatnagda45 85390c83a4 fix(solidity): extract file-level free functions and their calls
Free (file-level) functions have been valid Solidity since 0.7, but the
extractor only descended into named type declarations (contract, library,
interface, abstract contract). A function declared at source-unit scope —
and every call made from its body — was dropped entirely, so a file of
free utility functions produced no nodes at all.

Walk source-unit function_definition nodes, emit each as a file-contained
callable node, and resolve an unambiguous same-file free-function call to a
calls edge. Member calls (Lib.f()) are parked as raw_calls for cross-file
resolution; calls that cross into contract scope are left unresolved rather
than guessed (fail-closed).

(cherry picked from commit d2e56e932f)
2026-09-30 20:41:10 +01:00
safishamsiandClaude Opus 4.8 29eaf12174 release: 0.9.73
Rust/Zig/C++/Scala enum members as case_of nodes (#3938/#3940/#3939/#3937),
Java inherited + super call resolution (#3932), and a warn-once on
semantic file truncation (#3923).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-30 20:30:54 +01:00
rajatnagda45 5bb8a61140 fix(cpp): extract enum / enum class specifiers and their enumerators
`enum_specifier` was missing from the C++ class_types, so an `enum` or
`enum class` produced no nodes at all: the enum type and every enumerator
vanished from the graph, even though struct/class specifiers right next to
them were extracted normally.

Add `enum_specifier` to the C++ class_types — its name and body sit on the
same `name`/`body` fields as struct_specifier (type_identifier +
enumerator_list) so the type gets a node and its body is walked — and add
`_cpp_extra_walk` to emit a node plus a `case_of` edge per `enumerator`.
Anonymous enums (`typedef enum { A, B } Flag`) carry no type name and are
skipped by the existing name guard rather than emitting a nameless node.
This is the C++ parity of Java's enum_constant (#1719), Swift, and Scala.

(cherry picked from commit 9cde6c2a7f)
2026-09-30 20:16:06 +01:00
rajatnagda45 35207e9b4b fix(scala): extract Scala 3 enum definitions, their cases and methods
`enum_definition` was missing from the Scala class_types, so a Scala 3
`enum` produced no nodes at all: the enum type, its cases, and any methods
declared in its body all vanished from the graph, and references to the
enum resolved to nothing.

Add `enum_definition` to the Scala class_types and `enum_body` to the
body fallbacks so the type gets a node and its body is walked, and add
`_scala_extra_walk` to emit a node plus a `case_of` edge per case. Cases
nest under an `enum_case_definitions` wrapper as `simple_enum_case`
(`case Red`) or `full_enum_case` (`case Add(x: Int)`); both carry the case
name as an `identifier` child. This is the Scala parity of Java's
enum_constant (#1719), Kotlin's enum_entry (#1738), and Swift.

Case constructor parameter types and per-case `extends` arguments are not
linked; the case node and its case_of edge are the fix for the dropped
members.

(cherry picked from commit 175af52419)
2026-09-30 20:10:34 +01:00
kclamano b507207a1a fix(llm): warn once when file exceeds _FILE_CHAR_CAP in _read_files (#3773)
(cherry picked from commit 5f0ae1f784)
2026-09-30 20:10:34 +01:00
Jan Mohr 03ac9071fd fix(java): resolve calls to inherited methods and super
Member calls were only matched against the receiver's own type, so
this.start(), super.close() or worker.start() got no edge when the method
lives in a superclass. Walk up the extends chain and take the first
declaration. No edge if the chain leaves the project.

Fixes #3931

(cherry picked from commit a2da367fc7)
2026-09-30 20:10:34 +01:00
rajatnagda45 244f777323 fix(zig): emit a node per enum member with a case_of edge
The enum body walk only emitted an enum's methods; its members — the
`container_field` nodes (`red`, `north = 0`) — were dropped, so an
`enum { red, green, blue }` produced a node for the enum with no members at
all, leaving it a leaf.

Emit a node plus a `case_of` edge per enum member. The handler is gated on
the `enum_declaration` parent so struct and union fields, which share the
`container_field` node shape, stay untouched. This brings Zig to parity with
the other languages that have enums: Java's enum_constant (#1719), Swift,
Scala, and Rust.

(cherry picked from commit 1e44311e22)
2026-09-30 20:10:34 +01:00
rajatnagda45 b8ee397721 fix(rust): emit a node per enum variant with a case_of edge
The enum_item handler walked each variant only to collect its payload type
references (`Click(Logger)` -> Logger), but never emitted a node for the
variant itself. So an `enum Shape { Circle, Square, Empty }` produced a node
for Shape with no members at all — the enum was a leaf and its variants were
absent from the graph.

Emit a node plus a `case_of` edge per enum_variant, keyed on the variant's
`identifier` child, alongside the existing payload-type walk. This brings
Rust to parity with every other language that has enums: Java's enum_constant
(#1719), Kotlin's enum_entry (#1738), Swift, and Scala.

(cherry picked from commit 13903a8ac3)
2026-09-30 20:10:34 +01:00
safishamsiandClaude Opus 4.8 1cd9a36c0c docs(changelog): note auto-refresh of stale skills (#3895) in 0.9.72
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-29 14:59:37 +01:00
berce 8ae9878465 feat(cli): refresh stale skills after a package upgrade (#1805)
After `uv tool upgrade graphifyy` or `pip install -U graphifyy`, the
installed skills stay on the old version. `graphify install` only fixes
the platform it detects, so codex, opencode, gemini and the others keep
running outdated instructions until someone reinstalls each one by hand.

The CLI now checks the version stamp of every user-scope skill on its
first run after an upgrade, `graphify update` included, and re-copies
the ones that are older than the package. This is on by default and can
be turned off with GRAPHIFY_NO_AUTO_REFRESH=1.

It is deliberately conservative about what it touches:

- only skills graphify installed itself (stamp and SKILL.md both present)
- never a skill newer than the package, so nothing gets downgraded (#1568)
- never a directory that two installers write to, such as copilot and
  `graphify vscode install`, or two platform dirs symlinked to the same
  place, because the stamp can't say which variant lives there
- a locally edited SKILL.md is kept as SKILL.md.bak (#3144)

Install, uninstall and the refresh take the same lock per skill
directory, so two processes never write through each other's fixed
.tmp staging names, and an uninstall can't race a refresh that would
put the skill back. It is an OS file lock (flock on POSIX,
msvcrt.locking on Windows). The OS releases it however the holder
exits, so a crash never leaves a directory locked and there is no
staleness timeout to tune. The lock file lives under
~/.cache/graphify/skill-locks/ rather than in the skill directory, so a
project install leaves nothing behind in the repository. Install and
uninstall wait for the lock; the refresh skips a directory another
process holds and reads the stamp again once it has the lock. Where the
file system can't lock, install and uninstall run unlocked as they did
before, and the refresh leaves the skill to the version warning.

Output goes to stderr, one line per refreshed directory, so --json and
the MCP stdio server are unaffected. A failed refresh never breaks the
command the user actually ran: the stamp stays old and the existing
version warning still points to the manual fix.

While here, the version warning now also checks the gemini skill, which
it used to miss because gemini is not in _PLATFORM_CONFIG, and the vscode
skill path moved into _vscode_skill_destination() so install, uninstall
and the refresh share it. The README lists the new variable and mentions
the refresh in the version-mismatch troubleshooting entry.

(cherry picked from commit 50ebe642af)
2026-09-29 14:37:10 +01:00
safishamsiandClaude Opus 4.8 e40f5c44fc docs(changelog): add the 2026-09-29 batch to the unreleased 0.9.72 section
HTML node-info field fix (#3918), Kotlin annotated-inferred-property
crash (#3915/#3899), SQL DDL-before-DO (#3900), Razor @functions (#3908),
Blade @extends (#3907), and imported-module resolution (#3898).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-29 14:34:41 +01:00
harshaygadekarandClaude Opus 4.8 e34c558035 test(kotlin): add #3899's annotated-inferred-property regression test
The code fix landed via #3915 (byte-identical hoist). Keep @harshaygadekar's
independent regression test for #3884 (found simultaneously) for coverage
and contributor credit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-29 13:51:37 +01:00
nothariharan af153f85ea fix(kotlin): keep annotated inferred properties in the graph
An annotation on a class property with no explicit type never assigned
`line`, so the annotation loop raised UnboundLocalError and _safe_extract
dropped the whole file. Set `line` before the type-node check so the file
and its attribute edge both survive.

Fixes #3884

Co-Authored-By: Grok 4.7 <noreply@x.ai>
(cherry picked from commit 03ba8cc9a3)
2026-09-29 13:49:39 +01:00
harshaygadekar 95c498f967 fix(extract): ignore contained symbols when resolving imported modules (#3887)
In _resolve_python_member_calls, candidate imported modules are gathered from imported_by_filenode by checking 	 in contains_children. Following #3410, functions enclosing a nested def also have contains edges to their nested functions. When a caller imports both a module and a function from that module (where the function contains a nested def), both the module and the function matched the candidate filter because the function's _module_stem_key evaluates to the stem of its source file. The resulting len(mods) == 2 triggered the ambiguity guard and dropped all module.func() calls from that file.

Exclude contained symbols by verifying 	 not in file_of_node, which is already populated for all containment targets and excludes top-level file/module nodes.

(cherry picked from commit 542e4869ba)
2026-09-29 13:49:39 +01:00
rajatnagda45 494c08452c fix(blade): link a view to the layout it @extends
The Blade extractor recognised @include, <livewire:> components, and
wire:click bindings, but not @extends. Template inheritance is the primary
structural relationship in a Blade view — most page templates render inside
a layout via @extends('layouts.app') — so the child was left with no edge
to its parent layout in the graph.

Emit an 'extends' edge from the view to the named layout, mirroring the
existing @include handling (dotted view name -> path). Adds the first test
coverage for the Blade extractor.

(cherry picked from commit efeeeefa53)
2026-09-29 13:49:39 +01:00
rajatnagda45 4f6a4efd1f fix(razor): extract methods from @functions blocks, not just @code
@code is the Blazor (.razor) spelling of an embedded C# member block;
@functions is the equivalent Razor Pages / MVC (.cshtml) spelling. Both
compile to class members, and this extractor serves both file types, but
only @code was matched. A .cshtml page that declared its methods inside an
@functions block lost every one of them.

Match @functions alongside @code in the block regex; the existing
brace-balanced body scan and method extraction are reused unchanged.

(cherry picked from commit e3693430b3)
2026-09-29 13:49:39 +01:00
berce 452e7b7da2 fix(sql): walk block nodes so DDL before a DO block is extracted
With a bare `BEGIN;` transaction, a later `DO $$ ... END $$;` makes
tree-sitter-sql read everything from BEGIN up to the DO body's END as a
single block node. The top-level dispatch had no branch for `block`, so
every CREATE TABLE inside it was silently dropped. Walk block nodes the
same way transaction nodes are walked.

Fixes #3886

(cherry picked from commit 8f47001d5b)
2026-09-29 13:49:39 +01:00
himanshupatro-334 3394d10ccf fix: correct node info field names
(cherry picked from commit 390264da80)
2026-09-29 13:49:39 +01:00
safishamsiandClaude Opus 4.8 9fd5aadfd8 docs(readme): add contributors image (contrib.rocks)
Add a Contributors section rendering the contributor avatars via
contrib.rocks, linking to the contributors graph.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-29 11:50:32 +01:00
safishamsiandClaude Opus 4.8 4d01104edf release: 0.9.72
Atomic label sidecars (#3853), docx table/all-text extraction (#3833),
wiki index-collision (#3818) and escaped wikilink aliases (#3772),
community-listing real-node filter (#3836), warn-once on missing pypdf
extra (#3710), plus the --help logo banner + app.graphify.com line.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-28 10:37:24 +01:00
shobhitagnihotri69 2aa891be4e fix(detect): warn when pypdf extra is missing in extract_pdf_text (#3702)
Closes #3702

(cherry picked from commit 81e1c6e627)
2026-09-28 10:18:13 +01:00
shashank-100andClaude Opus 4.8 3cf033cce2 fix(watch,cli): publish label sidecars atomically, labels before signatures
Publish the community-label and signature sidecars via the existing
atomic write helper and write labels before the .sig, so an interruption
between the two leaves the .sig trailing (which the staleness guard reads
as a mismatch and safely re-labels) rather than silently keeping stale
labels for a clustering that no longer exists.

Cherry-picked from #3853 by @shashank-100; the unrelated CI-matrix change
(dropping Python 3.13/3.14) in that PR was omitted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-28 10:16:51 +01:00
ayushcodes10 f5afa6f37a Add a regression test for the community listing real node filter
Covers issue 3794 directly: a community made of real code nodes plus
a rationale docstring fragment node and a concept node must only
count and list the real code nodes in its Nodes (N) line, matching
the exact repro shape from the issue. Confirmed against pre fix code
via git stash, the test fails there and reproduces the issue's own
example output almost exactly.

(cherry picked from commit 02435f5dd3)
2026-09-28 10:15:38 +01:00
ayushcodes10 d6ff6e0984 Reuse the shared real node filter in the community listing loop
The per community Nodes count and listing loop only excluded file
nodes, so a rationale docstring fragment node or a concept node
leaked into Nodes (N) as if it were a real code declaration, and
inflated the reported count by including it. The Knowledge Gaps
section a few lines below already excluded file, concept and
rationale nodes together, the correct set an earlier issue
established for this same function, the community listing loop was
never given the same treatment.

Consolidates every real node check this function makes, the summary
thin and shown counts, the community listing, and the gaps section
isolated and thin community counts, onto one shared predicate instead
of four separate inline filters that had drifted apart. Fixing only
the display line without also fixing the count computations that
decide which communities are thin or shown would have reintroduced
the exact header versus render disagreement an earlier issue fixed,
since the header counts and the rendered content need to agree on
what counts as a real node.

Fixes issue 3794.

(cherry picked from commit 57fab42e81)
2026-09-28 10:15:38 +01:00
L4XB e27d51d7c0 fix(detect): keep tables in place and read all text in docx sidecars
docx_to_markdown wrote every paragraph first and appended all tables at the
end, so a table lost the heading it belongs to. Paragraph.text also drops
tracked insertions, content controls, fields and text boxes. And a cell's
text went into its markdown row as is, so a line break split the row and a
pipe added a column.

Walk the body in document order, read each paragraph's runs inside those
containers (skipping deleted text and the fallback copy of a text box), and
put a cell on one line with its pipes escaped.

(cherry picked from commit ee72d5256f)
2026-09-28 10:15:38 +01:00
Peter Pshenichny 5793226ff4 fix(markdown): parse escaped wikilink aliases
(cherry picked from commit f50f96f3c8)
2026-09-28 10:15:38 +01:00
breken-ai efc5a4ded3 fix(wiki): keep an article labelled index from overwriting index.md
A god node labelled index() (an ordinary web view) or a community named
after one slugs to "index", so to_wiki wrote its article to index.md and
then replaced it with the catalog; the catalog entry linked back to the
catalog itself. Reserve the index slug in the dedup set, and link the
navigation footer to index.md directly so the label resolver can map an
"index" label to its own deduplicated file.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
(cherry picked from commit aad5e0feab)
2026-09-28 10:15:38 +01:00
safishamsiandClaude Opus 4.8 17b007ab74 feat(cli): show the logo banner + app.graphify.com on graphify --help; 14-day trial copy
- The bare 'graphify' / 'graphify --help' screen now prints the logo
  banner on top (TTY-gated, reusing _print_banner) and the
  app.graphify.com hosted-platform line at the bottom, matching the
  install banner.
- Update the hosted-platform offer copy to 'Try the graphify platform
  free for 14 days' across the CLI help, the install banner, and the
  README early-access banner (was 'open free before the public v1 launch').

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-28 10:08:37 +01:00
safishamsiandClaude Opus 4.8 d6eaa8aae8 release: 0.9.71
SQL triggers (#3863), Groovy enums (#3861), R namespace-qualified
constructors (#3864) and R6 self$/private$ calls (#3865), markdown
wikilink index ignore-rules (#3826), foreign manifest key syntax (#3879),
tweet oEmbed host-only rewrite (#3880), and the refreshed install banner
(#3892).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-28 09:25:35 +01:00
rajatnagda45 aa2584c455 fix(r): resolve R6 self$ and private$ intra-class method calls
An R6 method reaches a sibling only through self$method() or private$method(),
never as a bare name, but walk_calls only handled a bare identifier callee. So
every intra-class call inside an R6 class was dropped, leaving methods that
clearly call each other disconnected in the graph.

Handle an extract_operator callee whose receiver is self or private: resolve
the method against the enclosing class scope, which is already reachable from
the caller via scope_parent. super$ is deliberately excluded — it dispatches to
a parent class this single-file pass cannot see, so a local binding would be
wrong.

Added a regression test covering both self$ and private$ calls.

(cherry picked from commit 4e00eaf105)
2026-09-28 09:14:38 +01:00
rajatnagda45 a4c6323910 fix(r): recognise namespace-qualified class constructors (R6::R6Class)
R6::R6Class(...) is the idiomatic, library()-free way to define an R6 class,
but call_parts returns the qualified text 'R6::R6Class', which never matched
_CLASS_CONSTRUCTORS. The binding therefore fell through to a plain variable
node and the entire class body — every method — was dropped. The same applied
to methods::setClass / methods::setRefClass in the statement path.

Strip the namespace qualifier before the constructor check in both the binding
path and process_call_declaration, so a qualified constructor is treated
exactly like its bare form. Unqualified declarations are unaffected.

(cherry picked from commit 513bea43c2)
2026-09-28 09:13:29 +01:00
rajarshidattapy d5f0c98fab feat(install): replace install banner with new graphify logo
(cherry picked from commit 6eb1a02460)
2026-09-28 09:13:29 +01:00
abhirupone 57a263ce8f fix(markdown): respect ignore rules when building wikilink index (#3822)
(cherry picked from commit 48a8da896b)
2026-09-28 09:13:29 +01:00
rajatnagda45 4536c5cdc0 fix(groovy): extract enum declarations and their constants
enum_declaration was missing from the Groovy config's class_types, so a Groovy
enum and every constant it declares were dropped from the graph — a consumer
could not see which value a branch selects. tree-sitter-groovy exposes the same
enum_constant shape (a name field, optional class_body) that Java uses, so the
enum type now joins class_types and the existing Java enum-constant handler is
reused to emit a node per member with a case_of edge.

Added a regression test asserting the enum type and its constants are present,
attached to the enum rather than the file.

(cherry picked from commit 2c386de21a)
2026-09-28 09:13:29 +01:00
rajatnagda45 d7e463e476 fix(sql): extract triggers and link them to their table
Two defects left CREATE TRIGGER under-extracted:

- The create_trigger AST branch read the subject table off keyword_for, but the
  table follows ON ('... AFTER INSERT ON users'); FOR EACH ROW carries no table.
  So even a cleanly-parsed trigger got a node with no link to the table it fires
  on. Read the table after keyword_on instead.

- A trigger with a procedural body ('FOR EACH ROW BEGIN ... END') has no grammar
  production, so the statement lands in an ERROR node and only the whole-file
  routine-recovery scan can save it — but that scan's pattern matched only
  FUNCTION/PROCEDURE, so the trigger and its table were dropped entirely. Add a
  dedicated trigger-recovery pattern that mints the trigger node (label without
  (), since a trigger is not callable) and a triggers edge to the table named by
  the first ON after the trigger name. A trigger already recovered via the AST
  path is skipped to avoid a duplicate edge.

Added regression tests for both the clean EXECUTE FUNCTION form and the
procedural BEGIN...END form.

(cherry picked from commit a28de74a52)
2026-09-28 09:13:29 +01:00
Daksh 1e7531fb25 fix(detect): keep foreign manifest keys in their own path syntax
_to_absolute_from_storage normalized a foreign-platform absolute key
with os.path.normpath, which applies the current platform's rules: on
Windows "/home/u/foo.py" became "\home\u\foo.py", a string POSIX cannot
read back. Collapse dot segments under the key's own syntax instead
(ntpath for a drive letter or leading backslash, posixpath otherwise).

test_save_manifest_relativize_step_collapses_seeded_duplicates never
reached save_manifest's own collapse: load_manifest already removes the
duplicate first, so the test passed with the save side reverted to
last-wins. Stub load_manifest to hand over the un-collapsed rows.

Also annotate _collapse_manifest_duplicates like its sibling helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 9db2cfe2eb)
2026-09-28 09:13:29 +01:00
Daksh c2fb556919 fix(ingest): rewrite only the host when normalizing a tweet URL for oEmbed
_fetch_tweet did url.replace("x.com", "twitter.com") over the whole URL,
so "x.com" in the path or query was rewritten too (a ?next= link, or a
handle like dropbox.com_fan becoming dropbotwitter.com_fan), and an
uppercase X.COM host was missed. Match and rewrite the host only, the
same way _detect_url_type classifies it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 3ec4fdcfca)
2026-09-28 09:13:29 +01:00
safishamsiandClaude Opus 4.8 4c21b15e9b docs: add SUPPORT.md, CODEOWNERS, and a Q&A discussion template
- SUPPORT.md routes help requests to docs.graphify.com / Discussions /
  Discord, keeps issues for bugs and the security policy for vulns.
- CODEOWNERS sets @safishamsi as default owner with explicit routing for
  the roundtrip-sensitive skillgen paths, workflows, and security/release
  docs (advisory review routing; not a merge gate on its own).
- Q&A discussion template nudges askers to check docs/search first and
  include version + environment.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-27 21:42:28 +01:00
safishamsiandClaude Opus 4.8 df65669489 docs(readme): surface docs site + CI/license badges, dedupe contributing
- Add CI status, Apache-2.0 license, and Docs (docs.graphify.com) badges
  to the top row (health signals were absent).
- Link docs.graphify.com from 'Learn more' and repoint the issue-template
  Documentation contact to the docs site (was README, 0 prior mentions).
- Replace the inline Contributing <details> block (duplicated CONTRIBUTING.md
  and prone to drift) with a short pointer to CONTRIBUTING.md/ARCHITECTURE.md;
  the issue-template Contributing link already targets CONTRIBUTING.md.
  README drops from ~64.8 KB to ~62 KB.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-27 21:29:20 +01:00
safishamsiandClaude Opus 4.8 4df8d4dcfa release: 0.9.70
Security: close the Fortran cpp #include arbitrary-file-read
(GHSA-pcc4-rvhr-2pr8), the last Aider/Devin monolith --watch shell sink
(#3852), and terraform name/value secret redaction (#3870). Plus Windows
watch rebuild locking (#3883), C# tuple element-name refs (#3877), JSX
component-usage calls (#3855), and nested scan-root Python import
projection (#3867).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-27 19:15:46 +01:00
harshaygadekar e4a6f5098e fix(watch): serialize _rebuild_lock on Windows via msvcrt
Closes #3881.

On Windows, _rebuild_lock falls back to yield True when fcntl cannot be
imported, leaving concurrent rebuilds completely unserialized and causing
file collisions on .graph.tmp.json.

Implement Windows file locking using Python's standard library msvcrt module.
Lock a byte range at offset 4096 so external readers can still read the owning
PID at byte 0 without hitting Windows mandatory lock PermissionErrors.

Un-skip the 4 rebuild lock tests and 3 pending queue tests on Windows, and
add test_rebuild_lock_blocks_concurrent_process.

(cherry picked from commit d8cd456650)
2026-09-27 18:59:12 +01:00
safishamsiandClaude Opus 4.8 e1d9deed6a security(fortran): strip #include directives before cpp (GHSA-pcc4-rvhr-2pr8)
The Fortran capital-F cpp step relied on -nostdinc -I /dev/null to block
#include-based host-file reads, but cpp always searches the source file's
own directory for quoted includes and always honours absolute paths
regardless of those flags. A malicious .F/.F90 file with
#include "/etc/passwd" or #include "../../../secret" could inline
arbitrary host files into graph.json/GRAPH_REPORT.md and the LLM context
on the default offline path (CWE-22/73/200, high severity).

Strip every #include directive before preprocessing and feed the
sanitized source to cpp on stdin, so cpp never opens the file's directory
or any absolute/traversing include path. Macro expansion (#define/#ifdef,
the actual reason capital-F files need cpp) is preserved; cross-file
include fidelity is traded away to close the arbitrary-read vector.
Feeding stdin also removes the -I/etc/x.F90 argument-injection edge case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-27 18:56:31 +01:00
nikhil2004 c66eebe25f fix(python): resolve nested scan-root imports via namespace projection (#3843)
When the scan root is a sub-directory of a monorepo package hierarchy
(e.g., root = Company/Apps/Jobs/Team/), absolute imports using the full
dotted namespace (from Company.Apps.Jobs.Team.lib import delivery) were
unresolved because the scan root probed root/Company/Apps/Jobs/Team/lib
which doesn't exist inside root.

_infer_scan_root_namespace walks above the scan root collecting ancestor
directory names that contain __init__.py, establishing the root's
namespace prefix. When an absolute import's module name starts with that
prefix, the prefix is stripped and the remainder is re-probed relative
to root.

The existing root/rel fast path, ancestor walk (#2072), ambiguous import
guard (#3729), and phantom-edge retraction (#3784) are all untouched.
Third-party imports cannot false-match because the prefix check requires
a strict dotted prefix plus a remaining local component.

Co-Authored-By: Google Antigravity <noreply@google.com>
(cherry picked from commit 640e39efc4)
2026-09-27 18:40:06 +01:00
Sinan Gümüşkabak 1990b02b00 fix(extract): skip JSX member tags
With a lowercase receiver, <icons.Close /> and <props.Comp /> resolved by the
property name and bound to unrelated local Close() / Comp() functions. None
of the member tags tried produced a correct edge, so only bare identifiers
are handled now.

(cherry picked from commit aa4be46dac)
2026-09-27 18:39:52 +01:00
Sinan Gümüşkabak a3559c2541 test: member JSX tag must not bind to a local function by its last segment
(cherry picked from commit af7ea6adaf)
2026-09-27 18:39:52 +01:00
Sinan Gümüşkabak 3a8db79305 fix(extract): add calls edges for JSX component usage
<Comp /> and <Comp>...</Comp> are parsed as jsx_self_closing_element /
jsx_opening_element with the tag in the `name` field, and neither type was
in call_types, so components that are only rendered got no incoming edge.

Add both types to the JS and TSX call_types and read the callee from
`name`. Tags starting with a lowercase letter are intrinsic elements and
are skipped; for member tags the last part decides, so <div> and
<motion.div> don't bind to a local div(). Namespaced tags and fragments
are ignored.

(cherry picked from commit 2828b55851)
2026-09-27 18:39:52 +01:00
KaiyiQuan cd7aa6cb78 test(csharp): verify user-defined tuple element types stay referenced (#3796)
Per Copilot review: the regression test must prove both halves of the fix —
element names are excluded, AND the real element type references are still
collected. Add a test using user-defined element types `(Mode mode, Label
label)`: asserts Mode/Label nodes and their references edges survive while
the names mode/label are not minted.

(cherry picked from commit 6506c32824)
2026-09-27 18:39:52 +01:00
KaiyiQuan 3c407dcb8c fix(csharp): don't collect tuple element names as type references (#3796)
A named tuple type `(int mode, string label)` is a `tuple_type` whose
`tuple_element` children carry both a `type` and a `name` field.
_csharp_collect_type_refs walked every named child, so the element NAMES
were collected as type references, minted as sourceless placeholder nodes
and emitted `references` edges — one junk type node per element, repeated
in every file declaring such a signature.

Only the `type` field of each tuple element should feed type-reference
collection; the `name` is an identifier, not a type reference. Fix the
collector to descend into the element's type field only.

Regression: tests/test_csharp_tuple_type_refs.py asserts no node/edge is
minted for element names (all existing C# tests pass).

(cherry picked from commit bfcdda97b0)
2026-09-27 18:39:52 +01:00
himanshupatro-334 286000d199 fix(skillgen): prevent INPUT_PATH shell injection
(cherry picked from commit a9551306af)
2026-09-27 18:39:51 +01:00
himanshupatro-334 fa284e9993 fix(skillgen): prevent monolith watch path injection
(cherry picked from commit a898e6890c)
2026-09-27 18:39:51 +01:00
breken-ai cb1016c405 fix(terraform): redact the value paired with a secret-named name in name/value lists
The ECS environment idiom { name = "DB_PASSWORD", value = "hunter2" } names the
secret in the name literal, not in a key, so key-name redaction let the value
reach graph.json and the MCP surface verbatim. When a map's name literal
matches the sensitive pattern, redact its value/valueFrom.

Fixes #3787

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e11cf947d0)
2026-09-27 18:39:51 +01:00
safishamsiandClaude Opus 4.8 4377ee93aa docs: add a Discord contact link to the issue template chooser
Shows a Discord button on the New Issue page so people can jump to
real-time discussion before filing. No mass backfill of existing threads.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-26 19:16:57 +01:00
safishamsiandClaude Opus 4.8 54181b5b88 ci: embed the Discord invite as a link on the words, not a raw URL
Match the GitHub Discussions link style so both point via [Discord
server](...) / [GitHub Discussions](...).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-26 19:10:07 +01:00
safishamsiandClaude Opus 4.8 ac48534d5a ci: welcome new issues/PRs and invite them to Discord
Auto-comment on every opened issue and pull request (skipping bots)
pointing contributors to the Discord server for real-time discussion and
to GitHub Discussions for longer-form threads. Uses actions/github-script;
pull_request_target is used so fork PRs can be commented on, and the job
only posts a comment (no checkout/run of PR code), so it is safe.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-26 19:08:50 +01:00
safishamsiandClaude Opus 4.8 4139885a12 release: 0.9.69
Five language-extractor enrichments (OCaml/Elixir/Fortran/Julia methods,
protocols, type-bound procs, macros/@enum, Kotlin annotations+ctor props),
tsconfig references alias resolution, spawn-safe process-pool skip,
self-loop-preserving dedup, host-based URL classification, incremental
cache_root forwarding, deterministic manifest tie-break, and a
contributor-guide/community-health docs overhaul.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-26 14:02:32 +01:00
safishamsiandClaude Opus 4.8 0115e43122 docs: align #3845 contributor guide with maintainer policy
Follow-up edits on #3845 to match the settled maintainer decisions:
- CODE_OF_CONDUCT.md: set the enforcement/reporting contact to
  safi@graphify.com (was an unspecified 'email the maintainer if known').
- README team-graph section: add the machine-local never-commit list
  (.graphify_root, .graphify_python, .graphify_analysis.json, the AST
  cache, needs_update) and the re-extract-to-update note. manifest.json
  stays committable since #3781 made its keys portable.
- Add RELEASING.md (maintainer-facing): version bump + changelog +
  uv.lock, test on 3.10/3.13, push v8, gh release create -> PyPI via
  trusted publishing (no twine/token), verify with uvx --refresh.
- CONTRIBUTING Further Reading: drop the paid Gumroad link, point at
  RELEASING.md instead.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-26 13:57:39 +01:00
nikhil2004 a30bcfaf50 docs: overhaul GitHub issue and pull request templates
(cherry picked from commit 3388311881)
2026-09-26 13:55:08 +01:00
nikhil2004 910a4d7ab1 docs: establish contributor guidelines and code of conduct
(cherry picked from commit c7fb720429)
2026-09-26 13:55:08 +01:00
nikhil2004 d5916e6a20 docs: correct factual drift in architecture and security policies
(cherry picked from commit a61eeebb29)
2026-09-26 13:55:08 +01:00
nikhil2004 98d73fe3a8 docs: clarify repository orientation and team graph sync rules
(cherry picked from commit 9d2592ea50)
2026-09-26 13:55:08 +01:00
ayushcodes10 c973b90dea Add a regression test for foreign platform absolute key detection
Covers the review finding directly: a Windows drive letter key, a
UNC key, and a POSIX absolute key must all be recognized as already
absolute regardless of which platform the test runs on, and must not
be joined onto the scan root. Confirmed against pre fix code via git
stash, the test fails there since the recognizing helper does not
exist yet.

(cherry picked from commit 33b3a7a00a)
2026-09-26 13:53:08 +01:00
ayushcodes10 007844e0c8 Recognize a foreign platform absolute key before re anchoring it
Path.is_absolute() only recognizes the current platform's own path
syntax, so a manifest key using a different platform's absolute form,
a POSIX /abs/path loaded on Windows, or a C: or UNC path loaded on
POSIX, was wrongly judged relative and joined onto the scan root,
producing a nonsense path like root plus C: colon Users colon x colon
foo dot py instead of being left alone. A manifest genuinely can move
between platforms, which is this whole module's own stated scope for
tolerating format mismatches.

A new helper checks for a leading slash or backslash or a drive
letter pattern in addition to the native is_absolute check, so a
foreign absolute key is recognized and passed through unchanged on
any platform instead of only the one that produced it.

Fixes review finding on PR 3781.

(cherry picked from commit 7f47a5fef4)
2026-09-26 13:53:08 +01:00
ayushcodes10 978c8d433b Add a regression test for the dot segment collapse gap
Covers the review finding directly: a relative manifest key with a
redundant dot dot segment must canonicalize onto the same absolute
path as a plain key for the same file and collapse with it, keeping
the more recently seen entry, instead of surviving as a second,
uncollapsed row.

Confirmed against pre fix code via git stash: the test fails there
and passes only with the fix applied.

(cherry picked from commit 7505a29bb3)
2026-09-26 13:53:08 +01:00
ayushcodes10 82514fc534 Normalize dot segments when re anchoring a manifest key
_to_absolute_from_storage joined a relative key onto the resolved
root with a plain path join, which never collapses a parent segment
the way resolve does. A relative key such as sub/../foo.py, the kind
of format mismatch this function exists to tolerate across a mix of
call sites and versions per its own docstring, then canonicalized to
a different string than the plain absolute key for the same file, so
the duplicate collapse this function exists for silently missed it.

The joined result is now run through normpath, which purely
lexically collapses dot segments without touching the filesystem or
following symlinks, matching the sibling relativize function's own
choice not to resolve the key.

Fixes review finding on PR 3781.

(cherry picked from commit e558ed93c5)
2026-09-26 13:53:08 +01:00
ayushcodes10 361b17f21a Add regression tests for the manifest duplicate key collapse fix
One test covers load_manifest directly, checking both on disk
orderings of a stale absolute entry and a fresh relative entry for
the same file, confirming the fresher one wins regardless of which
key iterates last. A companion test covers the write side, seeding a
save through an untouched file's existing duplicate rows and
confirming the relativize step keeps the fresher entry there too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 4839ae9aba)
2026-09-26 13:53:08 +01:00
ayushcodes10 45edd77b71 Break manifest key collapse ties by seen time, not iteration order
A manifest written across a mix of versions or call sites, some
passing root to relativize keys and some not, an outdated installed
skill runbook for one, can end up carrying both an absolute and a
relative key for the same file, each with different data. Both
load_manifest and the relativize step inside save_manifest already
canonicalize every key through a comprehension, so the two forms do
collapse into one entry, but a plain dict comprehension keeps
whichever raw key happens to iterate last, an artifact of on disk
JSON key order that has nothing to do with which entry is actually
current. A fresher hash could be silently discarded in favor of a
stale one purely because of how the keys happened to accumulate,
letting the incremental change detector call a genuinely changed file
unchanged.

Reproduced directly: a manifest with a stale absolute entry and a
fresh relative entry for the same file returns the stale one when it
happens to be written second, and the fresh one when the order is
reversed, confirming the collapse really is order dependent today.

Both call sites now go through one small helper that breaks a
collision by each entry's own seen timestamp when both sides have one
and they disagree, since that field exists specifically to record
when an entry was last confirmed current. A legacy or partial entry
without that field falls back to the existing last one wins behavior
unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit fc7dc25a0a)
2026-09-26 13:53:08 +01:00
L4XB dd65345e98 fix(ingest): classify a URL by its host, not by text it contains
_detect_url_type tested substrings of the whole URL, so any host ending in
x.com (dropbox.com, netflix.com, linux.com, box.com) was treated as a tweet
and saved as an empty oEmbed stub, and a name in the path or query was
enough for the arxiv, github and youtube types. Match the parsed host or
its subdomains instead.

(cherry picked from commit d48ba15fe4)
2026-09-26 13:53:08 +01:00
abhirupone cfac4d096c fix(dedup): preserve pre-existing self-loops during entity deduplication
(cherry picked from commit 80c0d8b1ff)
2026-09-26 13:53:08 +01:00
abhay-codes07 eaa35c229b fix(extract): skip the process pool up front when spawn can't re-import __main__ (#3669)
Under the spawn start method (the Windows default) each worker re-imports the
parent's __main__ by its __file__ path. A stdin (`… | python -`), `python -c`,
or REPL caller has no such file — the path is missing or `<stdin>` — so every
worker dies during bootstrap and the pool raises BrokenProcessPool before any
work is done. The shipped SKILL.md pipes a heredoc into the interpreter, so on
Windows this is the path most users take, not an edge case: every skill-driven
run prints one full worker traceback per core, then a fallback warning that
blames a missing `if __name__ == "__main__":` guard — a fix the caller cannot
apply, because there is no file to put a guard in.

Detect the unusable-__main__ case before creating the pool: when the start
method is spawn (or the platform is Windows) and __main__ has no importable
file, run sequentially and print one note that names the real cause (stdin/-c/
REPL) and the remedy (write the step to a .py file, or pass parallel=False). A
script that DOES have a __main__ file but omits the guard is a different failure
this cannot catch here; it still surfaces via the existing BrokenProcessPool
fallback, whose __main__-guard message is now accurate for that remaining case.

Tests cover the detector (stdin, REPL-without-__file__, a real script, and the
fork start method) and that extract() with >= _PARALLEL_THRESHOLD uncached files
and an unusable __main__ never attempts the pool yet still produces correct
output. All five fail without the guard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit b475196ed1)
2026-09-26 13:53:08 +01:00
abhay-codes07 ef58341357 fix(js): follow tsconfig references so solution-file path aliases resolve (#3745)
`_read_tsconfig_aliases` walks `extends` chains but never `references`. In the
standard Vite / `tsc -b` layout the root `tsconfig.json` is a solution file —
`"files": []` with `references: [{path: "./tsconfig.app.json"}, …]` — and every
`compilerOptions.paths` block lives in a referenced project config. The loader
finds the solution file, sees no `paths` and no `extends`, and stops, so every
path-alias import in the project silently produces no `imports_from` edge and
`graphify affected` returns a partial consumer set with no warning.

Follow `references` the same way `extends` is followed: merge each referenced
config's aliases like an additional parent (the referencing config's own `paths`
still override), guarded by the existing `seen` set that protects against
cycles. A reference `path` may name a directory (resolved to its
`tsconfig.json`, per `tsc -b`) or a config file directly.

Regression tests cover both the solution-file layout and a directory-valued
reference; both fail on the unpatched loader and pass with the fix. The existing
JS/TS resolution, jsconfig-baseUrl, extension-resolution and Astro suites stay
green (135 tests).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 4e84a23822)
2026-09-26 13:53:08 +01:00
rajatnagda45 6c0636c426 fix(julia): extract macro definitions and @enum types
Two core Julia constructs were dropped by the extractor:

- macro name(...) ... end produced no node, even though macros are first-class,
  heavily used definitions. The grammar gives a macro the same signature shape
  as a function, so it now mints a definition (labelled @name) and its body is
  walked for calls -- with the signature skipped so the macro does not call
  itself.
- @enum Name a b c (and the @enum Name begin ... end block form) is a
  macrocall_expression that was ignored entirely. The first identifier in the
  argument list is the enum type; the rest, including members inside a begin/end
  block, are contained by it. Other macro calls still fall through so
  definitions nested in e.g. an @testset block are walked.

Added tests covering macro extraction with body-call attribution (no self-loop)
and both @enum forms with members contained by their type.

(cherry picked from commit 87edb5a278)
2026-09-26 13:48:37 +01:00
rajatnagda45 1edda3a704 fix(ocaml): extract classes and their methods and instance variables
The OCaml walker had no branch for class_definition, so a class object --
its methods, its instance variables, and the calls made from method bodies --
was dropped entirely. A file made only of classes produced no nodes at all.

Add a class_definition branch that mints the class node (defines/contains),
walks the object body (object_expression in .ml, class_body_type in .mli) for
method and instance-variable members, and attributes calls in each method body
to that method. Method names are deliberately not registered as local defs:
they are reachable only through obj#m, so binding a bare call to a same-named
method would be a false edge.

(cherry picked from commit 63572f0cbe)
2026-09-26 13:45:58 +01:00
safishamsiandClaude Opus 4.8 2cb9743731 test(kotlin): drop dead imports, add plain-param-not-a-field negative test
Polish on #3848: remove the unused mid-file tree_sitter imports (F401)
and add a negative test asserting a bare constructor param without
val/var is not emitted as a field property.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-26 13:43:42 +01:00
nikhil2004 2b8a2972c5 fix(extract): remove fully-qualified fallback for Kotlin annotations
(cherry picked from commit 4f198dfc72)
2026-09-26 13:39:55 +01:00
nikhil2004 5757fb56e7 fix(extract): extract Kotlin annotations and primary constructor properties
Resolves #3842.

- Adds `_kotlin_annotation_names` helper to correctly extract annotations for Kotlin.
- Emits references edges with context='attribute' for class, function, and property annotations.
- Correctly skips use-site targets like `@field:` when extracting annotation names.
- Correctly parses bracketed annotations with multiple targets (e.g. `@[Inject VisibleForTesting]`).
- Traverses `primary_constructor` to extract `val`/`var` property dependencies as field edges.
- Resolves annotations using simple names to prevent dangling fully-qualified nodes.

Co-Authored-By: Antigravity <noreply@google.com>
(cherry picked from commit 579bce264e)
2026-09-26 13:39:55 +01:00
rajatnagda45 a0c1359154 fix(fortran): link type-bound procedures to their derived type
A derived type's contains section binds procedures as the type's methods
(procedure :: area => circle_area, or plain procedure :: scale), but the
derived_type_definition branch only minted the type node and ignored the
binding list entirely. The type ended up in the graph with no connection to
its own methods, and calls dispatched through the type were unrepresented.

Collect the bindings while walking the type and, after the whole tree is
walked (so the module's internal procedures already have nodes), add a method
edge from the type to each implementing procedure. A binding to a procedure
from another module resolves to a sourceless stub via ensure_named_node, the
same treatment parameter and return types already get, so the corpus rewire
can collapse it and no dangling edge is produced.

(cherry picked from commit 75f8fff533)
2026-09-26 13:39:37 +01:00
ayushcodes10 6cff8d6952 Add a regression test for the incremental cache_root leak
Covers issue 3847 directly: an incremental detect call given a
cache_root outside the scan root must not create anything under the
scan root, and the word count stat index cache file must land under
the requested cache_root instead. Confirmed against pre fix code by
restoring the prior versions of detect.py and cli.py directly, the
call raises a type error there since the parameter did not exist yet.

(cherry picked from commit d745f7b00e)
2026-09-26 13:39:37 +01:00
ayushcodes10 bbb127e5f4 Forward cache_root through the incremental extract detection path
extract with an out destination outside the scan root stayed clean on
a fresh scan, since that branch already passes cache_root to detect,
but leaked the word count stat index cache file into the scan root on
the very next incremental run against the same destination.
detect_incremental had no cache_root parameter at all, so there was
nowhere for the caller to pass it even if it wanted to, and the word
count cache fell back to anchoring at the scan root instead of the
requested out directory.

detect_incremental now accepts cache_root and forwards it into its
own internal call to detect, and the incremental branch in cli.py
passes cache_root equal to out_root, matching what the fresh scan
branch a few lines below it already does.

Fixes issue 3847.

(cherry picked from commit 9553cae7d9)
2026-09-26 13:39:37 +01:00
rajatnagda45 1ebbcdbfb7 fix(elixir): extract defprotocol and defimpl as containers
defprotocol and defimpl were not recognized as definition keywords, so the
walker fell through to generic recursion with no parent module. The protocol
and implementation nodes were never created, and their functions were attached
to the file node instead of their container (two orphaned size() nodes hanging
off the file rather than off the protocol and its List implementation).

Handle both like module-like containers: mint the protocol/impl node, contain
it in its enclosing scope, and walk the do-block so each def becomes a method
of the protocol or implementation. The implementation also gets an implements
edge to its protocol; a cross-file protocol target is filtered by the existing
dangling-edge guard rather than left hanging.

(cherry picked from commit 5f4e979693)
2026-09-26 13:39:37 +01:00
safishamsiandClaude Opus 4.8 4000de1546 release: consolidate unreleased 0.9.69 into 0.9.68
0.9.68 was bumped locally but never published to PyPI (latest published
is 0.9.67), so fold the second triage round's five PRs into a single
contiguous 0.9.68 release rather than skipping the number. No PyPI gap.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-25 16:33:01 +01:00
safishamsiandClaude Opus 4.8 636f2fe08a release: 0.9.69
Complete the skillgen --watch INPUT_PATH injection fix in the add-watch
reference (#3742), preserve cross-file edges on incremental update
(#3812), stop C# type references resolving to same-named non-type nodes
(#3815), prefer a real source location over richness in dedup (#3786),
and resolve Maven inherited groupId + ${...} properties in pom.xml
(#3823).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-25 16:22:25 +01:00
himanshupatro-334 89280317ed fix: preserve cross-file edges during incremental updates
(cherry picked from commit b6f3adffc1)
2026-09-25 16:15:15 +01:00
safishamsiandClaude Opus 4.8 8595749021 security(skillgen): neutralize the --watch INPUT_PATH sink in add-watch reference
Completes #3742: the Step 1 fix closed the .graphify_root shell line, but
the progressive-disclosure add-watch reference still passed the raw,
agent-substituted INPUT_PATH placeholder unquoted into a bash command
($(cat .graphify_python) -m graphify.watch INPUT_PATH), the same
injection class - a scan root like $(...) / ; rm ... would execute.

The watcher targets the folder graphify already extracted, so read the
trusted graphify-out/.graphify_root that Step 1 resolves (the same
sidecar pattern this reference already uses for .graphify_python)
instead of re-substituting the untrusted placeholder. Regenerated all
14 host add-watch artifacts + expected/ snapshots; monolith-roundtrip
and always-on-roundtrip stay green (cores untouched).

The identical sink in the aider/devin monolith cores is tracked
separately (editing a core requires a gen.py sanctioned-diff).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-25 16:07:51 +01:00
ayushcodes10 43026db66f Add regression tests executing Step 1 with a hostile substituted path
Extracts the real Step 1 bash block from the committed skill.md
artifact, substitutes INPUT_PATH the way an agent following the
instructions would, and actually runs it, so the fix is checked
against what users receive rather than the fragment source alone. One
test confirms a command substitution embedded in the substituted path
never runs, another confirms a semicolon separated command never
runs, a third confirms a legitimate path with a space in it still
resolves correctly, and a fourth confirms a nonexistent path still
fails the whole step loudly. All four were checked against the
pre fix block first, three failed as expected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit ad98afa9f5)
2026-09-25 16:01:53 +01:00
ayushcodes10 0dfcd7fdd9 Regenerate skill artifacts for the Step 1 injection fix
Ran the generator, then the bless command, with no manual edits.
Confirmed clean with the check, audit coverage, monolith roundtrip,
and schema singleton verification commands.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 2b41299b89)
2026-09-25 16:01:53 +01:00
ayushcodes10 c8e5bfe2bb Stop substituting INPUT_PATH into an interpreted shell command in Step 1
Step 1's own bash and PowerShell fragments both built a command whose
literal text was the resolved scan path, substituted verbatim by the
agent following the instructions before that line ever ran. The bash
form, echo dollar paren cd INPUT_PATH and pwd close paren, still
expands a command substitution even inside the outer double quotes,
and the cd itself was entirely unquoted; the PowerShell form passed
INPUT_PATH as a bare unquoted argument to Resolve Path, exposed to the
same class of problem through a stray semicolon or pipe. A path drawn
from an untrusted source, a malicious readme's suggested command, a
copied value from an untrusted page, executed as code the moment this
line ran, before any Python was ever reached.

Both now capture INPUT_PATH through a construct their own interpreter
guarantees performs no expansion at all: a quoted bash heredoc for the
posix form, a single quoted PowerShell here string for the windows
form. The raw text reaches Python (respectively Resolve Path) only as
inert data on standard input, never as source the shell itself
parses. Verified for the posix form by actually executing the
extracted Step 1 block with a malicious substituted value and
confirming no injected command runs; the PowerShell form could not be
executed in this environment (no interpreter available to install
without an interactive credential prompt), so it was written using
well established, unambiguous here string syntax and reviewed
carefully rather than run.

As a side effect of no longer building the path through an unquoted
cd, a legitimate path containing a space is now handled correctly
too, and a nonexistent path now fails the whole step loudly instead
of silently continuing past a swallowed cd error.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 9a7e5d0a51)
2026-09-25 16:01:53 +01:00
ayushcodes10 d7e3c6f7f2 Add a regression test for the stray source_location gate
Covers the review finding directly: a candidate with a
source_location but no source_file must not out rank a fully bare,
richer candidate. Confirmed against pre fix code via git stash, the
test fails there and passes only with the fix applied.

(cherry picked from commit f6afc87140)
2026-09-25 16:01:47 +01:00
ayushcodes10 9bc077b907 Gate the source_location tiebreak on a real source_file
A stray source_location with no source_file, a location pointing at
an unstated file, which _merge_missing_attributes can produce by
backfilling one field but not the other when a survivors own
source_file is an empty string rather than None, was still granted
an edge over a fully bare candidate by the location tiebreak, even
though neither side actually has real provenance. The tiebreak now
only counts source_location when source_file is present too, so a
location with no file falls through to richness like any other bare
field would.

Fixes review finding on PR 3786.

(cherry picked from commit 3b3cc81541)
2026-09-25 16:01:47 +01:00
ayushcodes10 a71ee67d7c Add regression tests for the source_location provenance tiebreak
Covers the review finding directly: a record with a source_file but
no source_location must not lose to a richer, unlocated stub that
also carries a source_file, and the tiebreak must stay inert when
both sides already have a real location, preserving the existing
richness ordering there.

Confirmed against pre fix code via git stash: the direct repro test
fails there and passes only with the fix applied.

(cherry picked from commit 4915270490)
2026-09-25 16:01:47 +01:00
ayushcodes10 f7092b45d5 Extend the provenance tiebreak to source_location too
source_location is richness ignored the same way source_file already
is, so two candidates that both carry a source_file could still be
ordered by field count alone, letting a record with no real location
out score one that also knows exactly where in the file it lives. The
codebase genuinely emits source_location as None on some records, so
this is a real distinction, not a hypothetical one. The tiebreak now
checks source_location as a second provenance step, after source_file
and before richness, and only changes the outcome when the two sides
disagree on having one.

Fixes review finding on PR 3786.

(cherry picked from commit 1d33a488e0)
2026-09-25 16:01:47 +01:00
ayushcodes10 699d18f760 Add regression tests for the pick winner provenance tiebreak
One test is the issue's own exact reproduction, a source less stub
that genuinely out scores a real located declaration on field count
alone, checked in both argument orders. A companion test confirms the
provenance tiebreak stays inert when both candidates carry a source
file, so the existing richness then length ordering this file already
established is untouched. The first test was checked against the pre
fix code and failed there as expected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 0e155019e3)
2026-09-25 16:01:47 +01:00
ayushcodes10 02b32f4cfe Give a real source location priority over richness in pick winner
source_file and source_location are both in the set of keys the
richness score deliberately ignores, since #3372 added that score to
compare actual content, not placement. That leaves richness with no
way to tell a real, located declaration apart from a source less
stub that happens to carry a couple of incidental bookkeeping keys,
letting the stub out score and replace the genuine record purely on
field count.

Provenance is now checked ahead of richness in the survivor scoring
tuple, so a node with a real source location always wins over one
without. This only changes the outcome when the two sides actually
disagree on provenance; every case where both, or neither, side
carries a source file keeps the exact ordering the richness fix
already established.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit a9180c0da7)
2026-09-25 16:01:47 +01:00
himanshupatro-334 bb373632d6 fix: prevent C# member nodes from being resolved as types
(cherry picked from commit 25de4ace89)
2026-09-25 16:01:47 +01:00
himanshupatro-334 769851dfae fix: exclude non-types from C# type resolution
(cherry picked from commit dfe5a220b2)
2026-09-25 16:01:47 +01:00
Vladimir Babin cac084cf3d fix(manifest_ingest): resolve inherited groupId and ${...} properties in pom.xml (#3806)
(cherry picked from commit 292b9d8465)
2026-09-25 16:01:47 +01:00
safishamsiandClaude Opus 4.8 d197ae36fa release: 0.9.68
Windows hash-seed re-exec wait (#3816/#3799), Terraform secret-named
variable-default/output redaction (#3817), COBOL fixed-format
sequence-number detection (#3813) and PERFORM...THRU both-endpoint
linking (#3814), and gate the GRAPH_REPORT undocumented-components
reason on a real semantic layer (#3828/#3801).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-25 15:54:48 +01:00
ayushcodes10 88776942ef Add regression tests for the undocumented components gate
Covers issue 3801 directly: a code plus concept only graph (no
document, paper or image nodes anywhere) must not offer undocumented
components as a reason for an isolated node, only possible missing
edges. Adding a single document node elsewhere in the same graph
shape brings the fuller reason back, confirming the gate tracks the
graph's actual content rather than being tied to a particular test
fixture shape.

Confirmed against pre fix code via git stash: the first test fails
there and passes only with the fix applied.

(cherry picked from commit 02e1b4d6c2)
2026-09-25 15:44:21 +01:00
ayushcodes10 6b6778aede Gate the undocumented components reason on a real semantic layer
GRAPH_REPORT.md's Knowledge Gaps section always offered undocumented
components as a possible explanation for an isolated node, regardless
of whether the graph could ever actually have one. That phrase only
means anything when a semantic layer exists, document, paper or image
nodes an LLM extracted meaning from, where an isolated node genuinely
could be mentioned but never explained further. A code only graph has
no such nodes at all, so offering it as a live possibility on every
report is misleading.

The reason now checks whether any node in the graph carries a
document, paper or image file_type before including that clause,
using the same VALID_FILE_TYPES distinction validate.py already
draws between the semantic layer and code/rationale/concept nodes, so
no new build time flag is needed.

Fixes issue 3801.

(cherry picked from commit 8a49e1f38a)
2026-09-25 15:44:21 +01:00
breken-ai 0dd9f8ba5c fix(terraform): redact secret-named variable defaults and output values
A variable or output names its secret in the block label, so the literal
sits under the generic key default/value and the key-name check never
flags it: variable "db_password" { default = "..." } reached graph.json
verbatim. Redact default/value when the label matches the sensitive-key
pattern or the block sets Terraform's own sensitive = true.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
(cherry picked from commit 01e417166b)
2026-09-25 15:44:21 +01:00
Sinan Gümüşkabak f3483171b9 fix(cli): wait for the hash-seed re-exec on Windows instead of os.execvpe (#3799)
On Windows os.exec* does not replace the process: CPython spawns a new one
and the caller exits at once, so update/extract/cluster-only/label returned
before graph.json was written, and the exiting parent intermittently died
with an access violation (exit 139). Run the child with subprocess, wait for
it and propagate its exit status there; POSIX keeps the real os.execvpe.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
(cherry picked from commit 94a9657e93)
2026-09-25 15:44:21 +01:00
abhay-codes07 45ceb2273a fix(cobol): link both endpoints of a PERFORM ... THRU range
`PERFORM A THRU Z` (and `THROUGH`) runs the whole paragraph range A..Z, but the
PERFORM pattern captured only the first name, so a `calls` edge was emitted to A
and the range-end Z got none. "What performs Z?" then answered nothing even
though this paragraph does, and any reachability walk stopped short of the
range's tail.

Capture the optional `THRU`/`THROUGH` target and enqueue both endpoints for
resolution against the paragraph table. Intermediate paragraphs in the range are
not individually linked (that would need paragraph source ordering); the two
endpoints are the reliable, common signal and both now resolve. A plain
`PERFORM A` is unchanged.

Regression test: `PERFORM A-PARA THRU Z-PARA` now links MAIN to both A-PARA and
Z-PARA (fails on the old single-capture pattern).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit abcdde1a65)
2026-09-25 15:44:08 +01:00
abhay-codes07 81afa16bd9 fix(cobol): detect fixed-format source that carries sequence numbers
The fixed/free format detector counted a line as fixed-format only when its
first six columns were blank (`^ {6}[ *\-/ ]`). Legacy mainframe COBOL — the
main reason to have a COBOL extractor — puts a sequence NUMBER in columns 1-6,
so every such file scored zero fixed markers and was classified free-format.

In free mode the code is taken verbatim (no column-8 slice), so the sequence
number stays glued to the statement: `000400 MAIN-PARA.` no longer matches the
paragraph anchor `^NAME .? .$`, and the whole procedure layer disappears. A
seven-line program with two paragraphs and a PERFORM collapsed to just the file
and program nodes — zero paragraphs, zero `calls` edges — silently.

Match a sequence area that is six spaces OR six digits, followed by a valid
indicator column (space = code, `*`/`/` = comment, `-` = continuation, `D` =
debug). Once the file is correctly read as fixed-format the existing
column-8..72 slice strips the sequence number and paragraphs/PERFORMs resolve
as they should. Blank-sequence fixed-format and genuinely free-format source are
unaffected (a 6-digit prefix is not something free-format code begins a line
with).

Regression test: a sequence-numbered program now yields its program, both
paragraphs, and the PERFORM `calls` edge — and fails on the old detector.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 96b9522bd5)
2026-09-25 15:43:14 +01:00
safishamsiandClaude Opus 4.8 8e09034743 docs: standardize the Discord invite to discord.gg/XDnKVpzdXB
Point the README and he-IL translation at the single current invite (the old 2DDrEgvZb4/598Ad9zQZ links are retired). All Discord references now resolve to one canonical invite.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-25 13:52:21 +01:00
safishamsiandClaude Opus 4.8 fe566710cc docs: add community banner for the Discussions welcome post
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-25 13:29:51 +01:00
safishamsiandClaude Opus 4.8 4c735618f3 release: 0.9.67 — Windows hash-seed re-exec fix, PHP closures, absolute Python import resolution, package/module phantom-cycle fix, terraform list-secret redaction, idempotent wiki/Obsidian writes
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-23 20:23:51 +01:00
safishamsiandClaude Opus 4.8 793aca6714 test(php): cover file-scope, no-duplicate, and method-scope closures (#3409/#3461 follow-up)
#3461 fixes #3409 (PHP closures produce no nodes / inner calls lost). Adds the
coverage its tests omitted:
- the reporter's exact repro — a FILE-SCOPE argument-position closure — asserting
  the closure node exists AND its inner call resolves to the closure (not the file);
- a no-duplicate-node assertion guarding the walk partition against double-walk;
- a method-scope closure asserting its inner call attributes to the closure, not
  the enclosing method (pins the function_boundary_types behavior).

Verified end-to-end: closure->handler() edges attribute to {closure#N} nodes with
no duplicates.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-23 19:45:40 +01:00
nikhil2004 95dd8cf9a0 fix(php): allow relative prefixes in route groups and correctly fail tests on extractor error
(cherry picked from commit 29ed19f1e4)
2026-09-23 19:42:04 +01:00
nikhil2004 4c74bd68fe fix(php): prevent closure fallback leak and support fluent routing prefixes
(cherry picked from commit b8e2033e3c)
2026-09-23 19:42:04 +01:00
nikhil2004 904deaecab fix(php): prevent non-route closures from adopting parent route names
(cherry picked from commit 9d592e6996)
2026-09-23 19:42:04 +01:00
nikhil2004 10f144de06 fix(php): match correct AST node names and scan nested closures
(cherry picked from commit ceb961a6b3)
2026-09-23 19:42:04 +01:00
nikhil2004 435f5a88e9 refactor(extract): hoist PHP route helper to module level (#3409)
Address maintainer nits by moving _php_get_route_name and the
_PHP_ROUTING_VERBS frozenset out of the _extract_generic body
to the module level, preventing them from being repeatedly
re-initialized per file on large codebases.

(cherry picked from commit e845f15b68)
2026-09-23 19:42:04 +01:00
nikhil2004 8227c468c2 fix(extract): robust PHP nested routing closure extraction (#3409)
Address edge cases identified in review:
- Nested route closures (e.g., inside group() or prefix()) now correctly compose their full path by walking up the AST across closure boundaries.
- Non-routing closures passed to methods that share verbs (like ->get('user:42')) are no longer misidentified as routes. A route path must begin with '/' to qualify, otherwise it correctly falls back to an ordinal name.

(cherry picked from commit 38861aa1c4)
2026-09-23 19:34:18 +01:00
nikhil2004 2c172e4969 fix(extract): stable closure naming for PHP (#3409)
Address reviewer feedback:
- Replace line-based {closure@N} names with stable ordinal {closure#N}
  names scoped per enclosing class or file. Ordinals are unaffected by
  line insertions/deletions above a closure; only reordering closures
  or inserting one earlier in the same scope shifts later ordinals,
  which is a much rarer edit.
- Route closures passed to routing verbs (get/post/put/patch/delete/
  options/any/match/map) receive a semantic 'VERB /path' label that
  is both stable and directly meaningful to graph queries (the primary
  use-case from the issue).

Note: adding anonymous_function_creation_expression and arrow_function
to function_boundary_types (introduced in the first commit) means calls
inside a closure now attribute to the closure rather than the enclosing
named function. This is the correct behaviour; existing codebases with
closures inside named functions will see those edges move on next
incremental update.

(cherry picked from commit 5400b9cbd7)
2026-09-23 19:34:18 +01:00
nikhil2004 cd3fd9436e feat(extract): support PHP closures (#3409)
The bug:
PHP closures (`anonymous_function_creation_expression` and `arrow_function`)
were invisible to the graph, disconnecting API routes and callbacks from
the backend code.

The fix:
- Added closure syntax node types to _PHP_CONFIG's `function_types`.
- Updated engine.py to synthesize line-bound names (e.g., `{closure@42}`)
  for unnamed closures matching these AST node types, enabling them to be
  extracted as linkable nodes in the graph without ID collisions.

(cherry picked from commit c8c3af1960)
2026-09-23 19:34:18 +01:00
safishamsiandClaude Opus 4.8 f2b65b78ec fix(python): reconcile #3784 phantom-edge retraction with #3729 package imports
#3729 (absolute package import resolution) and #3784 (retract phantom
package/module-collision import edges) landed in the same cut and interacted: a
legitimate `from pkg import sub` (pure package, no colliding pkg.py) now resolves
its provisional edge to the real `pkg/__init__.py` node, but #3784 retracted it —
via the __init__.py candidate id and the len==1 blind fallback — even though there
is no name collision (no phantom cycle to fix). This dropped the correct
package-dependency edge (caught by test_absolute_package_import_targets_package_init).

Tighten #3784 to retract ONLY genuine module-collision phantoms: drop the
__init__.py candidate id forms (keep the module-file `pkg`/`pkg.py` collision ids
that the #3777 fix actually targets) and remove the len==1 blind fallback (a real
phantom always matches by its module-file id, so no fallback is needed). Both the
#3729 package-import tests and all 26 #3784 phantom-cycle tests now pass together.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-23 17:38:41 +01:00
himanshupatro-334 310b317355 fix: retract provisional package import edges
(cherry picked from commit 9a54565cb4)
2026-09-23 17:02:17 +01:00
Ha1baraA11 3792ff1fda fix: preserve loose sibling import resolution
(cherry picked from commit 61e3b8fcbc)
2026-09-23 17:01:39 +01:00
Ha1baraA11 45e9af94db fix: guard ambiguous absolute Python imports
(cherry picked from commit 238c9df3d0)
2026-09-23 17:01:39 +01:00
Ha1baraA11 1c12006360 fix: resolve Python imports within scan root
(cherry picked from commit 962a0569b1)
2026-09-23 17:01:39 +01:00
Ha1baraA11 2944b2d8ec fix: resolve absolute Python package imports
(cherry picked from commit f1b880c726)
2026-09-23 17:01:39 +01:00
abhay-codes07 3454890057 fix(export): stop rewriting unchanged wiki/Obsidian pages on every run (#3060)
`to_wiki()` and `to_obsidian()` regenerate the full page set on every call and
write every page unconditionally — `to_wiki` even unlinks every `*.md` up front,
guaranteeing a full rewrite. An export re-runs on any graph.json change, so on
an always-on `watch`/export setup this rewrites tens of thousands of identical
pages per run (measured: 31,417 pages / 137 MB per export, ~7 GB/day), and each
rewrite is also a modification event that re-fires Obsidian re-indexing, sync
clients, and downstream inotify pipelines for content that did not change.

Compare before writing:

- New `paths.write_text_atomic_if_changed(path, text) -> bool` writes (and
  reports True) only when the content differs from what is on disk, comparing
  DECODED text — text-mode writes translate `\n`↔`\r\n` on Windows, so a byte
  compare would report every file changed.
- `export._owned_write` uses it and still records the note in `_written`
  (the ownership + prune-exclusion set, #1896), so an unchanged note stays owned
  and is neither pruned nor dropped from the manifest.
- `to_wiki` drops the up-front unlink-all — which forced the rewrite and opened
  a window where a reader saw an empty `wiki/` mid-export — for an end-of-run
  sweep that removes only the `*.md` this run did not produce, keeping the same
  orphan guarantee for relabelled/removed communities.

Tests: the helper skips an identical write (mtime untouched) and writes on a
diff or a missing file; an Obsidian re-run leaves an unchanged note's mtime
untouched yet still owned (not pruned) and still rewrites a note whose body
changed; a wiki re-run leaves unchanged articles untouched and still sweeps a
relabelled community's stale page. The wiki/export/obsidian suites stay green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 91546de3b4)
2026-09-23 16:54:04 +01:00
abhay-codes07 7b2ac86e09 fix(terraform): redact secrets nested inside list values, not just maps (#3644 follow-up)
`_redact_value` (the #3644 guard that keeps hardcoded credentials in .tf files
out of graph.json and the MCP query/get_node surface) recursed into map values
but not list values. HCL routinely nests objects inside tuples —
`list(object(...))` variables, `dynamic` blocks, tuple defaults — and
`_parse_attr_value` turns those into Python lists of dicts, so:

    config  = { password = "x" }      -> redacted   (map recursion)
    configs = [{ password = "x" }]    -> LEAKED      (list not recursed)

The list form left the secret in the serialized node verbatim, defeating the
guard for a very common Terraform shape (a `connections`/`containers`/`secrets`
tuple of objects).

Recurse into lists and tuples as well, under the same key — the list branch is
only reached when the key is not itself sensitive (a sensitive key redacts the
whole value above), so a scalar element carries no key signal and is returned
as-is while a dict element is checked against its own inner keys. A non-secret
list of scalars is untouched.

Tests: a unit check that a secret inside a list-of-objects and a nested list is
redacted (while a sensitive key still redacts the whole list and a plain scalar
list is left intact), and an end-to-end check that a `password`/`token` inside a
tuple-of-objects attribute never reaches the serialized node. Both fail without
the fix. The terraform suites otherwise stay green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 2998cb2121)
2026-09-23 16:54:04 +01:00
ayushcodes10 6a1a432de8 Update hash seed tests for the module based re exec and add a regression
The existing probe assertions now expect the module flag form. A new
test drives the probe with a launcher stub path that is not even a
real file in place of argv zero, confirming the fix no longer depends
on it being anything runnable, the exact shape of the Windows uv
launcher regression this closes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit e2fd1c4f30)
2026-09-23 16:54:04 +01:00
ayushcodes10 d9d4756506 Re exec the hash seed pin as a module, not by replaying argv[0]
The previous form replayed sys.argv[0] as the script path to run,
which happens to work for a POSIX console script wrapper or a python
dash m invocation, both of which are real, runnable Python content.
It does not work for a uv, pip, or pipx console script launcher on
Windows, which installs as a native executable stub with no such
content, so the interpreter has nothing to open and every affected
command failed outright the moment it tried to pin the seed.

Re execing through the module flag instead never depends on argv[0]
being anything runnable at all, so a launcher stub that is not even a
real file no longer matters, and this now matches the exact
invocation shape the end to end test for this function already
exercised and proved working.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 6509f609dc)
2026-09-23 16:54:04 +01:00
safishamsiandClaude Opus 4.8 a5957aa6ef release: 0.9.66 — five new language extractors (COBOL/VB.NET/R/Solidity/Erlang), deterministic PYTHONHASHSEED builds, Go interface + Rust generic resolution, Cargo workspace/subdir handling, method-ghost dedup, serve id-aliases, install CRLF fix, labeling retry, stale-root fallbacks
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-22 22:39:40 +01:00
ayushcodes10 f49ec5038c Add regression tests for the shared output graphify root marker fix
One test sets a shared, absolute GRAPHIFY_OUT and confirms the marker
written by an update from a relative path is resolved to an absolute
form. A companion test confirms the ordinary, relative GRAPHIFY_OUT
case still preserves the caller supplied relative path exactly as the
existing 777 test already expects, so this fix only changes the
shared output case.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 181a46dca9)
2026-09-22 17:30:28 +01:00
ayushcodes10 5439e6d1f3 Resolve the graphify root marker when GRAPHIFY_OUT is shared and absolute
Update writes a raw, caller supplied watch path into the graphify_root
marker, which #777 deliberately chose over a resolved absolute so a
committed marker file stays portable across clones and CI runners.
That is fine as long as every reader of the marker runs with the same
CWD it was written from, which normally holds since the generated git
hooks and an unqualified graphify watch both assume it.

It stops holding once GRAPHIFY_OUT is set to an absolute, shared
location, the multi worktree setup from #686. The same marker file is
then reachable from any worktree's CWD, so a relative value like the
dot from graphify update dot resolves against whichever worktree
happens to read it later instead of the one that was actually
scanned, silently falling back to the wrong scan root.

Add a small helper that only resolves in that shared, absolute case
and otherwise keeps the existing relative behaviour untouched, so the
777 portability guarantee for the common, single clone case is
preserved rather than reverted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit e36edf8462)
2026-09-22 17:30:28 +01:00
Ha1baraA11 78b42dfcdc fix(build): fall back from stale graphify root
(cherry picked from commit 1717695609)
2026-09-22 17:30:28 +01:00
Ha1baraA11 1db41f0bef fix(labeling): retry and report partial community labels
(cherry picked from commit 315974e0a5)
2026-09-22 17:30:28 +01:00
ayushcodes10 d8dd477836 Add regression tests for the install CRLF and idempotency guard fix
Cover an unrelated mention of the word graphify no longer suppressing
the real registration block, a stale or hand edited block correctly
getting refreshed on re install instead of being left alone, and both
the CLAUDE.md and GEMINI.md writers now passing newline equals empty
string so an existing file's own line endings are never translated on
write.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit ddf2497f68)
2026-09-22 17:30:28 +01:00
ayushcodes10 f07423b8da Fix CRLF corruption and a bare substring idempotency guard in install
_register_always_on_block had three problems, all only visible on the
claude and codebuddy paths that call it. Path.write_text opens in
text mode, so on Windows appending a few lines to an existing
CLAUDE.md rewrote the WHOLE file to CRLF, turning a one line
registration into an eighty five line diff for anyone who keeps that
file in a dotfiles repo or syncs it across platforms. Separately, the
re install guard was a bare check for the word graphify anywhere in
the file, so a user whose file mentioned the project for any other
reason got silently treated as already registered and never received
the real block, and an edited or stale block could never be repaired
by re running install since the word was still present either way.

Switch the write to pass newline equals empty string so existing line
endings are never translated, and switch the guard to
_replace_or_append_section, the same marker anchored helper
claude_install and gemini_install already use, so a stale block is
correctly refreshed instead of silently skipped. That helper's
boundary detection was hardcoded to the next H2 heading, which does
not fit this block's own heading level, so it gains a boundary_prefix
parameter mirroring the one _remove_marker_section already has, kept
in sync with a new shared marker constant so the paired removal
function matches on exactly the same heading. Deliberately kept at H1
rather than switched to the H2 markers the issue itself suggested,
since the existing removal function anchors on H1 specifically to
never collide with a genuine user authored H2 heading elsewhere in
the same file, a design choice from a separate earlier issue that a
plain heading level change would have quietly broken.

gemini_install writes GEMINI.md through the exact same text mode
write, so it gets the same newline fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit c325aad3b0)
2026-09-22 17:30:28 +01:00
ahm3dwasim a1d2318e50 fix(serve): get_node/get_neighbors accept node_id/id, not just label
The two node-lookup MCP tools read arguments["label"] directly, so a client
that passes the node identifier under "node_id" (or "id") gets a
KeyError('label') instead of a result. Several of the agent frameworks graphify
advertises support for send the argument that way, so the tools are unusable
from those clients while query_graph/god_nodes work fine against the same graph.

Extract a small module-level _node_arg() that accepts label/node_id/id, return
a short guidance string when none is given (instead of raising), and declare
node_id in both inputSchemas so the parameter is discoverable. Add a unit test.

(cherry picked from commit cf84c59735)
2026-09-22 17:30:28 +01:00
oleksii-tumanov 7a508a71bd fix(cargo): resolve inherited workspace dependency identity
(cherry picked from commit 4d8fa2e93c)
2026-09-22 15:00:07 +01:00
ayushcodes10 9b42507014 Add regression tests for cargo subdirectory manifest discovery
Cover a Tauri style layout where the manifest lives one level down and
must still be found, a discovered workspace manifest whose own
members resolve relative to its own directory rather than the outer
scan root, a decoy manifest inside a dependency install folder that
must never be searched into, and a manifest nested past the discovery
depth cap that is correctly left unfound.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 6d2ef5455f)
2026-09-22 14:58:22 +01:00
ayushcodes10 165a7da4a1 Discover a Cargo.toml in a subdirectory when none sits at the scan root
introspect_cargo only ever looked at root divided by Cargo dot toml,
with no search, so any repository whose crate lives in a subdirectory
got no crate nodes or dependency edges at all, even though the AST
pass had already parsed every rs file there. The common case is a
Tauri app, whose default scaffold keeps its manifest under its own
frontend adjacent crate folder rather than the project root.

Add a bounded depth search that only runs when the root manifest is
missing, reusing the same noise directory pruning the AST scanner
already applies so a vendored or example manifest nested inside a
dependency folder never wins over the project's own. A workspace
manifest found this way now resolves its own members relative to its
own directory rather than the outer scan root, since those two can
now differ.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 577e51749a)
2026-09-22 14:58:22 +01:00
ayushcodes10 137ead6d56 Add regression tests for cargo extraction with a missing manifest
One test runs extract with the cargo flag against a repo that has no
Cargo.toml at all and confirms it still succeeds and still writes the
graph built from the code already indexed, with a note explaining the
crate edges were skipped. A companion test confirms a repo that does
have a valid manifest still gets its crate node, so the fix only
changes the missing manifest path.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit a9b14fef06)
2026-09-22 14:58:22 +01:00
ayushcodes10 b11b035722 Degrade instead of aborting when cargo introspection finds no manifest
FileNotFoundError is a subclass of OSError, so a missing Cargo.toml at
the scan root was caught by the same handler meant for ImportError
and connection failures and exited the whole process. That fires
after the AST pass has already completed, discarding every file of
completed structural extraction work just because an optional
enrichment source found nothing to read, an ordinary condition for
any repo whose manifest lives in a subdirectory, such as a Tauri app
that keeps it under its own separate frontend adjacent crate folder.

cargo_result already starts as the empty, handled shape the merge
step downstream expects, so catch FileNotFoundError on its own, print
a note, and let extraction continue with an empty cargo result instead
of exiting.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 94cc22be3b)
2026-09-22 14:58:22 +01:00
ayushcodes10 890856f873 Add regression tests for the hash seed pinning fix
Since a real re exec replaces the process it runs in, every test that
needs to observe whether it fired runs a small probe in its own
subprocess with a deliberately constructed environment, rather than
mocking inside the pytest process itself, which pytest's own handling
of its current test marker would defeat anyway. Cover each of the
four affected commands re executing with the seed pinned when unset,
an explicit seed never being overridden, unrelated commands never re
executing, the guard against firing while pytest itself is mid test,
a failed re exec being survived rather than raised, and a full real
invocation of update still completing successfully end to end through
the whole re exec.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 2f5f2d705e)
2026-09-22 14:58:13 +01:00
ayushcodes10 3d1a03ef2a Pin PYTHONHASHSEED for update, extract, cluster only and label
The generated git hooks already export PYTHONHASHSEED=0 because
networkx's Louvain implementation iterates string keyed sets whose
order is randomized per process, so community assignments otherwise
churn between runs with no code change. A bare graphify update, which
the CLAUDE.md template tells agents to run after every code change,
skipped this, clustering differently every time and producing a
large, spurious diff in the output directory.

PYTHONHASHSEED is read once at interpreter startup, so setting it on
os.environ from inside an already running process has no effect on
that process's own hash randomization. The only way to pin it for a
command already in flight is to restart the interpreter with it set
from the start, so main() now re execs itself with the seed set
before doing anything else, for exactly the commands whose output
depends on clustering, only when the caller has not already chosen a
seed themselves, degrading instead of raising if the re exec itself
fails so an unusual host that disallows it can still run graphify.

Skips this entirely while running under pytest, detected via the
PYTEST_CURRENT_TEST variable pytest itself sets for the duration of
a running test. Dozens of existing tests call main() directly with a
monkeypatched argv to simulate a full CLI run in process, which only
worked because main() was previously free of this kind of side
effect; without the guard, every one of those calls replaced the
test process running them the moment PYTHONHASHSEED happened to be
unset, which it normally is in a dev or CI environment, with no
traceback or error, just an empty, silently green test run.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit b70382ceda)
2026-09-22 14:58:12 +01:00
carterko23 081004f60b fix(go): repoint intra-module imports_from edges from go_pkg_ sinks to the package's files
extractors/go.py mints every import target as `go_pkg_<raw import string>` with
no module lookup, so an intra-module import never reaches a file: the sink has
no source_file and nothing links it onward. `affected` and any reachability
walk miss every consumer that arrives through an import, while qualified calls
(`b.F()`) resolve, because the call pass already filters callees by
_go_import_path_for_file. This inverts that mapping once per run and repoints
the intra-module `imports_from` edges onto the imported package's file nodes,
the way the JS/TS resolver repoints module specifiers. Stdlib and external
imports have no file in the corpus and stay sinks by design.

Measured on a 744-file single-go.mod module, same commit, with and without
this change: a 111-file handler package goes from 0/21 direct intra-module
imports resolved to 21/21 (24/24 transitive); the 57 intra-module go_pkg_
nodes disappear; +16,616 imports_from edges; no other relation changes.

Closes #3746

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit fb40961f4a)
2026-09-22 14:58:12 +01:00
oleksii-tumanov f7bc904bda Preserve case-only interface signature owners
(cherry picked from commit 72d5914a10)
2026-09-22 14:58:12 +01:00
oleksii-tumanov bda82f9ded fix(go): preserve interface method signature references
(cherry picked from commit 00fb309983)
2026-09-22 14:58:12 +01:00
safishamsiandClaude Opus 4.8 6fdc26db03 build: lock the new grammar deps for the R/Erlang/Solidity/VB.NET extractors
Regenerated uv.lock to add tree-sitter-language-pack (R + Erlang grammars),
tree-sitter-solidity, and tree-sitter-vb-dotnet (+ transitive embedded-template,
yaml) that the 0.9.66 extractor batch introduced. uv lock --check passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-22 14:53:59 +01:00
safishamsiandClaude Opus 4.8 0e855f3b40 fix: complete the Solidity/method-ghost/Erlang review items (#3716, #3719, #3714 follow-ups)
- #3716 (Solidity): non-callable members (struct/enum/event/error/state-var) had
  no signature and fell back to the LINE NUMBER for their node id, churning ids on
  incremental rebuilds. Use the member name (unique per kind in a contract scope)
  as the discriminator instead.
- #3719 (method-ghost dedup): gate the candidate index on a method-shaped label
  (leading '.' AND '()' suffix) so a dotfile label like '.env' is never treated as
  a method; normalize the index/lookup key via make_id for parity with the alias
  path. Adds a negative test proving two same-named methods in one file are left
  unmerged (the len==1 ambiguity guard).
- #3714 (Erlang): the remote-call resolver reads module/name/arity off node
  metadata, which the incremental context builders stripped for non-Ruby langs,
  so foo:bar() silently failed to resolve on 'graphify update'. Forward the Erlang
  resolution metadata keys through the watch.py/cli.py allow-lists (same fix shape
  as the elixir _elixir_module marker).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-21 19:44:17 +01:00
shobhitagnihotri69 3097e9d2fa fix(build): deduplicate spec-conformant method nodes and aliases (#3705)
(cherry picked from commit fefdb5f074)
2026-09-21 19:19:56 +01:00
Abdullah 89c27c7b80 feat: add Erlang language extractor
(cherry picked from commit 3a92853329)
2026-09-21 19:19:26 +01:00
Abdullah 9f069eafea feat: add Solidity language extractor
(cherry picked from commit 41a1575e5e)
2026-09-21 19:13:40 +01:00
Abdullah d68d6012bd feat: add R language extractor
(cherry picked from commit 250395de31)
2026-09-21 19:10:13 +01:00
Abdullah ebe1f32c81 feat: add VB.NET language extractor
(cherry picked from commit 304c82fe10)
2026-09-21 19:06:50 +01:00
Abdullah ab568c8f42 feat: add COBOL language extractor
(cherry picked from commit 6573ea6306)
2026-09-21 18:04:14 +01:00
shobhitagnihotri69 5da2da3978 fix(build): preserve higher confidence on same-relation edge collision (#3703)
(cherry picked from commit 0b5d0e96c7)
2026-09-21 18:04:04 +01:00
safishamsiandClaude Opus 4.8 20a20d30d8 test(ts): de-flake the normalizer scaling test that reddened v8 CI
The #3359 scaling guard flaked on CI 3.13 (3.2x vs a 3.0x ceiling): at n=1000 the
measurement (~0.03s) is small enough that a GC pause landing in process_time
inflates the ratio. Not a regression — the normalizer path is unchanged; it was
green on 0.9.64 by luck. Harden it: disable GC around the measured section,
measure at 4k/8k where O(n) work dominates and linear converges to a clean ~2x,
and relax the ceiling to 3.5x (still separates linear from quadratic 4x).
Observed locally: 2.10x, stable across repeated runs on 3.10 and 3.13.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-20 18:53:35 +01:00
safishamsiandClaude Opus 4.8 7ca736cf94 release: 0.9.65 — Pillow CVE floor, Go/Swift/Java/Verilog extractor fixes, JS block scoping, fail-closed eviction deadlock fix, vis-network crash + tooltip encoding, repo-link/docs cleanup
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-20 18:46:53 +01:00
safishamsiandClaude Opus 4.8 86d8aadd3b fix(export): complete the vis-network crash fix and pin the tooltip XSS boundary (#3699, #3686 follow-ups)
#3699: the Fermat-spiral seed positions referenced `i` inside RAW_NODES.map(n => ...)
which has no index param, so the emitted JS threw 'ReferenceError: i is not defined'
and graph.html failed to render at every graph size. Bind the index: map((n, i) => ...).

#3686: the tooltip `title` sinks were correctly un-escaped (vis-network renders a
string title via Popup.setText -> innerText, verified in the pinned 9.1.6 bundle:
its only non-Element branch is innerText and it has zero innerHTML=<var> sinks).
Documented that invariant at the sink as the #1838 stored-XSS boundary.

Adds two guards to test_export.py: a vis-network version pin assertion (a bump must
force re-verifying the innerText tooltip path) and a spiral-seed indexed-map guard
(catches the free-`i` regression, which the substring-only export tests missed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-20 18:07:23 +01:00
Sanjaiyan Parthipan 124c263488 fix(export): prevent vis-network stack overflow crash on HTML render
Resolves the `BarnesHutSolver.js` maximum call stack size exceeded
error. By explicitly initializing node X/Y coordinates using a
sunflower spiral (Fermat's spiral) formula, nodes no longer spawn
stacked on top of each other. This prevents `avoidOverlap` physics
forces from dividing by zero and exploding into infinite values
on the very first frame.

(cherry picked from commit a20b3593bd)
2026-09-20 18:01:00 +01:00
himanshupatro-334 785ee5a426 Fix HTML entity encoding in graph tooltips
(cherry picked from commit 88025d0a93)
2026-09-20 18:01:00 +01:00
Abdullah 9a06e95408 docs: add GitHub issue and pull request templates
(cherry picked from commit 9ff3e92d10)
2026-09-20 18:00:48 +01:00
Abdullah aa5b334e69 Update link for graphify Enterprise
(cherry picked from commit ac219fa9e4)
2026-09-20 18:00:48 +01:00
viral-antuit 5f6b2a2e83 fix: security pillow updated to 12.3.0 for cve-2026-54058
(cherry picked from commit adaedf5c5e)
2026-09-20 18:00:48 +01:00
safishamsiandClaude Opus 4.8 2ff5db3c37 test(watch): drop two broken #3695 symlink tests that never trigger fail-closed (#3697 follow-up)
The two test_issue_3695_symlink_worker_* tests monkeypatch _reconcile_existing_graph
to inject a deleted_source_identities collision, then assert the 'fail-closed: kept'
message prints — but on v8 that setup never reaches the corpus-sweep excluded-alive
branch, so the message never fires and the tests fail regardless of the fix. The
production fix stays genuinely guarded by the honest tests (fail_closed_preserved /
full_rebuild_preserves_alive / reextracted / shrink_involving), verified to fail
without the watch.py change and pass with it, plus the real-OS-symlink
test_requires_symlinks_rebuild_symlink_worker.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-20 15:07:29 +01:00
himanshupatro-334 c99c3a67bb Strengthen fail-closed regression assertions
(cherry picked from commit e7c15f0512)
2026-09-20 13:59:37 +01:00
himanshupatro-334 87a82770eb Fix fail-closed AST ownership eviction
(cherry picked from commit ae5654a8c2)
2026-09-20 13:59:37 +01:00
ayushcodes10 873b5ebde8 Add regression tests for block scoped let/const shadowing
Covers the issue's three reported shapes (const inside an if block,
a for of binding referenced after the loop, and a closure that
outlives the loop), the control case that must not regress (a
reference still inside its own loop), var's continued function wide
reach in the same shapes, and a genuine reference elsewhere still
resolving. The C style for loop case asserts on source_location since
both calls read as identical source text and a plain edge presence
check cannot tell "only the outside call resolved" from "both wrongly
resolved."

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 9801c0eac1)
2026-09-20 13:59:26 +01:00
ayushcodes10 4a4fd974ce Scope JS let/const bindings to their own block, not the function
_js_local_bound_names collected let/const declarator targets, and a
for of/for in loop's own binding, into one function wide shadow set,
but both are block scoped in JS, unlike var, which is function scoped
through hoisting regardless of nesting depth. A reference to a
same named module callable made outside the block that actually binds
the name had its genuine indirect_call edge suppressed, whether the
binding sat inside an if, try, or bare brace block, came from a for
of/for in loop referenced after the loop ends, or was read from a
closure that outlives the loop.

The function wide set now only collects var, distinguished by
checking whether a declarator's parent is a variable_declaration
rather than a lexical_declaration, and a for in loop's own binding
only when it uses var. Every let/const and for/for of/for in binding
is instead folded into extra_locals for exactly its own block or loop
subtree, the same mechanism already used for catch bindings, so a
reference genuinely inside that block or loop still correctly shadows
while one outside it resolves. A C style for loop's own let/const
initializer gets the same treatment, since it is scoped to the whole
loop the same way a for of binding is.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 875c2a4761)
2026-09-20 13:59:26 +01:00
rajatnagda45 199d741f67 fix(verilog): link a module instantiation to the local definition, not a phantom
A module instantiation minted its target id with a bare, unscoped
_make_id(name), while a module definition uses _make_id(stem, name). The
two never matched, so instantiating a module defined in the same file:

    module counter(...); endmodule
    module top;
      counter u1(...);
    endmodule

split `counter` into a real definition node and a second, sourced phantom
that carried the `instantiates` edge. `top`'s dependency on the module you
actually defined was invisible, and because the phantom was sourced it also
baked this file's path into the id and blocked the corpus-level rewire that
would otherwise collapse it (the #1402 duplicate shape the other
extractors guard against).

Pre-scan module names so a same-file instantiation (Verilog allows
forward/any-order instantiation) resolves to the definition id. A module
defined in another file becomes a SOURCELESS stub instead, so the
corpus-level rewire collapses it onto the real definition rather than a
per-file duplicate — mirroring the Go extractor's ensure_named_node.

Adds regression coverage for both the local-definition link and the
cross-file sourceless stub.

(cherry picked from commit bca8bbac72)
2026-09-20 13:59:25 +01:00
rajatnagda45 c049ea0a69 fix(java): attach enum body members to the enum, not the file
A Java enum wraps its fields, constructors and methods in an
enum_body_declarations node, nested under enum_body after the constant
list. The generic walker recurses into a class body keeping the enclosing
type as the parent scope, but an unknown wrapper node resets that scope to
None (an unknown wrapper usually IS a scope boundary). That reset orphaned
every enum method, field and constructor onto the file:

    public enum Planet {
        EARTH(5.976e+24), MARS(6.421e+23);
        private final double mass;
        Planet(double mass) { this.mass = mass; }
        public double surfaceGravity() { return 6.673e-11 * mass; }
    }

Planet became a bare list of constants; surfaceGravity was emitted as a
file-level function and the constructor was dropped entirely.

enum_body_declarations is not a scope of its own - its members belong to
the enum - so recurse through it transparently, preserving the enum as the
parent scope (mirrors the companion_object and ERROR handling already in
the walker). Constructors and methods now hang off the enum via method
edges and their bodies are walked as call-graph scopes.

Adds regression coverage: members attach to the enum and don't leak onto
the file, an inter-method call is captured, and the constant case_of edges
are untouched.

(cherry picked from commit 820018ee3c)
2026-09-20 13:59:25 +01:00
rajatnagda45 fc8e9e167f fix(swift): extract method requirements declared in a protocol body
tree-sitter-swift gives a protocol's body-less method requirement its own
node type, protocol_function_declaration, instead of reusing the
function_declaration used inside a class or struct. The Swift config's
function_types only listed function_declaration, so a protocol like

    protocol Drawable {
        func draw()
        func area() -> Double
    }

became an empty node - the method contract every conformer must implement
never entered the graph.

Add protocol_function_declaration to function_types and
function_boundary_types. Requirements now surface as .method() nodes hung
off the protocol, their signature type references (return/param types) are
captured, and they stay distinct from a conformer's implementation of the
same name. Stored property requirements are left alone, matching how
stored properties on a class are already handled.

Adds regression coverage for all three.

(cherry picked from commit 4300054291)
2026-09-20 13:59:25 +01:00
rajatnagda45 a9450a537e fix(go): extract method requirements declared in an interface body
The interface_type branch only handled interface embedding and generic
type-set constraints, so the method requirements that make up an
interface's contract were dropped. An interface such as

    type Shape interface {
        Area() float64
        Perimeter() (float64, error)
    }

became an empty node - Area and Perimeter never entered the graph, and
nothing could resolve against the interface's method set.

Walk the method_elem children too, mirroring the receiver-method path:
each requirement becomes a .Method() node hung off the interface via a
method edge. Embedding (type_elem) keeps emitting embeds/references, so
the two never blur.

Adds regression coverage: requirements surface as method nodes, an
embedded interface stays a heritage edge, and an interface method and a
concrete struct method of the same name remain distinct nodes.

(cherry picked from commit 739940a42b)
2026-09-20 13:59:25 +01:00
Abdullah d3d2538731 docs: align repository links and translated README logos
(cherry picked from commit 3acbedb69a)
2026-09-20 13:59:25 +01:00
safishamsiandClaude Opus 4.8 b9cd957072 release: 0.9.64 — terraform block attributes (with secret redaction), JS in PHP script blocks, rust generic-impl self calls, kotlin/C++ cross-file member calls, npm subpath imports, stale-analysis reconstruct, markdown-family reconcile, external-vs-dangling diagnostics
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-18 22:16:16 +01:00
safishamsiandClaude Opus 4.8 650f47f526 fix(terraform): redact secret-named attribute values before they hit the graph (#3644 follow-up)
#3644 persists HCL block attributes into node metadata, which is serialized to
graph.json verbatim and surfaced to the model over MCP (query/get_node) with no
sanitize_metadata pass. A hardcoded credential in a .tf file (password,
db_password, aws_secret_access_key, client_secret, a connection string, ...)
would leak. Redact the VALUE of any attribute whose key names a secret while
keeping the key visible, so instance_type/ami queries still work and a user can
still see THAT a secret is set. Recurses into map values so a nested secret in a
tags/connection map is redacted too.

Also notes Terraform block attributes in the _AST_CACHE_SCHEMA 4 comment (they
are newly-cached facts covered by the same bump #3653 introduced).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-18 15:21:04 +01:00
himanshupatro-334 1e09e8bc82 Preserve Terraform attributes during extraction
(cherry picked from commit 6ec5de733c)
2026-09-18 15:17:06 +01:00
oleksii-tumanov 3e87d865d0 fix: resolve generic Rust self calls
(cherry picked from commit d9f00b0f55)
2026-09-18 15:16:09 +01:00
ayushcodes10 f97cf99b87 Add a regression test for the PHP JS id collision edge drop
Covers a same name PHP/JS function pair in one file: exactly one
surviving node, the JS call to the colliding name absent as a calls
edge entirely rather than misattached, and the unrelated JS symbol's
own contains edge from the shared file node still present.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit f59ce06c8c)
2026-09-18 15:15:58 +01:00
ayushcodes10 96e653cc7c Drop edges of a JS node dropped for colliding with a PHP node
A reviewer on this PR pointed out that when a JS symbol's id collides
with an existing PHP node (same name, one file, resolved in favor of
the PHP node), the merge still appended every JS edge unconditionally.
An edge meant for the discarded JS symbol silently attached to the
unrelated PHP node sharing its id instead of vanishing with it. The
file node's own always on collision (both passes deliberately reuse
its id) is excluded from this so an unrelated JS symbol's own edges
sourced from the file node are unaffected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit c96169b320)
2026-09-18 15:15:58 +01:00
ayushcodes10 cc80351872 Add regression tests for the PHP inline script extraction
Covers the issue's exact reproduction (two functions plus the call
edge between them), that line numbers survive the masking pass, that
a script tag with only a src attribute contributes nothing without
crashing, and that a plain PHP file with no script tag is unaffected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 2d408de529)
2026-09-18 15:15:58 +01:00
ayushcodes10 01ae1edc03 Index JavaScript in inline script blocks of a PHP file
The PHP tree sitter grammar treats a span that is not PHP, such as an
inline script block, as opaque markup, so any JavaScript declared
there was entirely absent from the graph: functions, calls, and
everything else in that region.

extract_php now runs a second pass after the PHP extraction. Every
part of the source that is not a script body is blanked to spaces,
preserving newlines so line numbers stay accurate, and the masked
source is parsed with the JS grammar the same way the Vue extractor
already masks everything outside its own script block. The two node
sets are merged onto the one file node, so a symbol declared in the
script block looks like any other symbol in the file. A script tag
with only a src attribute and no body masks to an empty region and
contributes nothing, and a file with no script tag at all skips the
second pass entirely.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 2114766c91)
2026-09-18 15:15:57 +01:00
oleksii-tumanov bdb605fd8a fix: preserve Markdown links on parse failure
(cherry picked from commit 3a9cd7b8dd)
2026-09-18 15:15:57 +01:00
oleksii-tumanov e96235cb1f fix: reconcile Markdown link suffixes
(cherry picked from commit 4da224338c)
2026-09-18 15:15:57 +01:00
safishamsiandClaude Opus 4.8 41c0407504 docs(diagnostics): note ref_ external refs and external=True stubs are distinct (#3590 follow-up)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-17 11:10:31 +01:00
safishamsiandClaude Opus 4.8 4e811363a6 test(kotlin): cover companion members + incremental persistence (#1698 follow-up)
#3598 resolves Kotlin object/class-qualified member calls across files. Adds
two regression tests the PR omitted:

- a `companion object` member call (`Service.create()`), pinning the #2565
  enclosing-class attribution the resolver relies on;
- an incremental-rebuild test routed through the real watch._rebuild_code, so
  it actually exercises the context builder's allow-list carrying _callable_class
  + method edges (a hand-fed resolution_context_nodes list would bypass exactly
  the path that silently regressed in sibling PRs).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-17 11:09:52 +01:00
ayushcodes10 4afdfcbaaa Add regression tests for the cross file Kotlin object member call fix
Covers three cases: the new cross file resolution (Config.load() called
from another file resolves to object Config), a same file control to
prove the existing in file resolution is unaffected, and an ambiguous
receiver defined in two packages that must yield no edge under the
exactly one candidate guard.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit f22f17b575)
2026-09-17 11:05:12 +01:00
ayushcodes10 095530a335 Add and register the Kotlin object member call resolver
Fixes issue 1698.

Mirrors _resolve_kotlin_qualified_calls just above it and the same
type_by_name plus methods_by_type shape _resolve_swift_member_calls
uses for its own type qualified case: index every Kotlin sourced
class or object by its bare name, resolve the receiver against that
index, then look up the callee among that type's methods. Both steps
bail on anything but exactly one candidate, the same god node guard
every cross file resolver in this module already uses.

Verified end to end: the issue's own cross file repro now produces an
EXTRACTED calls edge, the same file control case is unaffected, and
two objects sharing the same name in different packages correctly
produce zero edges instead of an ambiguous guess.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit a6c89df809)
2026-09-17 11:05:12 +01:00
ayushcodes10 492ea4fda8 Thread the object receiver into raw_calls for Kotlin
Still toward issue 1698. Still no observable behavior change on its
own: nothing reads the new kotlin_object_receiver field yet, so
existing edges are unaffected. The resolver that consumes it lands
in the next commit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit aed98d6395)
2026-09-17 11:03:41 +01:00
ayushcodes10 2595d62859 Capture the receiver for a two segment Kotlin navigation call
Still toward issue 1698, still no behavior change: the variable is
computed but nothing reads it yet.

A capitalized two segment receiver (MessageHelper in
MessageHelper.isRoomClosed()) names an object singleton or a class or
companion member, statically unambiguous in source. Captured
separately from member_receiver so the existing in file bare name
lookup and its capitalized receiver deferral guard are untouched;
threading this into raw_calls for a dedicated cross file resolver
lands next.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 7728d99295)
2026-09-17 11:03:41 +01:00
ayushcodes10 3507b4a774 Add a variable for the Kotlin object member call receiver
Toward issue 1698: a call like MessageHelper.isRoomClosed() has
exactly two navigation segments, so the existing fully qualified
prefix capture (which only fires at three or more segments) never
sees it, and the code deliberately never stamps member_receiver for
this shape either, since that would defer the in file bare name
lookup that already resolves the same file case correctly.

This adds the new variable with no behavior change yet; capturing
into it and threading it through to raw_calls lands in the next
commits.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 91550dd055)
2026-09-17 11:03:41 +01:00
ayushcodes10 ffa0f529e9 Add a regression test for the god node guard on the fallback
Two different classes that both fail header parsing and happen to
share a class name and a method name must not let a call resolve to
either one.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 9e26952d8b)
2026-09-17 11:03:41 +01:00
ayushcodes10 d77141ec85 Add a regression test for the qualified only fallback
The issue's own repro, an Unreal style UCLASS whose method
declaration never survives header parsing, must still get a calls
edge from a site that invokes it through the qualified name.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 3d4dec6b9a)
2026-09-17 11:03:41 +01:00
ayushcodes10 64fa746b43 Wire the second chance lookup into the scoped call branch
Only the Foo colon colon bar branch tags a fallback label, since it
is the only one with a class name in source to build one from. The
lookup only runs when the primary method index lookup already came
back empty, and only accepts an exactly one candidate match, the
same guard every other resolver in this module already applies.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit b5e066c7d4)
2026-09-17 11:03:41 +01:00
ayushcodes10 835abadf7a Index qualified labeled C++ nodes for a second chance call lookup
Prep for resolving a scoped call whose callee exists only as a
qualified labeled fallback node: builds a label to node id index
for every node whose label looks like a qualified method
(Class colon colon method with parens), restricted to nodes with a
real source file. Nothing reads it yet, so no behavior change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 1c1f1336e3)
2026-09-17 11:03:41 +01:00
ayushcodes10 1ca2e4b1f3 Recompute god node data directly on the stale sidecar path
god_nodes ranks purely by graph degree, independent of the community
partition, so clearing it to an empty list on the stale path and
relying on the wiki subcommand's own recompute-if-empty fallback
further down worked today only because wiki happens to be the only
current reader of this value. Recompute it directly here instead, so
a future reader that does not carry the same fallback cannot silently
lose real data.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit b071d6e788)
2026-09-17 11:01:38 +01:00
ayushcodes10 9d747f4da5 Compare partition structure, not just the node id set, for staleness
The node id set comparison missed a whole class of staleness: a merge,
a split, or a single node moving from one community to another can
leave the overall node set exactly unchanged while still describing a
different clustering, so a stale sidecar that happened to still cover
the same nodes kept winning. Compare each side's set of community
blocks instead, which catches a partition change even when the flat
node set stays identical, while still ignoring a pure id renumbering
of the same partition per the existing #1667 guard.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 30a5955931)
2026-09-17 11:01:38 +01:00
ayushcodes10 11d91c8e17 Add negative control test for a sidecar that still matches
Guards against a false positive: an up to date sidecar (the normal
case immediately after extract or the clustering command) must not
trip the new staleness warning or take the reconstruction path.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 21342bda37)
2026-09-17 11:01:38 +01:00
ayushcodes10 bafe75b86b Add regression test for stale sidecar cohesion recomputation
Confirms the wiki export path specifically, since it is the one that
prints cohesion into article metadata: a stale, impossibly large
cohesion value in the sidecar must not survive into the export once
staleness is detected, proving score_all actually ran on the fresh
reconstruction rather than the fossil value merely being ignored by
coincidence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 12c50b975a)
2026-09-17 11:01:38 +01:00
ayushcodes10 18cae252cb Add regression test for the stale sidecar html export path
Corrupts the analysis sidecar community node id set (the exact
staleness signature the issue describes) and confirms export html
still succeeds, still renders graph.html, and prints the new warning
instead of silently exporting against the fossil.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 4518bae439)
2026-09-17 11:01:38 +01:00
ayushcodes10 06ff9d07dc Prefer the fresh reconstruction when the sidecar is stale
Fixes issue 2386.

The existing fallback only reconstructed communities from graph.json
when the sidecar was missing entirely; a sidecar that exists but was
written by an earlier clustering pass looked identical from the
outside and kept winning, since update and watch never regenerate
.graphify_analysis.json.

This compares the node id set each side covers, cheap and already in
memory, rather than the community ids themselves, since those can
renumber run to run even for the same partition. A mismatch means the
sidecar is stale: prefer the fresh reconstruction, recompute cohesion
with score_all so wiki articles and the HTML export do not swap one
silent degradation for a smaller one, reset gods_data so the existing
self heal at the wiki export site recomputes it, and print a warning
naming the exact command that refreshes the sidecar, since the whole
point of this issue is that nothing currently signals the divergence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit d4eb7af599)
2026-09-17 11:01:38 +01:00
ayushcodes10 a5ab2001a8 Compute the graph.json community reconstruction unconditionally
Toward issue 2386: this hoists the reconstruction from graph.json's
per node community attribute out of the "sidecar is missing" branch
so it runs every time, with no behavior change yet since it is still
only used when the sidecar produced nothing. The next commit compares
it against the sidecar to also catch a sidecar that exists but is
stale.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 0932abc4e0)
2026-09-17 11:01:38 +01:00
ayushcodes10 23d8a8798d Add an end to end regression test for the reporter's exact repro
A file that only imports a package subpath must resolve just like one
that imports the bare package, using the exact package.json plus two
file shape from the issue, instead of coming out fully disconnected
from the framework it depends on.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 5fb7fc34c1)
2026-09-17 11:01:38 +01:00
ayushcodes10 7aebd99372 Add a unit test for scoped package subpath resolution
A scoped package subpath lands on the scope plus package only, never
on a different package that happens to share the same scope.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 02183335e3)
2026-09-17 11:01:38 +01:00
ayushcodes10 3e9d22faf5 Add a unit test for plain package subpath resolution
A plain package subpath now lands on the same resolver target as its
bare import.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit b703d3126e)
2026-09-17 11:01:38 +01:00
ayushcodes10 7d2344f846 Namespace an external import on its package root, not the specifier
An unresolved bare specifier fell through to a ref namespaced id built
from the whole raw string, so a package subpath import like
next/image minted a different id than a bare import of next, even
though both refer to the same package. package.json's own dependency
node for that package is keyed off the bare name alone, so a subpath
import could never land on it and produced no edge at all while the
bare import of the same package resolved fine.

The fallback now strips the specifier down to its package root first:
the first segment for an ordinary package, the first two for a scoped
one, matching how the dependency node itself is keyed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit be0eb7f2a5)
2026-09-17 11:01:38 +01:00
Dev Chiniwala 6e761f205a fix(diagnostics): separate external reference edges
(cherry picked from commit ba49e71a98)
2026-09-17 11:01:37 +01:00
safishamsiandClaude Opus 4.8 26b02b5e34 docs: update README header logo to the Graphify card
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-16 20:41:38 +01:00
safishamsiandClaude Opus 4.8 eaaec1abd9 release: 0.9.63 — elixir cross-file alias/import resolution, rust self.method() across files, ruby inherited member calls, external import stub nodes (no more dangling graph.json endpoints), markdown mention edges survive rebuilds
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-16 16:51:37 +01:00
safishamsiandClaude Opus 4.8 778c04726d fix(build): mint typed external stubs for undeclared import endpoints (#2873)
graph.json shipped imports/imports_from/re_exports edges whose target was an
external module (stdlib, a third-party dep) with no entry in nodes[]. Every
loader (networkx node_link_graph) materialises such an endpoint as an
attribute-less phantom, so declared node-count != loaded node-count, and
merge-graphs fragmented the same module into one node per repo.

- build_from_json now mints a typed external stub node (type=external,
  external=True) for an import-family edge whose target is otherwise undeclared,
  instead of dropping the edge. Non-import relations are unchanged, so a
  sourceless external call target stays suppressed (#3156, no phantom god-node).
- The --no-cluster / incremental update path writes the raw merged extraction
  rather than a builder graph, so it applies the same stubbing via the shared
  mint_external_stubs_in_data helper. Idempotent; grows the node set so the
  #479 shrink guard is unaffected.
- prefix_graph_for_global leaves external stubs unprefixed (no repo:: tag), so
  the same stdlib/dependency module unifies into one global node across a
  cross-repo merge instead of fragmenting per repo.

Adds regression tests for build-level stubbing, serialized-graph consistency,
the #3156 non-import drop, idempotency, cross-repo unification, and an
end-to-end `update --no-cluster` integrity check through the real rebuild.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-16 16:20:01 +01:00
safishamsiandClaude Opus 4.8 e3535e942a fix(elixir): guard nested-module capture and same-file contains clobber (#3603 follow-up)
#3603 resolves cross-file alias/import/require/use targets onto the real
defmodule node. Two guards ported from the competing #3566 so the resolver
does not over-reach:

- Only top-level modules are indexed as resolution targets. extract_elixir
  marks them with _elixir_module; a nested defmodule (labeled with its bare
  inner name) is left unmarked so an unrelated `use <Name>` from another file
  cannot latch onto it. The marker rides through incremental rebuilds via the
  resolution-context allow-list in watch.py and cli.py, so the fix does not
  decay on the `graphify update` / watch path.
- A same-file alias is left unresolved: the import edge's source is the file
  node, which already `contains` that module, so retargeting would duplicate
  the pair as a weaker `imports` and clobber `contains` in the non-multi graph.

Adds regression tests for both guards plus an incremental-rebuild test that
routes through the real watch._rebuild_code builder (the path #3566's own
test bypassed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-16 15:37:30 +01:00
Ryan Peterson b117a6e420 fix(watch): keep code-span mention edges through a rebuild over an existing graph
_reconcile_markdown_links treats every AST-tier references edge owned by a re-parsed
Markdown file as an authored [link](file) and prunes any pair it did not author. A code-span
mention is also a references edge owned by its document, so a plain `graphify update` over
an existing graph, with or without changes, dropped every mention edge; only a build from
scratch kept them.

A mention targets a code symbol, never a file representative, so the reconcile now leaves
those edges to the AST ownership rule: re-extracting the document regenerates them and
re-extracting the code side keeps or drops them with the target node.

(cherry picked from commit 73cf2ae56c)
2026-09-16 14:50:54 +01:00
Ryan Peterson 8cfebfdfd2 fix(markdown): honour dotted qualifiers and explicit relative cites in mention resolution
Three findings from the automated review of #3562, all reproduced:

A dotted span with a non-code extension (README.md, pyproject.toml) was classified as a
symbol because only CODE_EXTENSIONS was checked, and every dotted form was reduced to its
last segment, so time.sleep matched a repo's own sleep(). The dotted form now keeps its
whole chain, the file early-exit also checks DOC_EXTENSIONS, and a bare-name match must
carry every qualifier as an owner label or a segment or stem of its source path.

_match_cited_file used lstrip("./"), which strips characters, so a .github/... cite could
never match by suffix. The leading ./ and ../ segments are now stripped as segments, and
the suffix form also matches a root-level file.

An explicit ./ or ../ cite that escaped the corpus fell through to the suffix rule and
could land on an unrelated copy of the file. It now resolves relative to the document
only.

(cherry picked from commit 3f84e7f3e2)
2026-09-16 14:50:54 +01:00
ayushcodes10 7dbc668933 Add a regression test for a genuinely external module reference
A module with no matching definition anywhere in the corpus, stdlib
or a hex dependency, must stay an external reference rather than
getting fabricated.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit da5e23a921)
2026-09-16 14:47:21 +01:00
ayushcodes10 50a65891f4 Add a regression test for the god node guard on a duplicate name
Two different files each declaring a module with the same bare name
must leave the reference exactly as extracted rather than guessing
which one the caller meant.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 690d387626)
2026-09-16 14:47:21 +01:00
ayushcodes10 9a5b2dd7f9 Add a same file negative control test
A module importing something declared in the same file already
resolved before this fix, since both ids share the same stem, and
must keep working exactly as before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 8320da005a)
2026-09-16 14:47:21 +01:00
ayushcodes10 7406aae5e6 Add a regression test for the issue's own repro
A module aliased from a different file now resolves to that module's
real, non dangling node.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 53877c6874)
2026-09-16 14:47:21 +01:00
ayushcodes10 4696a55df1 Add and register the Elixir import target resolver
Fixes issue 2556.

extract_elixir mints a module's own node id with the defining file's
stem but an alias/import/require/use target with just the bare
module name, so the two only ever match when a module refers to
itself. Every reference to a module declared in a different file was
silently dropped as dangling at build time, thirteen percent of
extracted edges on the real project measured in the issue.

Matches a target against the id of a module across the whole corpus,
which needs no heuristics since both sides already run through the
same id builder. Zero or two or more matches leave the edge exactly
as extracted rather than guessing, the same god node guard every
other cross file resolver in this module already applies; the issue's
own testing found id suffix matching produced wrong resolutions on a
real corpus, which is why this matches the full id, not a fragment
of it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 909310cfe7)
2026-09-16 14:47:05 +01:00
ayushcodes10 8c7b6675e8 Refuse to pool methods across two unrelated same named types
Pooling methods across every node sharing a type's bare label is
what makes a split impl block work, but it is only safe when every
one of those nodes really is an impl block for the SAME type. Two
unrelated structs that happen to share a bare name, each with its
own different methods, could still link a caller to a method that
only exists on the wrong one, most concretely when one type
overrides a trait default the other relies on and so never gets an
explicit method node for it.

A struct, enum, or trait declaration gets a contains edge from its
file; an impl block never does. So the type name itself is now
treated as ambiguous, and pooling skipped entirely, whenever two or
more nodes sharing the bare label are real declarations rather than
impl blocks. A single declaration with any number of impl blocks
spread across files, the shape this pass exists for, is unaffected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 141662b0eb)
2026-09-16 14:43:12 +01:00
ayushcodes10 58c497d2da Keep every method a duplicate index key maps to, not just the last one
A plain dict assignment silently overwrote an earlier target whenever
two method nodes shared both a source impl node and a stripped
label, which would have kept whichever one was seen last instead of
surfacing the case as the ambiguity it is. The index now keeps a set
per key and folds every match into the candidate set before the
exactly one candidate check runs, so a genuine duplicate still bails
instead of guessing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 2cbbf1a670)
2026-09-16 14:43:12 +01:00
ayushcodes10 4f13b17aa2 Scope the self call dedup check to existing calls edges only
The check against a pair already having an edge matched on ANY
relation, so a caller that already had, say, a references edge to
the exact same target (from also naming the type elsewhere) silently
suppressed a real call to it. The two relations are not mutually
exclusive and an existing non calls edge says nothing about whether
a call was resolved. Scoped the check to calls edges only, matching
an existing precedent elsewhere in this module for the identical
class of mistake.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 94735ce241)
2026-09-16 14:43:12 +01:00
ayushcodes10 5483e5222c Add regression tests for the god node guard on self calls
Two different structs sharing a bare type name with a colliding
method name must yield no edge rather than a guess, and a self call
to a method that genuinely does not exist anywhere in the corpus
must not fabricate a target.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit afeeefa109)
2026-09-16 14:43:12 +01:00
ayushcodes10 d77dcb9a67 Add regression tests for the split impl block self call fix
Covers the issue's own shape (impl Foo split across two files, a
self call in one block reaching a method defined in the other) and a
same file negative control proving the pre existing bare name
resolution is unaffected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 2d161af639)
2026-09-16 14:43:12 +01:00
ayushcodes10 0a92b56bd1 Add and register the Rust self member call resolver
Fixes issue 2234.

Pools methods by the bare type name across every node that carries
it, rather than requiring the name to resolve to exactly one node
like the Kotlin and Swift equivalents: Rust routinely splits an impl
block for one type across as many files as it likes, and rust.py
mints a separate graph node per file and type name pair rather than
merging them, so requiring a single node would refuse the exact
split impl block shape this issue is about. A call resolves only
when exactly one method across the whole pool matches the callee
name, so two impl blocks defining the same method name still bail,
a real ambiguity rather than a false one.

Verified end to end: a self call in one file now reaches a method
defined in a different impl block of the same type in another file,
the same file control case is unaffected, an ambiguous type name
shared by two unrelated structs with a colliding method name yields
no edge, and a call to a genuinely undefined method yields no edge.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 7a5ab00ff5)
2026-09-16 14:43:11 +01:00
ayushcodes10 55d84bbc3c Tag a self dot method call with its receiver's syntactic type
Detect when a member call's receiver is literally self (a distinct
tree sitter node type, not an identifier) and, when the enclosing
impl block's bare type name is known, carry it on the raw_call as
rust_self_type. Nothing consumes this yet, so the extracted edges
are unchanged; it is the signal the next commit's resolver needs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit 200081cf9b)
2026-09-16 14:43:11 +01:00
ayushcodes10 53e89d6cf7 Thread the enclosing impl block's bare type name through function bodies
Prep for resolving a self dot method call across files: extract_rust
already tracks which impl block a function body belongs to via
parent_impl_nid, but not the block's own bare type name, which is
what self is typed as syntactically inside that block. No behavior
change yet, this just carries the name down to where a call
expression is walked.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
(cherry picked from commit a49fd9139a)
2026-09-16 14:43:11 +01:00
oleksii-tumanov c5f57d3d61 fix: resolve inherited Ruby member calls
(cherry picked from commit 8f576afacc)
2026-09-16 14:43:05 +01:00
safishamsiandClaude Opus 4.8 c7ec108208 release: 0.9.62 — terraform local modules, Ruby inherited implicit-self calls, markdown code-span references, unicode ids, self-loop cohesion, atomic watch writes, semantic-cache basename recovery, destructured export nodes, thin file-only communities, GRAPHIFY_OUT hook gates
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-15 18:57:53 +01:00
oleksii-tumanov eee5b02b7d fix: preserve Ruby constant lookup boundaries
(cherry picked from commit bd1a2d2651)
2026-09-15 18:03:49 +01:00
oleksii-tumanov 7e857e020b fix: guard Ruby namespace rebinding
(cherry picked from commit 1a7262e2a8)
2026-09-15 18:03:49 +01:00
oleksii-tumanov 436a735f7f fix: guard Ruby constant rebindings
(cherry picked from commit 5f28f2bb3e)
2026-09-15 18:03:49 +01:00
oleksii-tumanov ff75ca1029 fix: reject ambiguous Ruby constant mutations
(cherry picked from commit 891ebfae53)
2026-09-15 18:03:49 +01:00
oleksii-tumanov dd0b95d18a fix: harden Ruby inherited lookup proof
(cherry picked from commit 43f56f8633)
2026-09-15 18:03:12 +01:00
oleksii-tumanov bf28196db9 fix: promote inherited Ruby call confidence
(cherry picked from commit aec5c32000)
2026-09-15 18:03:12 +01:00
vstepko 161e5f2ef5 feat(terraform): resolve local module sources and directory topology
(cherry picked from commit e00593d10e)
2026-09-15 18:01:35 +01:00
Ryan Peterson c805c6fb9d feat(markdown): resolve code-span mentions into references edges
The markdown extractor's docstring promised a heading --references--> node edge
when a backtick Name matches a known pattern, but nothing implemented it, so an
AST build produced no document-to-code edge at all.

extract_markdown now collects inline code spans outside fences and frontmatter as
raw_calls tagged language "markdown", owned by the heading they sit under (the
page before the first heading). A new markdown_mentions language resolver runs
after the id-remap passes and turns them into references edges: the explicit
path::Symbol[::member] form resolves through the cited file's symbols and is
EXTRACTED 1.0; a bare or dotted name resolves only when exactly one callable code
node carries that label and is INFERRED 0.95. Ambiguous names, builtins, missing
files and non-callable matches emit nothing. The shared cross-file call pass
skips markdown raw_calls so prose never emits calls edges.

Tests cover span classification, raw_call ownership, end-to-end resolution,
ambiguity, and cache round-tripping.

(cherry picked from commit 2d833a0a3c)
2026-09-15 18:01:28 +01:00
safishamsi d4b704fa05 test(cluster): add the self-loop cohesion_score regressions #3558 described
#3558's fix landed but its diff omitted the 3 tests its description claimed;
add them (self-loop ignored, self-loops-only is 0, 0..1 bound holds). Also drop
a changelog line the #3559 cherry-pick injected into the released 0.9.61 section.
2026-09-14 18:55:31 +01:00
ayushcodes10 9b1db672fb Add regression test for dangling edge pruning consistency
group_skipped feeds the dangling reference pruning pass and the write
loop must agree with it on whether a recovered group is written or
skipped. This proves an edge between two nodes inside the same
recovered group survives instead of being pruned as referencing a
supposedly skipped id.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 8a23b305fe)
2026-09-14 18:52:06 +01:00
ayushcodes10 6694f65465 Add regression test for unscoped callers with no allowlist
Confirms recovery never runs when allowed_source_files is omitted: a
genuinely bogus path is skipped exactly as before this fix, and a
normal well formed path in the same batch still saves and loads back.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 12999a80f6)
2026-09-14 18:52:06 +01:00
ayushcodes10 cf8ac5d035 Add regression test for an ambiguous basename staying skipped
Two allowed files sharing a basename must not let recovery guess
between them: an unresolvable source_file with an ambiguous basename
still falls through to the previous skip behavior unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit f59acf7c36)
2026-09-14 18:52:06 +01:00
ayushcodes10 a442031291 Correct recovered groups own source_file before writing them
A recovered group's write KEY pointed at the right file, but every
node, edge, and hyperedge inside it still carried the original
unresolvable source_file string. load_cached rejects an entry on read
if any item's source_file does not match the path it was loaded
under, so the previous commit alone wrote a group that reported as
saved but could never actually be read back, silently reproducing the
exact loss this fix exists for.

This corrects every item's source_file to the recovered path's
portable form before the group is written, only when recovery
actually redirected the key, so an unrecovered group stays byte
identical to before.

Includes the regression test proving the full round trip: a group
recovered by basename now survives a subsequent load_cached call.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 4b91dcd462)
2026-09-14 18:52:06 +01:00
ayushcodes10 796a3595a4 Recover malformed semantic cache paths by basename
Fixes issue #2973.

group_skipped and the save_semantic_cache write loop now call
_recover_group_path instead of resolving fpath directly, so a group
whose reported source_file never resolves to a real file gets one more
chance: an unambiguous basename match against the already dispatched
allowlist. An ambiguous or genuinely bogus basename still falls
through to the previous skip behavior unchanged, and unscoped callers
(no allowed_source_files) are byte identical to before since recovery
only runs when an allowlist is available.

This stops an incremental run from silently redoing already processed
chunks every time the adaptive retry split path reports a source_file
that a weak or local backend lost track of.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 73f5a66370)
2026-09-14 18:52:06 +01:00
ayushcodes10 6cf7b98d64 Add basename recovery helper for semantic cache groups
save_semantic_cache groups nodes and edges by source_file, then skips
any group whose path does not resolve to a real file. A weak or local
backend's adaptive retry split path sometimes reports a source_file
for a group that never resolves at all, silently dropping that
group's nodes and edges from the cache on every incremental run.

This adds a helper that recovers such a group by an unambiguous
basename match against the known good, already dispatched allowlist,
with no behavior change yet since nothing calls it. The write loop is
switched over in the next commit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 4528666ba6)
2026-09-14 18:52:06 +01:00
ayushcodes10 5d858ad37a Add regression test for the clustered path replace fallback
Same #2689 fallback requirement as the no_cluster test, exercised
against the default clustered rebuild path, the second of the two
watch.py call sites the issue reports.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 366ec5ef1f)
2026-09-14 18:52:05 +01:00
ayushcodes10 0da4fe68db Add regression test for the no_cluster path replace fallback
Simulates the VMware HGFS PermissionError this issue reports by
monkeypatching os.replace to always raise it, then confirms an
incremental no_cluster rebuild still succeeds and lands the new
content instead of aborting the whole run.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 9e75593b02)
2026-09-14 18:52:05 +01:00
ayushcodes10 dd5141df2b Route the rebuild path graph.json replace through the fallback
Fixes issue 2689 for the main rebuild write site, the second of the
two watch.py call sites reported.

Same reasoning as the reconcile path: existing_graph was read a few
lines earlier in this same process for the same_graph comparison, so
a plain Path.replace can hit the VMware HGFS PermissionError this
issue reports. Both call sites in watch.py now route through the
shared os_replace_with_fallback helper that export.py, cache.py, and
install.py already use.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit b01622eb9f)
2026-09-14 18:52:05 +01:00
ayushcodes10 c9d8123b9d Route the reconcile path graph.json replace through the fallback
Fixes issue 2689 for the reconcile existing graph write site.

This site reads existing_graph a few lines earlier in the same
process, then replaced graph_tmp onto it with a plain Path.replace.
On a VMware HGFS shared folder, os.replace over a destination that
was read earlier in the same process raises PermissionError even
though src and dst are on the same drive; deleting then renaming
succeeds in that exact situation. os_replace_with_fallback already
implements that fallback for PermissionError generally, so this
switches the call over to it instead of duplicating the recovery here.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 3214e8ee03)
2026-09-14 18:52:05 +01:00
ayushcodes10 a15e7bb4e2 Import the shared atomic replace fallback into watch.py
watch.py writes graph.json via a plain Path.replace() at two call
sites instead of the shared os_replace_with_fallback helper that
export.py, cache.py, and install.py already route through. This adds
the import with no behavior change yet; both call sites are switched
over in the next two commits.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit f3694aea49)
2026-09-14 18:52:05 +01:00
breken df9f37612f fix(hooks): resolve the output dir from GRAPHIFY_OUT in the sh gates, not a literal graphify-out/
#1423 moved the Python rebuild bodies onto GRAPHIFY_OUT, but the shell that
runs BEFORE them still hardcoded graphify-out/. With the documented override
(#686, e.g. GRAPHIFY_OUT=custom-out for worktree/shared-output setups):

- post-checkout exited at `[ ! -d "graphify-out" ]`, so a branch switch never
  launched the rebuild - a silent no-op with nothing in the log.
- post-commit's "only graph artifacts changed" filter only recognised
  graphify-out/ paths, so a commit touching only custom-out/graph.json
  launched a full rebuild - the loop the filter exists to prevent.

Both gates now read ${GRAPHIFY_OUT:-graphify-out}, the same source the rebuild
body reads. The commit filter is a POSIX case loop instead of grep so the dir
name is matched literally (no regex metacharacters); the leading ( on each
pattern keeps bash 3.2 (macOS /bin/sh) from mis-parsing the pattern's ) inside
the $(...) substitution.

Regression: tests/test_hooks.py runs the emitted scripts under sh with the
launcher stubbed and asserts whether the hook reaches the launch line.

Claude-Session: https://claude.ai/code/session_0134ujLF81GyXsCByibLcYsz
(cherry picked from commit 9efd052de4)
2026-09-14 18:49:21 +01:00
jordanalexanderp18-rgb 97d523a681 fix(cluster): exclude self-loops from cohesion_score so the ratio stays in 0..1
cohesion_score() counts self-loops in the numerator (number_of_edges) but
not in the denominator (n * (n - 1) / 2, distinct node pairs), so the ratio
its docstring defines over 0..1 can exceed 1.0. Recursive `calls` self-edges
are deliberately preserved by build_from_json, so they reach this code in
ordinary graphs: a two-node community holding one recursive function scored
2.0, and report.py prints the value unclamped.

(cherry picked from commit 5d66b992ac)
2026-09-14 18:49:21 +01:00
ayushcodes10 bf5769585a Update thin community tests for the corrected count
Three existing tests pinned the old, undercounting behavior directly,
including one whose own docstring asserted the exact shape this fix
corrects. Updates all three to the now correct figures and adds a
dedicated test asserting the two invariants the issue itself
suggested, shown equals what actually renders and shown plus thin
equals the total, at both thresholds already exercised in this file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit dd056ab9a8)
2026-09-14 18:49:20 +01:00
ayushcodes10 3d8d4e08ee Count an all file node community as thin, not invisible
Number 3148 fixed shown to be computed directly instead of total
minus thin, since the old formula counted a community with zero real
nodes as shown even though the render loop skips it. That fix left
thin itself under a zero real guard from before it, so a zero real
community was excluded from both figures at once and went uncounted
anywhere the report prints about itself, and shown plus thin no
longer summed to the total community count. Both counting sites drop
that guard so a community the render loop skips for having too few
real nodes, zero included, is now always reflected in the thin
figure next to it. Fixes #3548.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit d616c330e3)
2026-09-14 18:49:20 +01:00
ayushcodes10 c5ad8d6852 Add a regression test for unexported require destructures
Pins the exact interaction the fix commit already describes: a
CommonJS const equals require of a module destructure must still
resolve to exactly one EXTRACTED calls edge, not zero, confirming
the export only gate keeps it out of the per name split entirely.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit e9c10258a7)
2026-09-14 18:49:19 +01:00
ayushcodes10 93820c9c01 Add a test for rest pattern skip in destructured exports
A rest element does not correspond to one discrete exported name, so
it must be skipped rather than mangled into a bogus node, and its
sibling names must still extract cleanly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 7091925a3a)
2026-09-14 18:49:19 +01:00
ayushcodes10 7be28b1ca7 Add a test for renamed property export naming
A renamed destructured property must export under its property key,
never under the local alias it is bound to, since that alias is not
what an importer would ever bind by.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 8fae543236)
2026-09-14 18:49:19 +01:00
ayushcodes10 37b3db9654 Add a test for cross file resolution through a split export
A single name import must resolve to its own split node, and a call
made through it must resolve too, not just the import edge on its
own.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 78a3ca4bf7)
2026-09-14 18:49:19 +01:00
ayushcodes10 025caeaa93 Add a test for the per name destructured export split
Four destructured names on one export statement must each get their
own node, and the old combined pattern syntax label must not survive
anywhere in the output.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 3f62c3d85c)
2026-09-14 18:49:19 +01:00
ayushcodes10 fd9b1cdb40 Emit one node per exported destructured name
export const { auth, handlers, signIn, signOut } = NextAuth(config)
is NextAuth version five's own documented boilerplate, and
createNavigation from next intl follows the exact same shape. The
extractor collapsed the whole pattern into one combined node, id
joining every destructured name and label the literal pattern
syntax, so a single name import elsewhere could never find a node
named just auth and the edge, and any call resolved through it,
dangled. Each shorthand and renamed property in the pattern now
becomes its own node sharing the statement's line, exactly what the
export would have produced had it been written as N separate
statements. A renamed property exports under its key, since that is
what an importer binds by, never its local alias. A rest element or
a default valued entry does not correspond to one discrete exported
name and is skipped rather than guessed at.

The split only applies to an actually exported statement. An
unexported destructure of the identical shape, const doWork equals
require of lib being the common one, is a local import binding, not
a module export, and giving it a bare named node in the importing
file would collide with the real definition it only imports, turning
a clean resolution into a false ambiguous name. Caught this against
the existing suite before it ever reached a commit. Fixes #2604's
class 2.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit b1614da58a)
2026-09-14 18:49:19 +01:00
ayushcodes10 13fef586d3 Add changelog entry for issue 3352
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 68c6eafddb)
2026-09-14 18:49:17 +01:00
ayushcodes10 61316e80b6 Add negative control test for an ordinary ASCII path
Confirms the reconstructed prefix set for an ASCII path is byte for
byte identical to what the old ASCII only regex produced, so the fix
changes behavior only for paths the old code was already getting
wrong.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 97bd1f37f0)
2026-09-14 18:49:17 +01:00
ayushcodes10 0ea296e9ba Add end to end regression test for the issue own repro shape
Runs deduplicate_entities on the defining and referencing Korean
node pair in both arrival orders and asserts the defining file own
node survives either way, matching the concrete case the issue
reports: a page whose filename equals the concept name losing its own
node to a page that merely mentions it in passing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 852c61098f)
2026-09-14 18:49:17 +01:00
ayushcodes10 ff6707a015 Add regression test for defines_id on a non Latin path
Confirms the layer above _id_prefixes actually benefits from the
fix: a node whose id and source_file both encode a Korean path is
recognized as defining that id, and a node sharing that id from a
different file is correctly recognized as merely referencing it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 7d15c1bb26)
2026-09-14 18:49:17 +01:00
ayushcodes10 48380444b1 Add regression test for non Latin segments in id prefixes
Confirms the exact repro shape from the issue: the reconstructed
prefix set for a Korean file path preserves every segment instead of
collapsing them to nothing, matching what the file's own id is
actually minted as.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit ab4bde5413)
2026-09-14 18:49:17 +01:00
ayushcodes10 c46241a751 Use the canonical Unicode aware slugifier for id prefixes
Fixes issue 3352.

_id_prefixes reimplemented id segment slugification with its own
ASCII only regex, so any path segment made of non Latin characters
(Korean, CJK, Cyrillic and so on) collapsed to nothing instead of
being preserved. _defines_id, the only real caller, uses these
prefixes to recognize when a node's own source_file is the file its
id encodes, and _collision_rank already implements the definer wins
rule this issue asks for. With the wrong prefixes, a node minted from
a non ASCII path never matched, so a genuine defining page lost the
definer wins tiebreak and the survivor fell through to plain arrival
order, exactly the symptom this issue reports.

Swapping to normalize_id, the same recipe every real extractor mints
an id with, makes the reconstructed prefixes match the ids that are
actually minted for such a file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit e618f332f6)
2026-09-14 18:49:17 +01:00
ayushcodes10 b5247b5a88 Import the canonical Unicode aware id normalizer into dedup.py
Toward issue 3352: _id_prefixes reimplements id slugification with
its own ASCII only regex instead of the canonical normalize_id every
real extractor uses to mint an id, so it silently drops non Latin
characters. This adds the import with no behavior change yet; the
swap lands in the next commit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 237f02d135)
2026-09-14 18:49:17 +01:00
safishamsi e4399cb9ca release: 0.9.62 — sourceless-stub calls, module-level closure calls, C# cross-repo scoping, lua bare require, tokens secret FP, guard-hook timeout 2026-09-13 22:53:43 +01:00
safishamsi 9335cee627 docs(changelog): drop entries the #3529/#3519 cherry-picks injected into released sections
These belong in the next release and will be re-added at the bump with correct
credit (@HARSHAVARDHAN-RAJU5 for #3529) and wording.
2026-09-13 17:49:49 +01:00
A.Levin 9e0ae2cf0b docs(changelog): note the Lua bare-require fix (#3320)
(cherry picked from commit c7c03253e2)
2026-09-13 17:47:57 +01:00
A.Levin 08f5bdf20f fix(lua): emit imports edge for bare require() statements (#3320)
A bare require("mod") with no assignment - the dominant idiom in
Neovim configs - never reached the import handler: only
variable_declaration was in the Lua import dispatch set, so
require(...) used as a standalone statement produced no edge at
all. Detect the require call ahead of the generic import_types
check instead of widening it to function_call, which would have
swallowed every plain call and skipped the walker's recursion into
its arguments (e.g. a require() nested inside a callback passed to
vim.keymap.set).

(cherry picked from commit 2a208bbbb0)
2026-09-13 17:47:57 +01:00
A.Levin 6cebd67d3a test: cover bare require() imports edges for Lua (#3320)
A bare `require("mod")` statement with no assignment produces no imports
edge, while `local x = require("mod")` does. Cover the bare form in the
flattened and lua/config layouts, with and without parentheses, plus
guards for the callback recursion a fix must preserve and for method-style
calls that must not fabricate an edge.

(cherry picked from commit c87586c343)
2026-09-13 17:47:57 +01:00
Dev Chiniwala 46c93444b9 fix(merge): respect C# type visibility across repos
(cherry picked from commit cf6b7f7b68)
2026-09-13 17:47:56 +01:00
ayushcodes10 737db3ac05 Add regression tests for module level anonymous calls
Covers the same file case, the doubly nested repro shape from the
report itself, confirms the number 1740 named enclosing function
case is unaffected, and documents the direct import collision gap
called out in the fix commit as a pin rather than a silent
assumption.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 7983186f2f)
2026-09-13 17:47:55 +01:00
ayushcodes10 75427e5722 Attribute calls in a module level anonymous closure to the file node
Number 1740 fixed calls inside an anonymous callback by attributing
them to the enclosing named function, but that only works when a
named function actually encloses it. it("...", async () => { ... })
has no such enclosing function anywhere, and that shape hits test
files hardest since it is the idiomatic way to write one. The
original report already named the intended fallback, attribute to
the module node when no named function encloses the call, but that
half was never built. A topmost closure argument to a module level
call statement now gets its own function_bodies entry keyed by the
file node, mirroring the existing fix for this.X assignments found
in the exact same statement shape, so the ordinary call walking
machinery, including its own descent into further nested closures,
picks it up from there. Toward #3124.

Known gap left open, described in the new test module's own
docstring: a callee that is both directly imported by the same file
and only called from a module level anonymous closure still does not
resolve, because the cross file resolution pass dedupes purely by
source and target regardless of relation, so the file node's own
import edge to that target pre-empts the calls edge. Fixing that
dedup properly reaches far beyond this one case and is left for a
separate change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 8a0367c505)
2026-09-13 17:47:55 +01:00
Dev Chiniwala 50c9c7d895 fix(extract): skip calls to sourceless stubs
(cherry picked from commit 9f0ad48259)
2026-09-13 17:47:54 +01:00
ayushcodes10 fc33e2ccbd Add regression tests for the guard hook timeouts
One per hook, matching the existing matcher tests, checking the
timeout key is present and stays within a small bounded range rather
than pinning the exact value.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 59535b3e01)
2026-09-13 17:47:54 +01:00
ayushcodes10 575f829f46 Bound the search and read guard hooks with a timeout
An unset command hook defaults to Claude Code's 600 second timeout,
so a single wedged guard, a stuck filesystem or a hung subprocess,
stalls the surrounding tool call for ten minutes on Bash, Grep, Read
and Glob, the four highest frequency tools an agent uses. The guard
itself measures around 170 milliseconds warm, so both generated
entries now carry a 10 second timeout, generous headroom over the
measured cost while still two orders of magnitude below the unset
default. Toward #3314.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit fd08017d22)
2026-09-13 17:47:54 +01:00
HARSHAVARDHAN-RAJU5 3eb2486803 fix: bare plural "tokens" in a prose file is no longer treated as a secret
TOKENS.md / tokens.md read as design-token reference docs, not credential
dumps, unlike singular "token.md" or another keyword's bare plural
("secrets.md"), which still exclude. The .dart/.ts design-token source
files from the original report are already covered by the existing
graphable-source exemption; this closes the remaining prose-note gap.

Fixes #3527

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A6anVY9hgp5ph5qLXRmc2p
(cherry picked from commit 64e85524ef)
2026-09-13 17:47:53 +01:00
safishamsi fe66389083 release: 0.9.61 — fix Python 3.12/3.13 breakage from 0.9.60
- chinese extra: pin jieba-py from 3.12 (was 3.14); jieba's invalid escapes are
  a hard error on 3.12+ and broke graphify.serve import.
- serve.py: suppress the tokenizer SyntaxWarning by category so -W error can't
  escalate it; catch SyntaxError as a fallback.
- hooks.py: harden the #3492 rebuild-root guard for 3.13, whose resolve() no
  longer raises on a symlink loop — require a real directory.
Verified full suite green on both 3.10 (5628) and 3.13 (5627).
2026-09-12 22:23:00 +01:00
safishamsi 7464f5b125 release: 0.9.60 — Windows os.replace fallback, unclassified-file surfacing, C/C++ newline parse, Office sidecar fix, exported-function call resolution, workspace export conditions, Python 3.14 support 2026-09-12 21:54:14 +01:00
safishamsi 2b58bddf8b chore(lock): sync uv.lock for the #3490 dependency-floor bumps; fix stale skillgen windows test
The #3490 lock predated its own setuptools>=83 / pypdf / yt-dlp floor bumps, so
a frozen sync resolved setuptools 82.0.1 and the no-isolation wheel-build test
failed. Regenerate the lock so it honors the floors. Also update the windows
skill test: the troubleshooting item is now 'Skip Leiden' (graspologic ->
graspologic-native gating), which #3490 changed in the fragment but not the test.
2026-09-12 21:49:56 +01:00
taazbro 200f3a15b5 fix: address Python 3.14 review findings
(cherry picked from commit c49db38935)
2026-09-12 21:35:25 +01:00
taazbro 0fc31470b0 fix: raise vulnerable dependency floors
(cherry picked from commit 7590ec5856)
2026-09-12 21:33:43 +01:00
taazbro b42e5bc5c2 fix: support Python 3.14 optional dependencies
(cherry picked from commit 76bb841de0)
2026-09-12 21:33:43 +01:00
dajiaohuang 47ddc5c47b fix(imports): pick workspace exports by importer platform, runtime before types
The workspace `exports` resolver reduced a condition object to a single target,
so a package that splits its runtime source from its declarations never
produced a cross-package edge. Reported in #3487; the exports map itself is
present and works, the defect is in how one is chosen.

`_EXPORT_CONDITION_PRIORITY` listed `types` ahead of `require` and `default`.
`types` is declaration-only and normally points into `dist/`, which is build
output and not part of the corpus, so the resolver returned a path that is not
on disk and stopped there — `_package_entry_candidates` returned `[candidate]`
as soon as any condition matched, so the `default` source beside it was never
tried and the import became a dangling `ref_*` external.

That is not the order the map was added with. #1308 specifies
`source -> import -> module -> default -> require -> types`, and the commit
that implemented it says `default` is consulted LAST so a matching
`import`/`module`/`svelte` condition wins; the tuple shipped with `types` in
the middle instead.

Three changes, all on the workspace `exports` path:

- `types` moves to the end of `_EXPORT_CONDITION_PRIORITY`, restoring the
  specified order. `require`/`default` keep their relative order, so the
  behaviour pinned by `test_workspace_subpath_export_default_consulted_last`
  is unchanged.
- `_resolve_export_targets` keeps every condition target in preference order
  instead of returning the first, so a target that is not on disk falls
  through to the next condition rather than taking the import down with it.
- `react-native` is honoured only for an importer that is itself native, and
  each target is tried alongside its platform-suffixed siblings
  (`Icon.tsx` -> `Icon.web.tsx` / `Icon.native.tsx`), which is how a bundler
  reaches a platform split whose `exports` target names the unsuffixed path.
  Importer platform comes from whole path segments, so `apps/mobile/src` is
  native while `packages/web-utils` is not web.

`_resolve_export_target` keeps its signature and its semantics for the
`package.json` `imports` path, and platform expansion applies only to the
workspace `exports` path, so relative imports elsewhere are untouched.

Behaviour note for review: when every `exports` target escapes the package
directory, resolution still falls through to the bare-path fallback exactly as
before. The first revision of this change swallowed that fallback, which the
containment guard made reachable, and a test now pins it. The `"."` branch
additionally gains the containment guard its subpath sibling already had; that
is the only change here beyond the reported defect, and such a package
previously resolved outside its own directory.

Verified: same 29 pre-existing failures before and after, byte-identical
failure sets (`diff` clean; unrelated to this path — non-regular-file, watch
and uninstall-scope tests on Windows). Passing goes 5500 -> 5507, the seven
tests added here. The fixture from #3487 resolves its four previously-dropped
imports and leaves the three control cases unchanged; focused run 109 passed;
`ruff check` clean; all five `tools.skillgen` CI-parity checks OK.

(cherry picked from commit c704a5b2f2)
2026-09-12 21:31:35 +01:00
abhay-codes07 cd6e05df8a fix(js): resolve calls inside exported functions, incl. aliased imports (#3346)
_js_top_level_function_bodies scanned only direct program children, so a
top-level `export function f(){}` / `export const g = () => {}` — wrapped in
an export_statement — was skipped and the calls inside it never became `uses`
facts. Only the use-fact path consults the per-file import-alias table, so an
aliased-import call (`import { bar as baz }; baz()`) produced no calls edge:
the plain-name global resolver has no `baz` to match, and the alias mapping
that would have pointed it at `bar` was never exercised. Unwrapping a
non-re-export export_statement to its inner function/arrow declaration treats
exported and non-exported functions identically, so the alias table resolves
the call to the real definition.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 7d98266538)
2026-09-12 21:31:34 +01:00
ayushcodes10 600e4e7491 Exempt Office/Workspace sidecars from the ignore check
detect() converts Office files and Google Workspace shortcuts into
markdown sidecars under a converted subdirectory of the output dir,
then ran the same scan ignore check on the sidecar's own path. The
documented gitignore advice puts the whole output dir inside a
gitignored tree, so that check rejected the tool's own output for
the same reason a user would gitignore it, and the source document
vanished from the corpus with nothing recorded about why. The check
exists to keep user files out of the scan, not to filter output this
same pass just produced from an already admitted source, so a
sidecar under the converted directory is now exempt from it. Fixes
#3504.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 900b376d39)
2026-09-12 21:31:33 +01:00
Imanol Gutiérrez 81f7d68838 Add tests for newline char at EOF fix
(cherry picked from commit 543c171ec1)
2026-09-12 17:39:27 +01:00
Imanol Gutiérrez c32d30060d Add a newline char at EOF on C and C++ headers
(cherry picked from commit ff900a00d8)
2026-09-12 17:39:27 +01:00
ayushcodes10 cd8552242c Report unclassified files from graphify update too
graphify extract has printed this since #1692, but the update and
watch rebuild path never did, so a corpus with no extractor for its
language, Lean 4 in the reported case, rebuilt successfully with
those files completely absent and nothing said about it. Prints the
same wording from the extract command, and threads the count into
the local detection summary the rebuild path already builds for
GRAPH_REPORT.md, which previously dropped it. Fixes #3511.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 120405673f)
2026-09-12 17:36:10 +01:00
ayushcodes10 c9da36d87c Surface unclassified files in GRAPH_REPORT.md
detect() already returns every file it saw but could not classify, no
supported extension or shebang, but nothing read it: a corpus mostly
in an unsupported language got the same well covered verdict as one
that was actually extracted, silently. Adds an Unclassified line to
the Corpus Check section naming the count and the biggest offending
extensions. Toward #3511.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit f08e50534d)
2026-09-12 17:36:10 +01:00
ayushcodes10 0fd1f141d4 Guard os_replace_with_fallback against src equal to dst
Replacing a path with itself, if the initial os.replace call ever
fails for that call, crashed: the fallback backs dst up by renaming
it aside before landing the new content, and when src and dst are
the same path that rename moves src out from under itself, so the
final unlink of src then raised FileNotFoundError. Not reachable
through any current caller, every one passes a distinct temp file,
but cheap to guard against directly. Found by the graphify review
bot on PR 3509.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 5b108e1a1f)
2026-09-12 17:36:09 +01:00
ayushcodes10 4c27b61058 Restore the destination if the fallback swap fails
The fallback removed whatever sat at the destination and then
renamed the new content into place as two separate steps, so a
failure in the second step left nothing at that path at all, worse
than the original write it was trying to protect. Now renames the
existing destination aside as a backup instead of unlinking it, and
renames the backup straight back if the final rename fails, so a
mid swap failure restores the original rather than losing it. Found
by the graphify review bot on PR 3509.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit b56c77a107)
2026-09-12 17:36:09 +01:00
ayushcodes10 4489552b55 Preserve replace semantics for a symlinked destination
os.replace atomically swaps whatever sits at the destination, a
symlink included, by replacing the link itself. install.py relies on
exactly that for its managed skill symlinks, per #3286. The
fallback's plain shutil.copy2 does the opposite when the destination
is a symlink: opening it for writing follows the link and overwrites
whatever it points at instead of the link. Copies to a fresh temp
file beside the destination first, then swaps the destination out
from under it with an unlink plus rename, matching replace's own
behavior and, as a side effect, shrinking the window where a reader
could see a half written file down to two fast metadata operations
rather than however long the copy itself takes. Found by the graphify
review bot on PR 3509.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 39effa0c28)
2026-09-12 17:36:09 +01:00
ayushcodes10 784b1fb1bd Use the replace fallback for skill install writes
Fixes #3508's other reported failure: the Kiro skill install died on
the same WinError 17 while replacing SKILL.md. Covers the version
stamp write too, which shares the same pattern beside it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit e6ac02a49d)
2026-09-12 17:36:09 +01:00
ayushcodes10 c9aff7fb06 Use the replace fallback for GraphML export
The GraphML writer replaced its temp file directly with no Windows
fallback of any kind, so a mid size export could hit the same class
of failure as the cache and install paths.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit ab2bde0956)
2026-09-12 17:36:09 +01:00
ayushcodes10 f71e75eb31 Use the replace fallback for AST cache writes
The AST extraction cache writes its own temp file and replace, a
separate code path from the shared atomic writer, and only caught
PermissionError. This was the exact write named in the report: worker
failed for a file with WinError 17 while replacing a cache entry
under the output directory's ast cache. Also covers the stat index
write, which had no Windows fallback at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 7638d47565)
2026-09-12 17:36:09 +01:00
ayushcodes10 df5a9042e3 Add a shared Windows replace fallback helper
os.replace can fail on Windows even when the temp file and the
destination are in the same directory on the same drive: WinError
17, "cannot move to a different disk drive", maps to a plain OSError
in Python rather than PermissionError, so the existing copy then
delete fallback for WinError 5 and 32 never caught it. Adds
os_replace_with_fallback, checking both PermissionError and winerror
17, and points the shared atomic writer at it instead of its own
inline PermissionError only version. Toward #3508.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 32cbf1f83e)
2026-09-12 17:36:09 +01:00
safishamsi 522ea9662e release: 0.9.59 — incremental dedup node-loss fix, pool-start fallback, 47% faster Python resolution, explain path::Symbol, hook rebuild-root clamp 2026-09-12 15:17:30 +01:00
ayushcodes10 7a09d9ae57 Catch symlink loop RuntimeError in the root guard
Path.resolve() raises RuntimeError, not OSError, when a symlink chain
loops back on itself, so the #3265 in repo check let that propagate
up instead of falling back to the repo top like every other bad
marker value. Since a fork or PR can commit an actual symlink loop
alongside a crafted .graphify_root value, an untrusted checkout could
still turn the guard itself into a failure path. Both rebuild bodies
now catch RuntimeError alongside OSError. Found by the graphify
review bot on PR 3492.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 96d48c76b5)
2026-09-11 23:58:32 +01:00
ayushcodes10 e581565e95 Add regression tests for the git hook root guard
Executes the shipped snippet directly (extracted from the rebuild
body text) rather than a hand copy that could quietly drift from it,
covering both the rejected case (a marker pointing outside the repo)
and the case the guard must not break (a subdirectory scoped root).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 5976f7122a)
2026-09-11 23:58:32 +01:00
ayushcodes10 9e734a1ad2 Keep the git hook rebuild root inside the repo
Team setup documents committing the graphify output directory, and
.graphify_root lives inside it, so its contents are checkout
controlled. Both generated git hooks read that file and pass its
value straight to _rebuild_code with no bound, so a value planted
there by a forked PR could point the rebuild, and therefore what it
reads and what it writes back into that same committed directory, at
a location outside the repository the hook runs in. Both rebuild
bodies now only adopt the saved root when it resolves inside the
working tree the hook is running from, falling back to the repo top
otherwise. Fixes #3265.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 31aa4d4e9d)
2026-09-11 23:58:32 +01:00
ayushcodes10 3cd785c65d Stop path::Symbol from shadowing a literal :: label
A native Rust or C++ label containing "::" could be hijacked by the
new path::Symbol resolution when the substring before "::" happens to
match some unrelated file elsewhere in the graph, for example an
extensionless file literally named the same as a Rust module. The
query would then resolve to a node in that unrelated file instead of
the node the literal label actually names. Path scoped resolution now
only runs when the raw, unsplit label does not already have a literal
exact match among real node labels, since a genuine label essentially
never equals a whole path plus symbol string verbatim. Found by the
graphify review bot on PR 3491.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 642f62a0e1)
2026-09-11 23:58:31 +01:00
ayushcodes10 6e19e0eb31 Point the ambiguity message at path::symbol
The prior retry suggestion, a bare repo relative path, resolves to the
file node rather than the symbol, so following it never actually
disambiguates anything. Now that path::symbol exists, point both the
explain CLI and the shared MCP resolver at it, using a generic
placeholder rather than one of the rival paths so the message stays
the same regardless of node iteration order.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit c18f3d0a2c)
2026-09-11 23:58:31 +01:00
ayushcodes10 f9b6f21194 Add path::Symbol resolution for explain
A bare symbol name that exists in multiple files is ambiguous, and the
only suggested retry (a bare repo relative path) resolves to the file
node itself, never the symbol, so it could not actually disambiguate
anything. This adds a path::Symbol form that restricts the label match
to nodes defined in that file, wired into _find_node_tiers ahead of
the ordinary tiers so it is available to explain, get_node and
get_neighbors alike. Fixes #3485.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 84a2da2769)
2026-09-11 23:58:31 +01:00
himanshupatro-334 2f2bfd1bc2 test: route carried-hyperedge dedup through a re-extracted chunk (#3503)
Under #3503 (#3477) existing nodes from untouched files are protected from
dedup collapse, so the carried-hyperedge remap test must deliver the duplicate
via an incoming re-extracted chunk to fold into the protected survivor.
2026-09-11 22:51:35 +01:00
safishamsi 047dd93187 fix(resolution): clear the #3500 path-resolution caches per extract() run
The memoized path/source-key lru_caches are keyed by (path, cwd) with no mtime
component; without a per-run clear they replay stale results across repeated
extract() calls in a long-lived watch/MCP process. Wire them into the existing
cache-clear block. (follow-up to #3500)
2026-09-11 22:47:27 +01:00
abhay-codes07 cd8d99b2f4 perf(resolution): memoize Path.resolve() across the symbol-resolution passes
The symbol-resolution and cross-file import passes call Path.resolve() once
per import/export/use fact and per node — ~44k calls over a few hundred
distinct corpus paths, each walking nt._getfinalpathname on Windows. A
per-(path, cwd) memo collapses that to one syscall per distinct path. On a
364-file self-corpus a sequential extract drops from ~27s to ~14s, graph
byte-identical. The cwd is part of the key so a relative path resolved after
a chdir misses rather than replaying a stale answer.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 5ca30dfd8a)
2026-09-11 22:46:36 +01:00
abhay-codes07 d7de19d47d perf(resolution): memoize source-key resolution in the id-disambiguation pass
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 2adfa810c9)
2026-09-11 22:46:36 +01:00
abhay-codes07 f077217191 perf(resolution): parse each Python file once across both resolution passes
The symbol-resolution facts pass and the cross-file import pass each parsed
the whole .py corpus, back to back, in the main process — every file read
and tree-sitter-parsed twice for nothing. _parse_python_tree now memoizes on
(path, mtime, size), so the second pass reuses the first pass's tree while a
file changed between watch runs still re-parses. On a 364-file self-corpus a
sequential extract drops from ~27s to ~24s, graph byte-identical.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit dcbab53879)
2026-09-11 22:46:27 +01:00
abhay-codes07 a572b88777 perf(resolution): walk the Python tree iteratively, not via recursive yield-from
_walk_python_tree drove the symbol-resolution passes through a recursive
generator: one suspended frame per tree level, every node re-propagated up
the whole chain — ~25M frame resumptions on a 364-file corpus for ~2.8M
nodes. An explicit stack yields the identical preorder (node identity and
order verified) in ~30% less time, and no longer risks RecursionError on a
deeply nested tree. Same rewrite _walk_js_tree already carries.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit e1544e0ad4)
2026-09-11 22:46:26 +01:00
Curtis Muir 3f6ca655dd fix(extract): fall back to sequential when the process pool cannot start
_extract_parallel falls back to sequential on BrokenProcessPool, but an
OSError raised while constructing the ProcessPoolExecutor escaped and
killed the whole extraction (and `graphify update`).

Seen on macOS: ProcessPoolExecutor -> multiprocessing SemLock -> sem_open
fails with OSError(ENOSPC), "No space left on device", once leaked POSIX
named semaphores exhaust kern.posix.sem.max — with the disk nowhere near
full. Sequential extraction needs no semaphore, so hand back False the
same way the BrokenProcessPool branch does, with a warning that names the
OS error rather than the Windows __main__ hint.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
(cherry picked from commit c154c01d50)
2026-09-11 22:46:26 +01:00
himanshupatro-334 8a89253fec Scope deduplication during incremental merges
(cherry picked from commit 9e65a71993)
2026-09-11 22:46:15 +01:00
safishamsi 23f2ffaa43 release: 0.9.58 — python/php/bash import resolution, dedup source-path normalization, SQL indexes, rust statics, install/labelling robustness, all-extra psycopg 2026-09-10 23:19:02 +01:00
safishamsi 519f322125 chore(lock): sync uv.lock for the psycopg[binary] all-extra (#3483) 2026-09-10 23:05:15 +01:00
L4XB fc179f3394 fix(packaging): include psycopg[binary] in the all extra
The postgres extra's psycopg[binary] was the sole dep missing from all; a new
union test guards the all-extra against future drift. (#3483)
2026-09-10 23:05:04 +01:00
L4XB ec12e5e341 test: isolate backend-detection tests from the developer's environment
Autouse conftest fixture clears every backend env var detect_backend() reads
(API keys, Azure/AWS/Ollama), with a self-guard test that the cleared list
covers every variable the detector reads. (#3484)
2026-09-10 23:04:40 +01:00
safishamsi 2f9279f108 test(labeling): keep the no-backend test hermetic against the claude-cli fallback
#3475 added a PATH probe for a claude-cli labelling fallback; the no-backend
test must neutralize it so it stays deterministic on machines with claude
installed (follow-up to #3475).
2026-09-10 22:45:31 +01:00
ktsang622 d9e094c2e2 fix: label via an installed claude CLI, and stop pinning a path that expires
Two independent failures, both silent, found while repairing 16 repositories whose
graphs had quietly stopped tracking their code.

1. `graphify label` downgraded graphs while reporting success

`detect_backend()` is key-based, and `claude-cli` is the one backend with no API key
to find — `_get_backend_api_key` can never return one for it, and the fallback loop
excludes it by name. Nothing else looked for it. So on a machine with the Claude Code
CLI installed and no API key, labelling announced "no LLM backend configured",
replaced every real community name with a `Community N` placeholder, and exited 0.
Run over an existing graph, that overwrites good names with worse ones and looks like
success; taking the exit code at face value commits the damage.

The fallback is placed in the labelling path, NOT in `detect_backend()`. Widening
detection itself was the first attempt and it broke
`test_mixed_repo_without_key_errors_and_points_at_code_only`: extraction deliberately
refuses to run without a configured backend and points at `--code-only`, and on any
machine with the CLI present that contract would have silently changed to "shell out
to the CLI instead". That contract is unchanged here, and a test now pins it.

2. The post-commit hook pinned a path with an expiry date

`_pinned_python()` wrote `sys.executable` verbatim. graphify installed from inside a
snap-confined editor lives under `~/snap/<app>/<revision>/`, and snap swaps that
revision on update and prunes the old tree. Every hook pinned to it then dies —
observed across 15 repositories at once when an editor snap moved past revision 259.
Each commit printed "could not locate a Python with graphify installed" and the graphs
stopped following the code, with nothing failing loudly enough to notice.

Two changes: `_pinned_python()` declines to pin a path under a rotating revision
directory, which its docstring already describes as safe degradation; and the
uv-tools probe — which already scans tool environments — additionally scans
snap-confined HOMEs by glob, since an install made inside a snap lands in that snap's
private HOME and the plain `$HOME` roots never see it once the hook runs from an
ordinary shell.

Verified: same 25 pre-existing failures before and after (unrelated: terraform
fixtures, a TS scaling test); passing goes 5110 -> 5119, the nine tests added here.
Each change was mutation-tested — removing it fails a test that the others still pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
(cherry picked from commit c6065e24ea)
2026-09-10 22:44:40 +01:00
dajiaohuang 496112d6fc fix(install): do not abort the install when always-on registration is unwritable
`install()` copies the skill files first and writes the always-on
registration afterwards, so an unguarded write to `~/.claude/CLAUDE.md`
left a half-completed install plus a traceback whenever that file could
not be written. That is the normal shape for a declaratively managed
dotfile: nix/home-manager symlinks it into a read-only /nix/store, and
chezmoi or stow with read-only sources do the same.

Route the two registrations inside `install()` (CLAUDE.md and
CODEBUDDY.md, which had the identical unguarded pattern) through one
helper that reports the skip on stderr and lets the install finish, so
the skill files that were already laid down stay usable.

Refs #3474

Co-Authored-By: Claude Code <noreply@anthropic.com>
(cherry picked from commit 47041eef5d)
2026-09-10 22:44:40 +01:00
himanshupatro-334 437c9629bd Fix same-file source path collision during merge
(cherry picked from commit fa1284a356)
2026-09-10 22:44:39 +01:00
L4XB ab80fa7413 fix(rust): extract module-level static and const declarations
The Rust extractor gated every non-function item on struct_item,
enum_item and trait_item, so tree-sitter-rust's static_item and
const_item never produced a node: a constant existed in the graph only
through the files that referenced it, never from the Rust that defines
it (0 of 783 names in a jdx/mise snapshot).

Add a branch for both node types: a module-level declaration gets a
node with a file-level contains edge, an associated const inside an
impl is attributed to the impl like a method, and the declared type is
referenced the way a struct field type is.

Fixes #3471

(cherry picked from commit 70ff464064)
2026-09-10 22:44:38 +01:00
safishamsi adf814fd5e docs(readme): replace the header card with the graphify logo (png) 2026-09-10 15:39:24 +01:00
safishamsi b15cc167ee docs(readme): replace the header logo with the animated graphify card 2026-09-10 15:30:39 +01:00
L4XB d2abe4ed0c fix(sql): emit index nodes for CREATE [UNIQUE] INDEX statements
Adds an AST branch for create_index in the SQL extractor, emitting an index
node with an 'indexes' edge to its table (cross-file stub when the table is
defined elsewhere), mirroring the existing trigger handling. (#3470)
2026-09-10 14:51:54 +01:00
L4XB 355eefd391 fix(ts): keep star-export resolution off same-named interface methods
A workspace-barrel import (`import { evaluate } from '@scope/domain'`)
resolves through `export *` by probing each star target for a symbol
node with the imported name. The symbol map normalizes labels by
stripping the leading dot, so an interface/class METHOD `.evaluate()`
in the first star target satisfied the probe before the exported
function in the second one was reached. The import edge and the
cross-file call then bound to the method node, and the real function
lost its inbound `calls` edge (read as dead code).

Track member nodes separately and skip them in the star-export walk: a
module can only re-export top-level bindings. A member never shadows a
same-named top-level symbol in the map anymore either.

Fixes #3436

(cherry picked from commit 52e4a2b131)
2026-09-10 14:03:23 +01:00
xuxiongjian 76de060036 Never infer an empty repo tag for global add
`tag or source.parent.parent.name` is empty whenever the graph is not two levels
below a named directory: `graphify global add /tmp/graph.json`, or any relative
path. Every node is then prefixed `::`, the prune key is `""`, and the manifest
entry cannot be removed because the `remove` subcommand reads an empty tag as a
missing argument.

Infer through `distinct_repo_tags`, the helper `merge-graphs` already uses, so the
two entry points cannot diverge again and the degrade is `"repo"`; absolutize
first so a relative path names the repo dir rather than the cwd placeholder. An
omitted `remove` tag stays a usage error, while an explicitly empty one is now
addressable so stores written by earlier revisions can be cleaned up.

(cherry picked from commit 6a317e6ef2)
2026-09-10 14:03:22 +01:00
xuxiongjian dba63f7c9e Import Iterable in build.py, the annotations already use it
build.py annotates chunks and ast_sources with Iterable but never imports it, so
ruff reports four F821 on v8 and typing.get_type_hints() raises on
_tier_replacement_sources, merge_raw_extraction and build_merge. Nothing breaks at
import because `from __future__ import annotations` keeps the hints as strings.

The added test walks build.py's own functions rather than the package: nx under
if TYPE_CHECKING in cross_repo_calls.py, cross_repo_types.py and prs.py is
unresolvable on purpose, while build.py imports every annotated name at module scope.

(cherry picked from commit c315a15c24)
2026-09-10 14:03:22 +01:00
edwardselby 3dc3f4d78c fix(bash): resolve exec-position script paths built from a variable
`script_invocation` edges (#1756) only ever resolved a path that is a
bare literal -- `./helpers.sh`, or `bash ./helpers.sh`. Both paths into
that branch go through `literal()`, which rejects by design any token
containing `$`, so the single most common way a shell script calls a
sibling is invisible:

    script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    "$script_dir/helpers.sh" --flag

`cmd` is None for that command node, the `elif cmd and ...` guard short-
circuits, and no edge is emitted. On a 206-file shell tree that uses the
`script_dir` idiom throughout, `script_invocation` produced *zero* edges
-- the feature was effectively dead for that whole style of codebase.

The `source` branch already solved the same problem for
`source "$DIR/lib/x.sh"` (#2079): strip the leading `${VAR}/` segments
with `_bash_source_suffix` and resolve the literal remainder against the
sourcing file's own directory, because the canonical `script_dir` idiom
makes that variable equal to exactly that. This applies the identical
treatment to the exec position -- read the command-name node's raw text
rather than its `literal()`, strip the same way, and fall through to the
existing `resolved.is_file()` gate.

Nothing new is fabricated. `_bash_source_suffix` still returns None when
the remainder holds another expansion (`"$dir/$name.sh"`) or a `..`
segment, and the on-disk check still means a wrong script-dir guess
emits nothing at all. The three existing negative tests -- missing,
shadowed, and dynamic invocations -- pass unchanged.

Measured on the same 206-file tree: 0 -> 16 edges across 10 distinct
file pairs, every one hand-checked to a real invocation of a real file,
no false positives. Full suite: no change in outcomes (the 25 failures
here are pre-existing and unrelated -- terraform, ollama, skillgen).

Fixes #3416.

(cherry picked from commit 2e112c39fc)
2026-09-09 17:20:57 +01:00
abhay-codes07 34735fa762 fix(detect): probe every out subdirectory under an entry budget, not the first 20
Review follow-up: a wide TS outDir keeping compiled files only under a
late-sorted module dir slipped past the 20-subdirectory cap. The level-two
probe now covers every subdirectory, bounded by total entries scanned.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit ff0a8f6d64)
2026-09-09 17:20:57 +01:00
abhay-codes07 ba9b3e3d6c fix(detect): gate the bare out dir on build-output evidence (#3347)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit eca5af36f1)
2026-09-09 17:20:57 +01:00
ayushcodes10 465270fba3 Prefer the alias for a PHP use import edge's target
An aliased use clause (use GuzzleHttp\Client as HttpClient) always
targeted the bare imported name, ignoring the alias entirely. Two
files importing the same external class under different local
aliases, a real pattern for disambiguating two same named classes
from different namespaces, produced two different stub targets for
one class, splitting its identity. The cross file resolver repoints
a stub through the file's own alias to FQN map, keyed by the alias
when the import has one, so a bare name derived stub could never be
found under that key and stayed stuck, unresolved. The alias, when
present, is also what the rest of the file actually references, so
preferring it here keeps this edge's target consistent with those
reference edges too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017qfdzgbA5KedGEjD1AayNh
(cherry picked from commit 73f9f1667b)
2026-09-09 17:20:56 +01:00
himanshupatro-334 5dd24de1c9 Fix loose sibling module import resolution
(cherry picked from commit d00d3aea14)
2026-09-09 17:20:56 +01:00
flaukowski d4531f3d25 fix(python): resolve submodule imports inside PEP 420 namespace packages
`from . import brain, ledger` in a directory with no __init__.py — a
namespace package, which `python -m pkg.mod` runs without complaint —
emitted nothing: _resolve_python_module_path returns None when there is
no module file to probe, and the #1146 submodule branch sits behind that
None. So every `brain.think()` / `ledger.write()` call in such a repo was
invisible to the #1883 module arm, and the most-called functions carried
in-degree 0 in the graph.

_resolve_python_namespace_dir mirrors the module-path walk (relative
base, scan root, then sys.path-root ancestors per #2072) and returns only
a directory that exists inside the root and has no __init__.py. The fact
collector uses it when the module path resolves to no file; the existing
submodule probe then emits the same imports_from edges a regular package
gets. A name that is not a module file on disk still emits nothing, and
a namespace package binds no symbols of its own.

Measured on a 275-node Python repo laid out this way, same graphify
version with and without the change: calls 201 -> 307, nodes unchanged;
think() 0 -> 15 callers, remember() 0 -> 10, ledger write() 0 -> 20.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTNEBgonu6ASph6w8R2Wcp
(cherry picked from commit e2ec796bfd)
2026-09-09 17:20:55 +01:00
himanshupatro-334 c967797f62 Fix Python nested function resolution
(cherry picked from commit 416be1e9c7)
2026-09-09 17:20:54 +01:00
safishamsi 3f82bf7f83 release: 0.9.57 — incremental cross-file merge fix, richer dedup survivor, C# generic call sites, JS this-member forms 2026-09-09 13:00:13 +01:00
himanshupatro-334 32b209ae10 Fix incremental merge of cross-file project stubs
(cherry picked from commit 8286a51511)
2026-09-09 11:30:29 +01:00
abhay-codes07 5e6c2be092 fix(dedup): pick the richer duplicate as survivor and keep the losers' fields (#3372)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit a3ba93b859)
2026-09-09 11:30:29 +01:00
abhay-codes07 1dc0dc9423 fix(js): keep this.X = function members in every enclosing-function form (#3408)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 08487e9a73)
2026-09-09 11:30:28 +01:00
abhay-codes07 5d09dce42c fix(csharp): resolve unqualified generic call sites, Get<int>(...) (#3406)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 6d8086d585)
2026-09-09 11:30:27 +01:00
safishamsi 67f99bd005 release: 0.9.56 — rust trait methods, Windows temp-path bound, hook-skip subshell, @/ + Node subpath imports, undirected MCP query, builtin member calls, worker cleanup, TS normalizer perf, Dart source_location 2026-09-07 20:47:42 +01:00
safishamsi 20a631ea70 test(ts): measure CPU time in the normalizer scaling test to de-flake it
perf_counter counts wall-clock, which includes time the process is preempted
off-CPU during a busy full-suite run, inflating the larger measurement and
flaking the ratio. process_time counts only CPU work, isolating the algorithmic
scaling. Follow-up to #3402.
2026-09-07 20:30:19 +01:00
ayushcodes10 3b9356bae6 Add source_location to Dart extraction
extractors/dart.py hardcoded source_location: None at every node and
edge construction site, so a Dart graph could cite zero lines no
matter how many declarations it had (0% across three real repos,
~25k unciteable nodes in one of them).

Threads a line number through add_node/add_edge from each match's own
offset, anchored on the capture group rather than the whole match: a
pattern like the class declaration's leading ^\s* otherwise reports
the line too early when blank lines precede the declaration.

The comment stripping pass also needed a fix first: it deleted a
comment token outright, so a multi-line comment shifted every later
offset (and therefore every later line number) up by the comment's
own height. Blanking it to the same number of newlines instead keeps
src_clean's line count in step with the original file.

Sourceless reference stub nodes (an inherited class, a mixin, an
import target, and similar names the file only references rather
than defines) keep source_location: None, same as before, since there
is no single line in THIS file for a symbol that lives elsewhere.
Every node this file actually defines, and every edge attributed to a
real declaration site, now carries its real line.

Fixes #3365.

(cherry picked from commit 0dbcefc5ba)
2026-09-07 20:21:35 +01:00
Sagexd08 82b25b9a96 fix(extract): make _TsRangeIndex a real type alias
The alias was written as a quoted string, which makes it a `str` *value*
rather than a type. Type checkers reject it: mypy reports "Variable
_TsRangeIndex is not valid as a type" at both annotation sites, plus two
cascading errors where the tuple loses its type and the unpacking/indexing
in _ts_ranges_containing and _normalize_ts_import_types become untyped.

`typing.get_type_hints` happened to resolve it at runtime because it
evaluates the annotation string and then the alias string again, so nothing
failed in practice -- but that is an accident of double evaluation, not a
working alias.

Unquote the right-hand side. The module already has
`from __future__ import annotations`, so the annotations themselves need no
quoting either. No behavior change.

(cherry picked from commit d902820ccf)
2026-09-07 20:21:35 +01:00
Sagexd08 1dcb1e1f3a fix(extract): remove quadratic scan in TS import-type normalization (#3359)
`_normalize_ts_import_types` filtered each `import(...)` regex match against
every tree-sitter `type_arguments` byte range with a nested linear scan, in
both the pre-mask and post-mask passes:

    matches = [m for m in matches
               if not any(start <= m.start() < end
                          for start, end in original_type_ranges)]

That is O(matches x ranges), and `m.start()` is re-evaluated inside `any()`
for every range — which is why profiles blamed `re.Match.start`/`_sre` and
`sample` appeared to show a pathological regex. The regexes are all linear;
the quadratic caller was the real cost.

Both counts grow with file size in TypeScript that mixes generic calls
(`fn<A, B>(x)` — one `type_arguments` range each) with `import(...)` types,
which is the shape of generated and barrel modules in a large monorepo. On
the filter alone: a 0.8MB/10k-import file took ~21s, 2.1MB/25k ~2.6min, and
4.2MB/50k ~11.8min. With several such files `extract` never finished, and a
worker sat at 100% CPU holding no open files because the work is entirely
in-memory after the read.

Replace both scans with a binary search over start-sorted ranges plus a
prefix-maximum of `end` values, so a lookup touches nesting depth rather
than every range. Type-argument ranges nest but never partially overlap, so
the prefix maximum is a correct stop condition; a *closed* inner sibling
must not terminate the leftward walk, which a naive running-max break gets
wrong. Verified against the old predicate with 500k differential cases,
including non-nested random ranges: zero mismatches.

Normalization output is unchanged — byte-length and line-count preserving,
same masking decisions, and the runtime-vs-type disambiguation from 6baa5e0
still holds.

Also restore the emptiness guard in the second pass: the range list is now
an index tuple, which is always truthy, so it checks the spans it holds.

The new test asserts on scaling (2x input must not ~4x the time) rather than
wall-clock, so it is not machine-dependent. It fails at ~3.4x before this
change and passes after.

(cherry picked from commit b662361d8b)
2026-09-07 20:21:35 +01:00
vldlnr 98d62e231c test(labeling): pin max_concurrency=1 so batch-order assertion is deterministic
The assertion recorded the order batches reached their LLM call inside worker
threads, which is nondeterministic; the product merges by cid on the main
thread and concurrency equivalence is covered by a sibling test. Takes only the
flaky-test fix from #3374 (its SECURITY.md/uv.lock changes are handled
separately).
2026-09-07 19:03:11 +01:00
Julien E 2d54b05db2 fix(js): resolve Node subpath imports via package.json imports
`import X from '#services/x'` — Node's subpath-imports field, and the way
every AdonisJS 6 app reaches its own modules — was never resolved: the JS
resolver only knew tsconfig `paths` and workspace packages. In a real
Adonis app 438/680 alias imports produced no edge and `affected
"ZitadelService"` listed 2 nodes from a stray root script instead of the
7 controllers and the auth middleware that depend on it.

Resolve `#…` specifiers through the nearest package.json `imports` map,
after tsconfig `paths` (explicit aliases keep precedence, #1269) and
before workspace packages. Node semantics: exact key or a single `*`
wildcard, longest literal prefix wins, condition objects go through
_resolve_export_target, and only `./` targets are followed so an external
mapping keeps the ref-namespaced external id (#1638). The map applies to
every file in the package, so a nested tsconfig without the aliases
(e.g. `inertia/tsconfig.json`) no longer shadows it. Cached per start
dir and cleared per extract() run like the tsconfig caches (#2917).

Measured on a 966-file AdonisJS + Inertia repo: alias imports resolved
go from 242/680 to 680/680 in app/ and 17/17 in inertia/.

Claude-Session: https://claude.ai/code/session_011z6vqqu1uujGKjjUE9Dgbg
(cherry picked from commit 691cccc00f)
2026-09-07 19:02:18 +01:00
ayushcodes10 4a7653b609 Kill workers inside the SIGALRM handler too, before it raises
The no-SIGALRM fallback killing workers before os._exit does not
cover the primary path: on POSIX, where SIGALRM is available, a
TimeoutError raised while the main thread is waiting inside the
ProcessPoolExecutor with-block propagates straight through that
block's own __exit__, which calls shutdown(wait=True) and blocks
until every worker exits. Forever, for a worker stuck in a C-level
call the alarm firing does nothing to stop, the exact shape #3341
was. The except TimeoutError handler that would call sys.exit is
never reached, so the configured timeout bounds nothing in that case.

Reproduced directly: a worker in an unconditional loop, a SIGALRM
after 2s, and the process was still running 15s later.

Kills any live multiprocessing.active_children() inside the signal
handler itself, before it raises, so by the time the exception
reaches shutdown(wait=True) there is nothing left to wait for. Moved
the handler from an inline lambda (which cannot contain a statement,
only expressions) to a named function, matching the no-SIGALRM
fallback's own style.

Fixes #3396.

(cherry picked from commit ed948388db)
2026-09-07 18:42:57 +01:00
ayushcodes10 2226fd91b7 Kill orphaned workers before the rebuild watchdog exits
os._exit(1) terminates only the rebuild process itself, not any
ProcessPoolExecutor worker it spawned for a large corpus. It skips
every cleanup path, including the pool's own context-manager
shutdown, so a worker still running at the moment the watchdog fires
is orphaned, reparented to PID 1 on POSIX, and keeps going
unsupervised for as long as whatever it was doing takes. A worker
stuck in catastrophic regex backtracking, the exact shape #3341
fixed, was observed surviving 2.5 days that way on macOS.

extract.py already documents this risk for its own 1 worker special
case, but that only covers max_workers == 1, not a real multi worker
pool.

The watchdog fires on a separate timer thread with no reference to
the pool object, but multiprocessing.active_children() enumerates
every live worker process regardless of which thread asks, so the
fallback kills them before exiting itself. Kill, not terminate: a
worker stuck in a C level call like regex backtracking never gets a
chance to act on a signal a Python level handler would need to catch.

Fixes #3396.

(cherry picked from commit 319869e6c1)
2026-09-07 18:42:57 +01:00
ayushcodes10 462f89a3ed Let builtin named member calls through to cross file resolution
_LANGUAGE_BUILTIN_GLOBALS is one union across every language, right
for a BARE call (String(x) really would become a god node) but wrong
for a MEMBER call. open is a Python builtin and Set a JavaScript one,
so session.open() in Swift or _server.Set() in C# named after another
language's builtin was silently discarded outright: no same file
edge, but also no raw_calls entry, so cross file resolution never got
a chance to try it.

A member call carries a receiver, so it is not the ambiguous case the
union guards against. Lets a builtin named member call reach the
existing tgt_nid = None deferral every receiver typed resolver
already relies on for other cases (a capitalized Python receiver, any
Java member call, and so on), so it can only ever reach an edge
through a guarded, receiver typed resolver, never the unguarded
bare name path a real god node would need.

Verified against real cross file setups for Python (class qualified
call) and Swift (field typed receiver, reproducing the reporter's own
AppleReadyStreamFinder.find -> RemuxPlayback.open example), plus that
a same file member call still cannot bind to an unrelated bare
function sharing the builtin name.

Scoped to the shared engine only. go.py and rust.py carry the same
outer filter, and the reported issue asks for the same change there
too, but tracing where their raw_calls entries actually go shows the
shared cross file resolver skips every is_member_call entry
unconditionally (extract.py, the "obj.log() has no import evidence"
guard) regardless of builtin status, and neither language has a
dedicated receiver typed resolver the way Python, Java, C#, Swift,
TypeScript, C++, and Objective-C do. Making the same change there
would be safe but currently inert, so left out rather than shipping a
change with no verifiable effect; worth revisiting once either
language gets its own receiver typed cross file resolver.

Fixes #3381.

(cherry picked from commit c0f9ff57e0)
2026-09-07 18:42:56 +01:00
Ku Klaud 29b7a21e98 fix(serve): traverse the MCP query_graph undirected so a seed with no outgoing edges reaches its callers
`_load_graph` forces `directed: True` so renderers can recover stored arc
order (#2309), and `_bfs`/`_dfs` expand through `G.neighbors()`, which on a
DiGraph yields successors only. Seeded on a leaf that is only ever called,
imported and contained, the MCP `query_graph` therefore answered with the
seed alone, while the CLI `query` — which loads the same graph.json
undirected on purpose (#2080) — returned the callers, the test and the
neighbouring modules. Same shape as #1174: one read surface missed a fix
the others got.

Add `_traversal_view`: an undirected copy for the traversal with `_src`/
`_tgt` stashed per edge, so `_subgraph_to_text` keeps rendering
caller->callee regardless of the side the traversal reached the edge from.
An undirected input is returned as-is, so the CLI path is unchanged;
`_load_graph` is untouched because `get_neighbors` and `shortest_path`
rely on direction explicitly.

Regression tests seed the same `calls` edge from both endpoints through
`_load_graph`, in both traversal modes, with and without a context filter;
the callee-seeded ones fail on the prior code with `1 nodes found`.

(cherry picked from commit 341aec5286)
2026-09-07 18:42:56 +01:00
safishamsi 6e420a0840 test(rust): cover trait method declarations and decl/impl id distinctness (#3366)
Follow-up to #3367: guards that signature-only trait methods are captured and
that a trait-declared method stays a distinct node from its impl definition.
2026-09-06 16:31:40 +01:00
himanshupatro-334 5aef7f4081 fix: resolve unmapped @/ imports in JS projects
(cherry picked from commit b2725960c1)
2026-09-06 16:17:38 +01:00
abhay-codes07 b09c839eb3 fix(hooks): a graphify skip must not terminate the whole git hook (#2986)
The generated post-commit / post-checkout block is appended to whatever
hook a repo already has, and other tools chain their logic after it. Every
skip condition in the block was a bare `exit 0`, which in a flat sh script
ends the ENTIRE hook process — so anything after graphify's end marker
was silently dropped on every root commit (HEAD~1 does not exist), every
rebase/merge/cherry-pick, every linked worktree, every GRAPHIFY_SKIP_HOOK=1
and whenever no graphify-capable python could be found.

Both bodies now run inside a subshell `( ... )`, so an `exit` ends only
graphify's section: no rewriting of the seventeen skip sites, no
`return`-outside-a-function hazard for the _PYTHON_DETECT fragment that
tests run standalone, the detached rebuild launch unaffected, and the
hook's own exit status 0 as before. The markers stay outside the subshell
so reinstall/uninstall/status keep finding the block.

(cherry picked from commit 6f09919f10)
2026-09-06 16:17:37 +01:00
himanshupatro-334 7f87c3b08a fix(paths): bound atomic temp filename length
(cherry picked from commit 9d17b94aaf)
2026-09-06 16:17:36 +01:00
Santosh Purbey 43de793f87 fix(rust): extract trait method declarations (#3366)
A trait got a node; the methods it declares did not. Across three real Rust
repositories 504 of 654 trait methods (77%) had no node at all, so a trait — the
API contract — appeared in the graph as a bare name with no operations attached,
and "what must an implementor provide?" was unanswerable.

Two gaps, both here:

  - `function_signature_item`, the node type for a bodyless `fn greet(&self);`,
    had no branch anywhere in the package, so a signature-only method had no
    extraction path.
  - the struct/enum/trait branch returns before descending, so nothing walked a
    trait's body — a default-bodied method inside a trait was never reached
    either.

The methods that did appear came from impl blocks that happened to define the
same name, and were anchored at the impl rather than the declaration.

This adds a `function_signature_item` branch mirroring `function_item` (minus the
body walk, since there is none) and descends into the trait body the way
`impl_item` already descends into its own, attributing each method to the trait
node with a `method` edge.

Before / after on the reproducer in #3366:

    src/lonely.rs (a trait with no implementor in the corpus)
      before:  Lonely
      after:   Lonely, .only_signature() L3, .with_default() L4
               + method edges from Lonely

On a 937-file Rust service: 112 trait methods declared, 70 missing -> 0 missing;
9426 -> 9574 nodes, 28638 -> 29177 edges.

Full suite is unchanged: 17 failed / 5296 passed / 93 skipped both with and
without this commit (the 17 are pre-existing on v8, all in test_skillgen.py).

Note for anyone verifying: the AST cache is keyed on file content, not extractor
version, so `graphify-out/cache` must be removed to observe the change — `--force`
alone re-runs extraction but still serves cached per-file results.

(cherry picked from commit e9fbe22503)
2026-09-06 16:17:36 +01:00
safishamsi c9f9901877 release: 0.9.55 — leading-comment docstrings, underscore-id collisions, ghost source_file, owned type-use sources, no-cluster labels, named re-exports, entity dedup, TS runtime imports, json_config edges, claude-cli preamble, watch semantic flag, mcp stdin 2026-09-05 22:15:39 +01:00
zfaustk 6baa5e08fe fix: preserve runtime imports in TS type normalization
(cherry picked from commit ff7cb6d27a)
2026-09-05 21:55:36 +01:00
himanshupatro-334 a361228d09 fix(mcp): prevent PR subprocess stdin hangs
(cherry picked from commit 0bea7e6041)
2026-09-05 21:55:35 +01:00
Satvik Shrivas 59c76c5aff fix(watch): preserve pending semantic update flag
(cherry picked from commit 08301ccd06)
2026-09-05 21:55:35 +01:00
prav 17d9a71c5c fix(claude-cli): tolerate a diagnostic preamble before the JSON envelope
`claude -p --output-format json` shares stdout with the CLI's own
subsystems, so the envelope is not always the first thing on it. An
attached MCP server that advertises no tools makes every invocation emit

    Client.listTools() called but server does not advertise tools
    capability - returning empty list

ahead of the envelope, and `json.loads(stdout)` fails on the whole buffer.

The failure is raised after the model has already answered, so the chunk
is discarded with its tokens spent. On a real corpus this burned 149,582
input and 52,162 output tokens on chunk 1 of 3 and returned nothing, and
the error names the JSON rather than the preamble that caused it, so the
log points at the wrong thing. Anyone with an MCP server configured hits
it on every chunk.

`_envelope_after_preamble` scans for the first `[`/`{` that begins a
valid JSON document. `raw_decode` ignores trailing bytes, so a diagnostic
on either side is tolerated. The fast path is unchanged: clean stdout
still parses on the first `json.loads`, and stdout with no JSON at all
still returns None so the caller raises -- test_raises_on_garbage_envelope
holds.

(cherry picked from commit ede3a9e0a8)
2026-09-05 21:55:34 +01:00
prav 5711e9d268 fix(json_config): stop emitting self-referential dep imports and array-as-extends edges
(cherry picked from commit 33f02c936b)
2026-09-05 21:55:34 +01:00
Vasu Bansal 3993351c60 fix: preserve export cycles and legacy declaration facts
(cherry picked from commit 0a1f06be8b)
2026-09-05 21:55:33 +01:00
Vasu Bansal b961460d48 fix: resolve explicit named exports through imported bindings
(cherry picked from commit 08dd8c1fb7)
2026-09-05 21:55:33 +01:00
yotamleo 2a8b97af65 fix(dedup): say what the entity predicate proves and what it assumes (#296)
Absence of a `node_kind` stamp is not proof that a node is an entity: an
extractor can mint a node standing for part of its file without stamping one
(detect.py's per-sheet document nodes do exactly that), and the predicate read
those as entities while its name and docstring claimed proof.

Renames it `_reads_as_file_entity` and splits the docstring into what is PROVEN
(not the file's own node — an `_id_prefixes` reconstruction that holds for every
stored-path spelling) and what is ASSUMED (not a section, resting on the
producer stamping `node_kind`). Adds the producer contract next to
`_FILE_STRUCTURE_NODE_KINDS` and a test pinning the stamped/unstamped split, so
the limit is enforced rather than described.

No behaviour change: the same nodes merge as before.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit d123254ebf)
2026-09-05 21:55:33 +01:00
yotamleo 124ca10c96 fix(dedup): merge cross-file entity nodes typed by their file's extension (#296)
Per-file extraction over a note vault mints one node per mention of the same
person or project, and they never merge. Normalization is not the problem:
`_norm` already casefolds and collapses `[\W_]+`, so `@cyrilXBT`, `@cyrilxbt`
and `cyrilXBT` land in the same Pass 1 bucket. The bucket is then dropped,
because the cross-file union added in #2182 is gated to
`file_type == "concept"` — and an entity the extractor pulls out of a `.md`
note inherits `document` from the file's extension, not from anything about
the entity.

#1284's reasoning for that gate is right about files: two `README.md` in
different folders are two documents. It does not follow for a node that merely
lives in a document. This widens the Pass 1 cross-file residue to
`document`/`rationale` nodes that are provably not part of their file's own
structure, via a new `_provably_not_file_structure`:

* not the file's own node — reusing `_id_prefixes`, which already enumerates
  the ID a node standing for `source_file` would carry in every spelling a
  stored path may take;
* not one of the file's sections — `node_kind: "heading"`, and `"page"` for
  the file node the markdown extractor labels outright.

A node that cannot be checked (no ID, no provenance) answers False and stays
blocked, so the predicate can only narrow what the gate treats as
file-anchored, never widen it on a guess.

Deliberately unchanged: the entropy and provenance guards, `code` (#1205),
`image`/`paper` shared basenames, and Pass 2's fuzzy
`_crossfile_fileanchored_blocked` — so #1284's near-identical boilerplate and
#3094's repeated `## Decisions` sections stay per-file, both now covered by
tests.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit bc45e1cf8b)
2026-09-05 21:55:33 +01:00
ayushcodes10 343f76f6ec Fix Python leading-underscore method/function id collision
ids.py:make_id strips leading/trailing underscores from every name
part before normalizing, so _get_connection/get_connection (and more
broadly any name pair differing only by underscore wrapping --
x/_x/__x/__x__ dunder variants all collapse the same way) mint the
SAME node id. add_node's first-wins dedup then silently drops
whichever declaration is walked second: a public method could be
entirely absent from the graph while its private-by-convention
sibling occupied the public name, with no warning and exit 0.

Adds a Python-scoped pre-scan (_python_pre_scan_underscore_collisions)
that groups module-level functions and direct class methods by their
would-be node id, plus a resolver (_python_underscore_salted_nid) that
salts every group member except a unique public (no leading
underscore) one -- mirroring the established convention the Go
extractor already uses for its own case-only collision (#2779/#2780):
when no unique public member exists, every member is salted, so the
outcome never depends on declaration order. The public member's id
stays exactly what it would be with no colliding sibling at all, so
adding/removing a private-by-convention sibling in an incremental
rebuild re-points nothing.

Both hooks are gated on config.ts_module == "tree_sitter_python" and
live inside the shared _extract_generic engine (Python has no
dedicated extractor file, unlike Go/Rust/SQL), following the existing
precedent for per-language pre-scans already there (csharp_interface_names,
swift_protocol_names). Call-site resolution needed no changes: label_to_nid
is rebuilt from the final nodes list after the walk completes, so it
naturally picks up whichever id (salted or not) a method actually got.

9 new tests in tests/test_python_underscore_resolution.py: the exact
repro, id stability across incremental add/remove of a private
sibling, the call edge correctly binding to the salted target, the
module-level (non-method) case, the no-unique-public-member case
(both members salted), a dunder+plain collision, an unaffected
no-collision file, and scope isolation (a collision in one class must
not touch an unrelated same-named-but-non-colliding member in another
class).

Note: tests/ on the current v8 HEAD has 7 pre-existing failures
unrelated to this change (test_cli_export.py, test_cross_repo_shared_types.py,
test_extract_code_only_cli.py, test_merge_graphs_cli.py) -- confirmed via
`git stash` that they fail identically on pristine v8 without this diff.
Full suite otherwise: 5116 passed. ruff and skillgen --check clean.

Fixes #3302.

(cherry picked from commit cb8ccebab9)
2026-09-05 21:55:32 +01:00
safishamsi 24acabdf68 fix(build): correct ghost-merge issue references from #2963 to #3344
The #3345 ghost-merge fix cited #2963 (an unrelated Rust Self-keyword bug)
in its comments and test docstrings; the issue it actually resolves is #3344.
2026-09-05 21:22:13 +01:00
Vasu Bansal 9fc51bdbb6 fix(watch): preserve qualified file labels in no-cluster updates
Apply the existing file-label disambiguation pass to the raw incremental rebuild path.

(cherry picked from commit d0de610bd5)
2026-09-05 21:13:54 +01:00
Vasu Bansal 483a1d30a3 fix(resolution): require owned sources for type-use edges
(cherry picked from commit dcd9a7ee2d)
2026-09-05 21:13:54 +01:00
Lenin Herrera 677892d3f3 fix(build): ghost-merge nodes whose source_file is the referencing doc, not the referenced file
The #1145-extended ghost-merge (build_from_json) keys exclusively on
(source_file, label). When a semantic pass reads a document that only
*mentions* a real file by name (a saved graphify-out/memory/*.md query
answer, a runbook like "see App.tsx"/"backup.sh does X"), the new node
it mints gets source_file = the document being read, not the file
actually named in the prose. That wrong source_file means the key can
never match the real AST node's, so the ghost survives every rebuild.

Add a conservative label-only fallback pass reusing the existing
_is_file_node_label() predicate (already used for file-node label
disambiguation) against every AST file-self node collected in Pass 1.
Only remaps when the match is unique across the graph — 0 or 2+
candidates (e.g. two different index.ts files) are left alone, same
conservatism the existing (source_file, label) key already applies via
_loc_collisions.

Verified against a real ~4600-node project graph: 10 long-standing
ghost nodes removed across two unrelated documents (a memory query
file and an ops runbook), confirming this is a general failure mode of
the "document mentions a file by name" pattern, not a narrow edge
case. Both hyperedges that had cited the phantoms now correctly cite
only real, AST-backed nodes.

Fixes #3344

(cherry picked from commit a67e7060b0)
2026-09-05 21:13:53 +01:00
ayushcodes10 749206102d Fix module docstring extraction when a leading comment precedes it
_get_docstring's loop checked only the FIRST child of a module/class/
function body for a docstring expression_statement, then unconditionally
broke -- so a leading comment (the #! shebang essentially every
executable Python script starts with, a coding declaration, a license
header) sat in that first-child slot instead of the docstring, and the
real docstring one position later was never seen. No warning, no
partial-extraction report, exit 0 -- module rationale for an entire
class of file (any shebang-led or comment-led script) was silently
absent from the graph.

Comments are not statements: a docstring must be the first STATEMENT
in the body, so the fix skips leading `comment` children before
checking whether the first real statement is a docstring. The same
shared helper also serves class/function bodies, so a comment as the
first line of a function/class body is fixed too, not just the
module-level case.

Fixes #3312.

(cherry picked from commit 87d4cb49b7)
2026-09-05 21:13:53 +01:00
safishamsi 937e59a547 release: 0.9.54 — dup-edge collapse, unique memory-doc names, top-level hyperedge export, rationale scoring tier, atomic version/canvas writes, tomli runtime dep 2026-09-05 01:26:20 +01:00
safishamsi 782124c7a1 chore(lock): sync uv.lock for the tomli runtime dependency (#3306) 2026-09-05 01:22:56 +01:00
safishamsi a17a4bb8ab chore(readme): update Discord invite link 2026-09-05 01:19:53 +01:00
safishamsi 7841244f44 docs(manifest): describe tomli-missing path as fail-visible, not fail-loud
The ImportError from _load_toml_module is caught by extract_package_manifest's
except-block and surfaced as a per-manifest error dict, so the behavior is a
visible per-file error, not an aborting failure. Correct the docstring to match
(follow-up to #3306).
2026-09-05 01:19:53 +01:00
dr mike d424a7ccfa fix(manifest): require tomli on Py3.10 and fail loud when missing
Declare tomli with an environment marker and raise ImportError instead of returning None, so missing parsers no longer look like empty manifests.

Fixes #3283

(cherry picked from commit c06ba2731c)
2026-09-05 01:19:09 +01:00
dr mike 74e1424a84 fix(export): write graph.canvas and Obsidian notes atomically
Route to_canvas and _owned_write through paths.write_*_atomic so concurrent readers (e.g. git hashing) never see a truncated file.

Fixes #3282

(cherry picked from commit 39564e4eef)
2026-09-05 01:18:59 +01:00
dr mike c488c0e07d fix(install): write .graphify_version atomically via os.replace
Match the SKILL.md / references/ crash-safety pattern so an interrupted install cannot leave a truncated stamp, and replace managed symlinks instead of writing through them.

Fixes #3286

(cherry picked from commit 030c6372d1)
2026-09-05 01:18:59 +01:00
Andy Tsai 6377f1609d fix(query): score the rationale attribute as its own tier (#2293)
The extraction spec stores the WHY of a concept as a `rationale` attribute
on the node — deliberately not as a node of its own. `_score_query` matched
a question against `norm_label`, `label_tokens`, `source_file` and the node
id only, and `_node_search_text` indexed the same fields, so for a "why does
X …" question the node holding the answer was neither a trigram candidate
nor a seed unless the asker already knew its label (#2293: 0/5 answers
reached on a 5.5k-node corpus although every answer node existed and stated
the answer in its rationale).

Add a rationale tier, following the fix the issue proposes:

- `_RATIONALE_MATCH_BONUS = 0.75`: below the label substring tier (1.0),
  above the source-path tier (0.5). A term found in the rationale adds to
  the score and to the per-term singleton used for seed seating, but — like
  the source tier — never to term coverage, so a long rationale adds recall
  without winning back an exact-label tier it did not earn.
- `_node_rationale_text`: one normalizer (diacritics folded, lower-cased),
  tolerant of the list an extractor may emit; "" when absent.
- `_node_search_text` appends the same text as a trailing field, only when
  present, so the trigram prefilter stays a complete candidate generator and
  every existing field position (#2467) is unchanged.

Nodes without a rationale score exactly as before.

Design credit: @nuboxworld-byte (issue #2293 and #2294). #2294 implements
the same idea but its diff carries the whole repository (+252k lines, 766
files) from a base mismatch and cannot be reviewed or merged as-is; this is
a fresh minimal implementation against v8.

Tests: rationale-only match ranks; tier order label-substring > rationale >
source; no coverage credit; list-valued attribute; search text carries the
field (and is unchanged without it); end to end a "why" question phrased
from the rationale seats the node as a seed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit 95ff41101a)
2026-09-05 01:18:59 +01:00
yiheng-kkk f69dca3c6c fix: prefer top-level hyperedges in export
(cherry picked from commit 5faf7a774c)
2026-09-05 01:18:59 +01:00
daichiyasunami-vottia 2f743aea89 fix(ingest): make memory-doc filenames unique so concurrent saves do not overwrite
save_query_result named files query_<second>_<slug50>.md and wrote them with
write_text, so two saves in the same second whose questions share the first
50 characters resolved to one path and the later one silently replaced the
earlier. Both calls returned normally. This is the common case when several
agents sweep one subsystem in parallel.

Add a short uuid to the name. The query_ prefix and .md suffix are unchanged
so reflect.load_memory_docs and existing tests keep working.

Fixes #3301

(cherry picked from commit 0bdf89f64b)
2026-09-05 01:18:59 +01:00
abhay-codes07 42248aea4d fix(extract): collapse byte-identical duplicate edges at emission (#3251)
(cherry picked from commit f18b86ba61)
2026-09-05 01:18:59 +01:00
safishamsi 18e63909b8 docs(changelog): open 0.9.54 with the python-stubs/cross-repo-calls/definition_file/god-nodes batch 2026-09-02 16:10:31 +01:00
xiongjianxu c604f489cd feat(merge): finish member calls across a repo boundary (#3152)
When a member call's receiver type resolves to zero in-corpus declarations, park
{callee, receiver_type, lang, line} (names only, #3150-safe) on the caller; a merge-time pass
emits one calls/cross_repo/INFERRED edge only when the receiver type resolves to exactly one
declaration in another repo owning exactly one matching member (language-suffix matched,
non-sourceless). Strong-signal, single-definition guarded, edges-only — composes with the
#3007 cross-repo type link and the #3068 community offset. Wired for Java/C++/C#/Swift.
2026-09-02 14:58:01 +01:00
abhay-codes07 6f9b79ae87 fix(analyze): god_nodes honours exclude_hubs_percentile (#3205)
god_nodes had no exclusion parameter, so --exclude-hubs only reached cluster() and god-node
ranking ignored it. Apply the same percentile threshold cluster() uses (byte-identical
formula), thread it through the build/analyze/MCP paths; the default (no exclusion) output is
unchanged and the node dict shape is preserved for wiki/report consumers.
2026-09-02 14:49:03 +01:00
hopstreax b2825e05a5 fix: resolve Python type reference stubs across imports (#3252)
A Python type reference to a name imported from another module dangled or mis-resolved.
Run Python cross-file import resolution before the generic stub rewire and repoint sourceless
AST reference/inherits/implements edges onto the exact imported definition using the
file-scoped (module, symbol) -> node_id binding (not a bare-name match), so two same-named
types in different modules bind to their own; orphaned stubs are pruned only when no edge
still touches them.
2026-09-02 13:31:24 +01:00
hopstreax 02957036b2 fix: normalize definition_file on the watch and direct-extract paths (#3223)
Companion to #3243: extend definition_file portability to the paths build_from_json does not
cover — the watch/incremental relativize + cache-root rebase and the direct extract() return
normalization — via a shared _PORTABLE_PATH_KEYS list so source_file and definition_file stay
in lockstep. Together with #3243 this closes all four persistence paths (graph.json, AST
cache, watch, direct extract).
2026-09-02 04:00:08 +01:00
abhay-codes07 3e5944b0c7 fix(build): make definition_file portable, like its sibling source_file (#3223)
#2990 stamped definition_file with the still-absolute implementation path, so graph.json
shipped the build host's absolute path beside a repo-relative source_file (and the AST cache
replayed it on every warm rebuild). Normalize definition_file through the same
_norm_source_file path as source_file in build_from_json and the cache round-trip, so it is
relative/portable and byte-stable across machines.
2026-09-02 03:05:59 +01:00
safishamsiandClaude Opus 4.8 33362d9692 chore: bump to 0.9.53
Ships two batches: the robot/defang/watch/semantic-guard set — Robot Framework extractor
(#3192), generalized control-token defang (#3183), watch unresolved-link preservation
(#3190), unverified-semantic-loss guard (#3203), hook-guard search detection (#3121),
stale-SKILL.md backup (#3144), report/wiki count fixes (#3148/#3127); and a rescued batch of
@Synvoya cross-language inheritance-edge corrections (JS #1790, PHP #1791, Scala #1792/#1794,
Kotlin #1793, C# #1817, Go #1818) that had been buried in the backlog for ~7 weeks.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-30 16:01:33 +01:00
safishamsi e7a22eee92 docs(changelog): add the @Synvoya cross-language heritage-edge batch to 0.9.53 2026-08-30 15:54:38 +01:00
Synvoya 588dc041f7 fix(go): don't emit embeds for interface type-set constraints (#1818) 2026-08-30 15:53:16 +01:00
Synvoya 9aeade7199 fix(csharp): classify an interface base as inherits, not implements (#1817) 2026-08-30 15:53:16 +01:00
Synvoya c361189046 fix(kotlin): resolve a qualified supertype to its tail type name (#1793)
A qualified Kotlin supertype (`class Foo : com.example.Base()`) resolved to the first
identifier (`com`), collapsing distinct bases onto a bogus node. Take the last segment of the
user type (handling generics like `Container<String>` -> `Container`), so the edge targets
the real base; simple and delegated supertypes are unaffected.
2026-08-30 15:52:38 +01:00
Synvoya bf385a5052 fix(scala): normalize qualified heritage names to the tail type (#1794)
A qualified Scala base (`extends pkg.Base with other.Trait`) parses as a
stable_type_identifier (or generic_type wrapping one), which the heritage handler did not
match, so the edge was dropped or targeted the full qualified string. Add a helper that
takes the tail type name across all three shapes, emitting inherits for the first parent and
mixes_in for the rest, with no package/generic-arg false edges.
2026-08-30 15:52:04 +01:00
Synvoya 5a8a84d7ac fix(scala): capture trait declarations as class-like nodes (#1792) 2026-08-30 15:51:26 +01:00
Synvoya 88f53962dc fix(php): capture interface/enum/trait heritage as class-like nodes (#1791)
Only class_declaration was treated as a class type, so PHP interfaces, enums, and traits
produced no node and no heritage edges. Add them as class-like containers (and walk the
enum body) so their extends/implements/use heritage is captured as inherits/implements/
mixes_in edges to the right targets.
2026-08-30 15:50:48 +01:00
Synvoya 6b2dfa0bf2 fix(extract): emit inherits edge for JavaScript class extends (#1790)
A plain JavaScript `class Dog extends Animal` produced no inherits edge — only the
TypeScript extends_clause/implements_clause shapes were handled, not the bare identifier
directly under class_heritage that JS emits. Fall back to reading heritage identifiers when
no clause is present, so JS class inheritance is captured; a dynamic base (mixin call) yields
nothing and TS is not double-emitted.
2026-08-30 15:48:40 +01:00
safishamsi b27f219392 chore(lock): sync uv.lock for the robot extra (#3192) 2026-08-30 15:43:58 +01:00
safishamsi 96604ecc78 docs(changelog): open 0.9.53 with the robot/defang/watch/semantic-guard/hooks batch 2026-08-30 15:17:38 +01:00
safishamsi 43e63b1c3f fix(robot): namespace the external-library stub id to avoid keyword collision (#3192)
A user keyword named like an imported library (e.g. a keyword 'SeleniumLibrary') would mint
the same id as the library stub. Namespace the stub id under robot_library so the two cannot
collide; the display label keeps the raw library name.
2026-08-30 15:16:49 +01:00
nshiveg 832256f824 feat: Robot Framework extractor for .robot/.resource files (#3192)
Add a Robot Framework extractor using the official robot.api parser (pure-Python, optional
[robot] extra), emitting suite/test/keyword nodes plus keyword-call, resource-import, and
library edges. Keyword resolution is case/space/underscore-insensitive (RF's real semantics)
and handles BDD prefixes and ${CURDIR}/${EXECDIR} path resolution; degrades to an actionable
error when robotframework is absent.
2026-08-30 15:14:33 +01:00
safishamsi 6271740856 refactor(cli): factor the duplicated unverified-semantic-shrink block into one helper (#3203)
The raw and clustered write paths carried a byte-identical ~27-line block differing only in
whether the flag is read from merged or G.graph. Extract _handle_unverified_semantic_shrink
so the two paths cannot drift; behavior-identical (the #3203 and prune-sweep suites pass).
2026-08-30 15:14:16 +01:00
hopstreax 064957b398 fix: protect against unverified semantic node loss (#3203)
On the default incremental path a semantic chunk that returned successfully but under-produced
(prior semantic count > 1, fresh < prior) bypassed every guard, silently shrinking the graph.
Flag that per-source shrink (computed only from fresh nodes, so a genuinely deleted file is
never flagged) and route it through the existing shrink-guard refusal + manifest un-stamp so
the source re-extracts next run; --allow-partial overrides. Does not touch the prune path.
2026-08-30 15:12:10 +01:00
logan683 788c04e6c6 fix(watch): preserve unresolved authored reference edges (#3190)
Follow-up to #3191: an authored markdown link whose target basename is present in the graph
but under a different spelling (e.g. Windows-case [[target]] vs TARGET.md) was dropped on a
code-only rebuild. Preserve such an edge when its target node is still live in the merged
graph, without loosening the deleted-target existence gate (a genuinely deleted target's node
is evicted first, so it is never preserved).
2026-08-30 15:11:50 +01:00
abhay-codes07 4d8cb4c803 fix(install): actionable stale-skill warning; back up a diverged SKILL.md (#3144)
When the installed SKILL.md has diverged (user edit or old version), back it up beside the
install target before the atomic overwrite and print an actionable warning naming the stale
path and the exact reinstall command; a clean up-to-date reinstall backs up nothing (no
churn), and only the installed copy is touched, never the generated sources.
2026-08-30 15:11:40 +01:00
abhay-codes07 3993f023f7 fix(cli): hook-guard search detection matches executed commands, not prose (#3121)
The hook-guard matched a search command appearing anywhere in the intercepted Bash string
(a comment, a quoted -m message, an echo), firing false nudges. Match only an executed
command position (start-of-segment after a shell operator, wrapper-aware), so prose lookalikes
stay quiet while genuine pipes/&&/;/$() invocations still fire.
2026-08-30 15:11:40 +01:00
abhay-codes07 50d092db94 fix(llm): defang any <|token|> chat-template marker, not an enumerated few (#3183)
Only a handful of control tokens were defanged, so an attacker-chosen token outside the set
(e.g. Llama-3 <|eot_id|>) could still reach the prompt. Generalize the neutraliser to match
the control-token form (<|...|> and [/?INST|SYSTEM]) at the single _wrap_untrusted chokepoint;
the bounded charset leaves legitimate content (|| , markdown tables, generics) untouched.
2026-08-30 15:11:24 +01:00
abhay-codes07 fce26fc9b4 fix(report): make the report's headline numbers agree with themselves (#3148)
The GRAPH_REPORT headline figures disagreed: shown-community count included empty communities
the render loop skips, and the knowledge-gaps thin count used a hardcoded 3 beside a label
printing min_community_size. Drive every figure from one _real_count predicate so the counts
reconcile with what is actually rendered.
2026-08-30 15:11:24 +01:00
abhay-codes07 97e4275c09 fix(wiki): say when a god-node relation group was truncated (#3127)
A god-node relation group capped at 20 targets showed no indication it was truncated; append
a '…and N more' line (exact count, degree-sorted so the lowest-degree are dropped) only when
the group actually exceeds the cap.
2026-08-30 15:11:23 +01:00
safishamsiandClaude Opus 4.8 680e3ed8ed chore: bump to 0.9.52
Ships three batches: php new Foo() calls (#3115), inherited-field receivers (#3151), objc
field-table remap (#3150), ts type-only-import cycles (#3123) and import-type args (#3185);
razor @inject cross-file (partial #3187), MCP prs isError + get_node resolver parity,
project-scoped bare hook command (#3129); and T-SQL routine recovery (#3164), watch
markdown->semantic reconcile (#3190), --help completeness, and a deepseek pricing fix. The
#3155 provenance backfill was reverted (regressed the orphan prune).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-29 19:38:37 +01:00
safishamsi cbd9d910b6 docs(changelog): add 0.9.52 entries for the watch-reconcile/tsql/cli-help/pricing batch 2026-08-29 19:36:11 +01:00
safishamsi c24765a884 test(watch): pin that markdown reconcile does not resurrect a deleted target (#3190)
The reconcile relies on the extractor only stamping target_file when the link target exists
on disk. Add a negative test: link text intact but the target file deleted must leave no
reference edge and no edge pointing at the deleted document's node.
2026-08-29 19:35:41 +01:00
logan683 0a4c5e8fe3 fix(watch): reconcile markdown links to semantic-backed documents (#3190)
A code-only watch/update rebuild never re-creates a semantic-backed document node, so an
authored [[wikilink]] to such a doc resolved to a missing canonical id and reconcile
silently dropped the edge. Re-parse each markdown source and repoint authored references
edges onto a unique representative node for the target file (canonical id, else unique page
node, else unique document node; ambiguous -> keep the existing edge), preserving links to
the semantic tier across a code-only rebuild without resurrecting a deleted target.
2026-08-29 19:34:31 +01:00
kerzhaev f7e79048b9 docs(hooks): explain why the detached launcher uses CREATE_NO_WINDOW (Win11 focus-steal)
Add a comment warning against reverting the Windows detached spawn to DETACHED_PROCESS:
DETACHED_PROCESS lets the child allocate its own console, which Windows 11 + Windows
Terminal render as a visible focus-stealing window, so CREATE_NO_WINDOW is required.
2026-08-29 19:34:17 +01:00
adrianengkh b40cb53f8e fix(llm): correct deepseek-v4-flash pricing and the build_merge docstring
Update the deepseek-v4-flash per-1M-token pricing (same units/ordering as neighboring
models) and fix the build_merge docstring, which claimed it saved the graph back to disk;
build_merge only reads the existing graph and returns the merged result — callers persist.
2026-08-29 19:33:37 +01:00
SyedFahad7 aa5fef0c09 fix(cli): list prs, provider, and export formats in --help
graphify --help omitted the real prs and provider commands and the export format list. Add
them (verbatim from the dispatcher's own usage text), so every listed command/format exists
and the export formats match the supported allow-list.
2026-08-29 19:32:51 +01:00
egarcia74 8b3f1911b2 fix(sql): recover T-SQL bracket-named, CREATE OR ALTER, and PROC routines (#3164)
T-SQL routine idioms (CREATE OR ALTER, the PROC shorthand, bracket-delimited names like
[dbo].[Get Widgets]) parse to tree-sitter ERROR nodes, so the routine names were lost. Hoist
a single routine-recovery pattern covering all three forms and run it over a
comment/string-masked copy of the file so commented-out or dynamic-SQL DDL cannot fabricate
nodes; labels keep the raw bracketed text and plain CREATE PROCEDURE/FUNCTION is unchanged.
2026-08-29 19:32:44 +01:00
safishamsi b88e1640ca Revert "fix(extract): retain provenance for legacy and data nodes"
This reverts #3155 (b568488): the source_file backfill also fired on a shared external stub
(e.g. a cross-file `Path` reference with no source_file), giving the stub a file identity so
the orphan prune swept it when that one file was deleted even though another file still
referenced it — regressing test_prune_sweeps_orphans. The fix needs to distinguish a
legacy node that genuinely lost its provenance from an external stub that must stay
sourceless; sending #3155 back as needs-work.
2026-08-29 18:42:15 +01:00
safishamsi 753b5b7201 docs(changelog): add 0.9.52 entries for the razor/mcp-prs/get_node/install/provenance batch 2026-08-29 18:39:37 +01:00
hopstreax 663024253f fix(razor): resolve @inject types across files (#3187)
Wire Razor .razor/.cshtml @inject/@using through the existing scope-aware C# type resolver
instead of a bespoke path: @inject emits a references edge to a sourceless stub, @using
feeds scoping, and the type-resolution + stub-rewire passes now accept Razor sources. A
cross-file injected type resolves to its real definition; an external/undeclared type
fabricates nothing and a qualified inject does not mis-bind a same-named type.

Partially addresses #3187: a bare @inject of a type in a file-scoped namespace still dangles
(same as a bare C# cross-namespace reference without a using), and implicit _Imports.razor
global usings are not yet modeled — left as follow-up, so this does not auto-close the issue.
2026-08-29 18:38:33 +01:00
noQbot 72edfc0e10 Route get_node through the same resolver as get_neighbors
get_node used a raw substring scan and returned an iteration-order match, so it could miss
or mis-pick a node that get_neighbors resolves. Extract the shared tiered resolver
(_resolve_single_node) and route get_node through it — deterministic tiered winner or an
explicit ambiguity report, matching get_neighbors byte-for-byte; get_neighbors behavior and
return shapes are unchanged.
2026-08-29 18:38:05 +01:00
noQbot 09151a6727 Mark failed PR tool calls as isError instead of successful text
The prs MCP tools (list_prs, triage_prs, get_pr_impact) returned genuine failures (gh
missing/unauth, unresolved PR) as success text. Raise a ToolError propagated as isError on
both the 1.x and 2.x SDK paths, so a client sees the failure; an empty-but-successful result
(0 PRs, PR with no changed files) is unaffected. Mirrors the #2725 MCP-error pattern.
2026-08-29 18:37:06 +01:00
davidbhoward 35c63493e5 fix(install): emit a bare hook command for project-scoped installs (#3129)
A --project (committed/shared) install pinned the absolute interpreter path into the hook
command, so the committed hook churned across machines. Emit a bare `graphify <sub>` command
for project installs (resolved at hook-run time via the PATH/pin/uv-tool probes), while the
global install still emits the absolute path (preserving the Windows VS Code Codex case).
Uninstall still strips the bare command.
2026-08-29 18:36:56 +01:00
GmailTedam b568488cb4 fix(extract): retain provenance for legacy and data nodes
A sourceless legacy node now backfills its source_file from incident-edge provenance (only
when real edge evidence exists, deterministic min, never fabricated), and a declined data
JSON now emits a single file-identity node carrying source_file instead of nothing, so
freshness/affected checks can see the file. No node is resurrected and config JSON does not
double-add its file node.
2026-08-29 18:36:49 +01:00
safishamsi fac6f44a09 docs(changelog): open 0.9.52 with the php-new/inherited-fields/objc-remap/ts-import-type batch 2026-08-29 16:31:17 +01:00
hopstreax c60a564d1a fix(ts): normalize import types in call type arguments (#3185)
An `import(...)` used as a call type-argument (f<typeof import('mod')>()) could make the
parser drop declarations that follow it. Rewrite the import-type to a byte-length- and
newline-preserving placeholder before parsing so trailing declarations survive with exact
source locations; the dynamic-import edge is still recovered by re-reading the original
file. On the pinned tree-sitter-typescript (0.23.2) only the multiline form regresses today;
the single-line/member/TSX tests guard against regressions on future grammar bumps.
2026-08-29 16:19:48 +01:00
abhay-codes07 b84b4a7316 fix(ts): type-only imports no longer manufacture Import Cycles (#3123)
A type-only import (import type { T } from './m') produced an import edge like a value
import, so type-only round-trips showed up as false import cycles. Stamp type_only on the
module and symbol edges from type-only statements (correctly not firing for a mixed
import { type A, B }, which keeps its value edge) and exclude stamped edges from
find_import_cycles, mirroring the existing deferred-import exclusion.
2026-08-29 16:16:09 +01:00
safishamsi 8906834ff0 test(php): escape namespace backslashes in object-creation fixtures (#3115)
The fixtures embedded PHP namespace paths (\App\Bar, App\Command) as plain strings, so
\A / \C were invalid escape sequences (SyntaxWarning now, SyntaxError in a future Python).
Double the namespace backslashes; the \n newlines are unchanged.
2026-08-29 16:15:58 +01:00
abhay-codes07 f57af70f77 fix(php): emit a calls edge for object creation, new Foo(...) (#3115)
A PHP `new Foo()` emitted no edge. Add object_creation_expression to the PHP call types and
emit a calls edge to the constructed class (namespaced names resolve to the last segment),
consistent with the C# (#2998) and TypeScript (#3135) object-creation handling. Dynamic
(new $var()), self/static/parent, and unknown external constructions fabricate nothing.
2026-08-29 16:15:01 +01:00
abhay-codes07 b5162dc2e5 fix(engine): resolve fields declared on a superclass for receivers in a subclass (#3151)
A method call through a field whose type is declared on an ancestor class, used from a
subclass, did not resolve (the field-type table only held the class's own fields). Walk the
inheritance chain (per-file for Java/C#, cross-file for Java/ObjC) to type the receiver,
BFS with a seen-set so an inheritance cycle terminates. Target selection is unchanged (the
single-definition guards stand), so this only widens receiver typing and never fabricates
an edge; this.-only, and the binder refuses to guess on ambiguity.
2026-08-29 16:14:47 +01:00
abhay-codes07 208d0c1dcc fix(objc): remap the field->type table keys with the ids they hold (#3150)
The Objective-C field->type table is keyed by class node id, but the id-carrier rewrites
(prefix strip, symbol canonicalisation, cache portability round-trip) never remapped those
keys, so after graphify update the keys went stale and every self.field / obj.field method
call missed resolution. Remap the table keys alongside the existing id remaps (in-process
and in the cache round-trip); a dropped key can only cost a missed edge, never a phantom.
2026-08-29 16:14:29 +01:00
safishamsiandClaude Opus 4.8 281ccaa4ff chore: bump to 0.9.51
Ships three batches: the leiden-direct perf win (#3104) and git-workflow docs; TS new_expression
constructor calls (#3116), elixir when-guard-only clauses (#3111), commonlisp path-qualified
ids, and the FalkorDB wrong-service test skip; and the correctness set — shrink guard armed on
hollow/unparseable/omitting chunks (#3105), --force --code-only full rescan (#3125), carried
hyperedge survivor remap (#3102), atexit stat-index no-resurrect (#2974), and Leiden
edge-endpoint determinism.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-28 01:25:56 +01:00
safishamsi 982a09f9eb docs(changelog): add 0.9.51 entries for the shrink-guard/force-rescan/hyperedge/cache/cluster batch 2026-08-28 01:22:32 +01:00
hopstreax ae074b2122 fix(extract): rescan code with --force --code-only (#3125)
--force --code-only over an existing graph set incremental_mode, so unchanged code files
were skipped and stale alias/import resolution persisted. Separate scan-mode from
graph-merge: --force --code-only now full-scans all code (via a new merge_existing_graph
gate) while still carrying the existing semantic tier forward (preserving the #2923 fix) and
still pruning deleted/excluded files. Other flag combinations are unchanged.
2026-08-28 01:20:57 +01:00
abhay-codes07 a8852e8740 fix(extract): hollow, unparseable and omitting chunks count as incomplete (#3105)
The #479 shrink guard is disarmed when a build is known-incomplete, but a run that silently
lost content to a hollow, unparseable, or file-omitting chunk was treated as complete, so it
could overwrite the existing graph with a smaller one. Mark those cases incomplete (uncovered
files or partial-semantic files) so the guard stays armed and refuses the shrink; a complete
run is untouched, a #2880-retry-recovered chunk does not count, and --allow-partial still
overrides.
2026-08-28 01:20:27 +01:00
abhay-codes07 3378ae8fef fix(build): route carried hyperedges through the dedup survivor remap (#3102)
A hyperedge carried from a prior graph.json kept its original member ids, so when dedup
merged one of those members away the hyperedge dangled. Feed carried hyperedges into build()
on the base chunk so deduplicate_entities remaps their members onto the survivor at the same
time as edge endpoints; a member that resolves to nothing is dropped (the whole hyperedge if
none survive), and a hyperedge re-emitted by a new chunk is not duplicated. Materialise
new_chunks so the added second iteration is safe.
2026-08-28 01:20:10 +01:00
safishamsi bad832f225 test(cluster): pin partition invariance to edge-endpoint orientation (#3146)
Build the same logical undirected graph with forward vs flipped edge endpoints and shuffled
node insertion, and assert _partition yields identical communities — guarding the canonical
edge-ordering the determinism fix introduced.
2026-08-28 01:19:45 +01:00
ErichKinuya 27096817ed fix(cluster): canonicalise edge endpoints before sorting in _partition
For an undirected graph, (a,b) and (b,a) are the same edge but networkx may yield the
endpoints in either order depending on insertion order / version / hashseed, so the edge
sort was keyed on a non-canonical orientation and the ordering fed to Leiden could vary
across builds/machines, drifting community assignments. Sort each endpoint pair to (min,max)
before the sort so the edge order is canonical; the edge set and weights are unchanged.
2026-08-28 01:18:46 +01:00
abhay-codes07 c60ddf7b3e fix(cache): the atexit stat-index flush must not resurrect a deleted corpus (#2974)
The atexit stat-index flush did an unconditional mkdir(parents=True) on the cache path, so
if the corpus/output tree was deleted during the run the flush recreated the whole
graphify-out/cache/ chain as a husk. Skip the write when the index root no longer exists
(clearing the dirty flag so nothing retries); a live run still writes, and a cold start is
unaffected because the root exists before graphify-out/ does.
2026-08-28 01:18:04 +01:00
safishamsi 384e71e008 docs(changelog): add 0.9.51 entries for the ts-new/elixir-guard/commonlisp-id/falkordb-test batch 2026-08-27 21:17:11 +01:00
hopstreax 590258fe1b fix(ts): resolve new_expression constructor calls (#3116)
A TypeScript/JavaScript `new Foo()` emitted no edge. Fall back to the new_expression's
constructor child in the generic callee branch, so it emits a calls edge to the constructed
class (member, chained, and generic forms), reusing the existing built-in-global guard so
new Map()/new Promise() are not fabricated. Consistent with the C# object-creation handling
(#2997).
2026-08-27 20:57:16 +01:00
santhiprakash c66465c77e fix(elixir): extract functions whose only clause has a when guard (#3111)
A guarded function head (def foo(x) when is_integer(x), do: ...) nests the head call under a
binary_operator, so a def whose only clause carries a guard was not extracted. Unwrap the
guard to the head call (the head is always the first child, so the guard predicate is never
selected) and emit the real function name; multi-clause, multi-condition guards, and defp
are handled.
2026-08-27 20:56:15 +01:00
guitelesc e906227cf6 fix(commonlisp): derive node ids from the full path stem
The Common Lisp extractor minted its id prefix from the bare path.stem instead of the
canonical _file_stem used by every other extractor, so two same-basename .lisp files in
different directories collided (one file's nodes vanished on merge) and nested .lisp files
tripped a spurious legacy-id nudge. Use _make_id(_file_stem(path)) to match the shared
convention; cross-file rewire is unaffected (it matches on label, not id).
2026-08-27 20:20:36 +01:00
guitelesc 8d611dc4d0 test(falkordb): skip when the port answers but is not FalkorDB
The integration test guarded only on ping(), so a plain Redis (or an SSH-forwarded one) on
6379 passed the liveness check and then FAILED both tests on 'unknown command GRAPH.QUERY'.
Add a read-only GRAPH.LIST probe that identifies the service and skips with a distinct
message when the graph module is absent, so the test still runs (and can fail) against a
real FalkorDB but no longer breaks on a wrong service.
2026-08-27 20:20:16 +01:00
safishamsi 3af5021e79 docs(changelog): open 0.9.51 with the leiden-perf + git-workflow-docs batch 2026-08-27 18:33:29 +01:00
safishamsi a6e2a6827d docs(readme): tighten the git-workflow rebuild claims (#3112)
Two accuracy corrections to the Recommended workflow table: the post-checkout hook rebuilds
only on branch switches (not a file-only git checkout -- <path>), and the commit/switch
rebuilds run detached in the background so the graph can briefly lag the commit.
2026-08-27 18:32:51 +01:00
Mohammad-Palla df2f99b33e docs(readme): add explicit git-workflow guidance for keeping the graph in sync
Add a Recommended workflow section documenting that commits and branch switches rebuild the
graph automatically via the installed hooks, while a git pull/merge needs a manual
graphify update . (no pull hook exists), with a pull-alias shortcut and a troubleshooting
entry for a stale graph.
2026-08-27 18:03:28 +01:00
safishamsi 996c6add76 test(cluster): pin native-leiden vs wrapper equivalence and absent-binding fallback (#3104)
Guard the output-equivalence claim the perf change rests on: _partition via the direct
graspologic_native path must produce the same node groupings as the graspologic wrapper
(skipped unless both are installed), and _native_leiden must return None when the native
binding cannot be imported so the wrapper/Louvain fallback still runs.
2026-08-27 18:03:10 +01:00
Mohammad-Palla a9894ebb7f perf(cluster): call graspologic_native.leiden() directly, skip graspologic's import chain
The Leiden path imported graspologic, which drags in a heavy chain (umap / pynndescent /
numba JIT) at import time. Call the underlying graspologic_native.leiden() binding directly
with the same arguments the wrapper uses (seed 42, randomness 0.001, modularity, unit edge
weights), falling back to the graspologic wrapper and then NetworkX Louvain when the native
binding is absent. Clustering output is unchanged.
2026-08-27 18:01:13 +01:00
safishamsiandClaude Opus 4.8 43d54acbfa chore: bump to 0.9.50
Ships two batches: the detect ignore-perf rewrite (#2226) with the globstar cycle fix and
bounded pattern cache; C#/TypeScript enum-member nodes (#3063/#3064); watch read-only
inotify filtering; the postgres tree-sitter-sql extra; Ruby suffixed-method-id preservation
(#3077) and qualified-receiver matching (#3078); HOF-wrapped CommonJS export capture
(#3035); per-input community-id offset in merge-graphs (#3014); and the Windows PowerShell
BOM fix across all .graphify_root readers (#3028).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-25 18:24:12 +01:00
safishamsi b963858e83 docs(changelog): add 0.9.50 entries for the ruby/HOF-export/merge/windows-BOM batch 2026-08-25 18:12:26 +01:00
rohit-jsfreaky 984ff116d3 fix(ruby): match a qualified receiver by its constant path (#3078)
A call on a qualified constant receiver (ActiveRecord::Base.transaction) truncated the
receiver to its last segment (Base) and bound to any lone corpus class named Base, a false
EXTRACTED edge. Keep the full constant path and suffix-match it against declared classes,
emitting an edge only on a single unambiguous hit; a leading :: pins a whole-path match.
Bare receivers are unchanged.
2026-08-25 18:12:02 +01:00
hopstreax b48005276e fix(ruby): preserve suffixed method node IDs (#3077)
normalize_id strips !/?/= from Ruby method names, so save and save! (or foo and foo=) minted
the same node id and the second was dropped as a seen_ids collision. Add a Ruby symbol
sanitizer (!->_bang, ?->_pred, =->_eq) applied to the id only (the label keeps the raw
spelling), and rekey method_index on the raw name so member-call resolution still matches.
Ids stay stable across incremental re-extraction.
2026-08-25 18:10:43 +01:00
safishamsi ef00185bb2 test(merge): pin same-order community-offset byte-reproducibility (#3014)
Document that the per-input community-id offset is deterministic for a fixed input order
(consumers rely on stable merged output), while noting the offsets are position-dependent
by design.
2026-08-25 18:09:58 +01:00
santhiprakash 4e2e23278a fix(build): offset community ids per input in merge-graphs (#3014)
merge-graphs kept each input's community ids as-is, so community 0 from repo A and community
0 from repo B fused into one meta-community spanning unrelated repos. Offset each input's
community ids past the running maximum so every input's communities stay globally distinct
after merge, preserving within-input structure and recording the original id in
local_community.
2026-08-25 18:09:25 +01:00
hopstreax ad7c7d58d1 fix: capture HOF-wrapped CommonJS exports (#3035)
A CommonJS export wrapped in a higher-order function (exports.x = wrap(fn),
module.exports.y = onCall({...}, handler)) was not captured, so the exported symbol was
missing. Reach through the wrapping call to the topmost function closure argument (mirroring
the const-export HOF path #2552/#2568); the wrapper stays a call edge, not the export's
identity, and a non-function arg fabricates nothing.
2026-08-25 18:07:55 +01:00
safishamsi 5cb6532c24 fix(windows): read .graphify_root BOM-tolerantly in the update-recovery path too (#3028)
Complete the read-side BOM fix: the graphify update (no-args) recovery path at cli.py read
.graphify_root with plain utf-8, so a PowerShell-written BOM would fail the exists() check
and abort with path not found. Switch it to utf-8-sig like the other five reader sites.
Also clean up two invalid-escape f-strings in the windows skillgen test.
2026-08-25 18:07:40 +01:00
rohit-jsfreaky 3c448660cd fix(windows): stop a PowerShell BOM breaking hook rebuilds (#3028)
Windows PowerShell 5.1 writes a UTF-8 BOM, so the .graphify_root marker it produced carried
a leading BOM that Python's utf-8 decode kept as U+FEFF; .strip() left it in, breaking the
post-commit rebuild (WinError 123) and silently mis-rooting _infer_merge_root. Write the
marker BOM-less from PowerShell (WriteAllText + UTF8Encoding $false) and read the marker
with utf-8-sig at the reader sites so already-broken installs recover too.
2026-08-25 18:06:46 +01:00
safishamsi 5687fe1bcc docs(changelog): open 0.9.50 with the detect-perf + enum-member + watch/postgres batch 2026-08-25 15:52:49 +01:00
safishamsi d8abe52415 perf(detect): kill the globstar matcher's per-call cycle, bound the pattern cache (#2226)
Senior tweaks on the landed #3074:
- Lift the **-aware matcher out of the per-call @lru_cache closure (which referenced itself
  and leaked a reference cycle every call) into a module-level function with an explicit
  dict memo, plus a no-** fast path; port of the fix from the alternative #2845.
- Cap the process-global parsed-pattern cache so a long-lived watch across many repos cannot
  grow it without bound.
- Add a differential test pinning _lexical_relative against pathlib relative_to, and a
  gc test asserting the matcher leaves no cyclic garbage.
2026-08-25 15:52:10 +01:00
safishamsi f725eec172 chore(lock): sync uv.lock for the postgres tree-sitter-sql extra (#3072) 2026-08-25 15:46:44 +01:00
Azeem1985 258ab11db2 perf(detect): stop building pathlib objects per pattern per file in ignore evaluation (#2226)
Ignore evaluation built a Path and called relative_to (with its CPython quadratic parents
cost) per pattern per file, and re-parsed each pattern's flags every call. Replace it with a
lexical string-space relative computation (no Path construction, no exception control flow),
parse each pattern once into a process-wide cache, and memoize per-anchor relatives, segment
splits and is_dir per evaluation. Ignore decisions are unchanged (differential-fuzz
verified); ~50x faster on a pattern-heavy monorepo.
2026-08-25 15:46:44 +01:00
durmazoguzhan 3b12d5ce68 feat(typescript): emit a node per enum member (#3064)
A TypeScript enum's members got no graph node. Emit a member node per member with a case_of
edge to the enum (matching the C# handler), handling both member spellings
(property_identifier and enum_assignment), const enums, and unquoting a whole string member
name instead of one fragment; the member initializer is still walked so a nested expression
is not dropped.
2026-08-25 15:45:33 +01:00
durmazoguzhan 0e566345fc feat(csharp): emit a node per enum member (#3063)
A C# enum's members got no graph node, so an enum case was invisible. Emit a member node
per enum_member_declaration with a case_of edge to the enum (mirroring the Java/Kotlin/Swift
enum handlers), deduped against a case-only sibling collision; explicit and implicit values
both work and no builtin types are fabricated.
2026-08-25 15:45:06 +01:00
Azeem1985 62371ad28d fix(postgres): carry tree-sitter-sql in the postgres extra and surface grammar errors
The postgres introspection path synthesizes DDL and parses it with the SQL grammar, but
tree-sitter-sql was not in the postgres extra, so `pip install graphifyy[postgres]` left it
unable to parse and returned a silent empty result. Add tree-sitter-sql to the extra and
raise an actionable ImportError (with the install hint) when the grammar is missing or has
an incompatible ABI, instead of reporting zero nodes.
2026-08-25 15:44:52 +01:00
Azeem1985 b022c3469c fix(watch): ignore read-only inotify events so the watcher stops re-triggering on its own reads
On Linux, inotify emits opened / closed_no_write events for every file open and close,
including the watcher's own AST rebuild reading the tree, so the watcher fed itself a
rebuild loop. Drop those two read-only event types; close-after-write and
create/modify/move/delete still trigger, and the filter is a no-op on the macOS/Windows
backends that never emit them.
2026-08-25 15:44:45 +01:00
safishamsiandClaude Opus 4.8 282976b2f4 chore: bump to 0.9.49
Ships four batches this cycle: tsconfig cache-clear (#2917), C# generic type args at call
sites + field position (#2911), PDF/document slicing (#2900/#2903/#2906); the LLM/cache
resilience set — zero-node retry (#2927), reasoning-JSON recovery scope (#2926),
code-only --force semantic preservation (#2923), cross-language builtin-base fix (#2812),
uv-tool hook resolution (#2852), pre-manifest obsidian adoption (#2863); language
extractors — zig enum/union methods (#2999), julia abstract supertypes (#3000), commonlisp
cross-file inherits (#3001), powershell enums (#3002); and C#/extractor/merge fixes — C#
object creation (#2997), interface dispatch (#3003), property nodes (#3006), cross-repo
shared types (#3007), SQL transactions (#2953), bash command substitution (#2978), and
C++/ObjC definition-site preservation (#2990).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-24 14:18:33 +01:00
safishamsi 0b5297b479 docs(changelog): add 0.9.49 entries for the sql/bash/cpp/csharp/merge batch 2026-08-24 14:13:57 +01:00
safishamsi 960b6f5a0b test(merge): pin that a shared type links even when the declarations drift (#3007)
Document the cross-repo join's precision boundary: the key is namespace+name by design,
not structural, so a shared contract type whose declarations have drifted across repos
still links (and repo-unique types do not). Guards against a future change that tried to
gate the edge on member equality.
2026-08-24 14:12:53 +01:00
durmazoguzhan c46b756cde feat(merge): link a type declaration two repos share (#3007)
When merging graphs from multiple repos, a type declared in more than one repo under the
same fully-qualified namespace and name (a shared contract type) now gets a same_type_as
edge linking the declarations, so a cross-repo contract is navigable. Matching requires a
non-empty namespace plus label, a real sourced type declaration (not a method/field or
sourceless stub), and at least two distinct repos, so two unrelated types that merely share
a short name are not linked; the edge is INFERRED/0.9.
2026-08-24 14:09:46 +01:00
durmazoguzhan 3ef625b3b6 feat(csharp): emit a member node per property (#3006)
C# properties got no graph node, so a property was invisible as a class member (only
fields and methods appeared). Emit a member node per property_declaration with the same id
scheme, ownership, and defines/field-context edge as the C++ data-member branch; all
property shapes (auto, expression-bodied, read-only) are covered, the #2913 property-type
references walk is preserved, and no builtin types are fabricated.
2026-08-24 14:08:25 +01:00
winesoft-namjin-yun da8ca1684c fix(extract): keep the definition site when a decl/def pair is merged (#2990)
When a C/C++/ObjC declaration (header prototype) and its definition (implementation body)
merge into one node, the survivor kept the declaration's site, so the node pointed at the
prototype instead of the body. Record the definition's file/location on the survivor and
surface it as a Defined in: line; the pick is deterministic regardless of file order, and a
declaration with no definition keeps its own site.
2026-08-24 14:07:48 +01:00
akshitj11 5a56bd6943 fix(bash): emit calls edges for x=$(fn) command substitution (#2978)
A command substitution on the right of an assignment (x=$(foo)) was not recorded as a
call, unlike a bare $(foo). Gate call emission on the ancestor chain: allow a call inside a
command_substitution when it sits under a variable_assignment, while still suppressing bare
and arg-position substitutions and process substitutions.
2026-08-24 14:07:07 +01:00
akshitj11 6a06b652cc fix(sql): extract CREATE TABLE inside BEGIN/COMMIT blocks (#2953)
DDL wrapped in a transaction parses under a `transaction` node the statement walker never
descended into, so a CREATE TABLE inside BEGIN/COMMIT was never extracted while a top-level
one was. Recurse into transaction blocks; nested statements get the same handling, no
double-emit.
2026-08-24 14:06:55 +01:00
safishamsi 7fcff8eb4d docs(changelog): add 0.9.49 entries for the language-extractor + C# batch 2026-08-24 13:23:41 +01:00
durmazoguzhan 7f928bc1d0 feat(csharp): link interface methods to their single implementation (#3003)
A call through an injected interface dependency lands on the interface method, leaving the
implementation unreachable from the call site. When an interface has exactly one
implementing class, add a dispatches_to edge from each interface method to the matching
implementation method. Guarded to avoid false links: requires a real implements edge, a
single implementer, and a single case-sensitively same-named method; both ends must be C#;
0 or 2+ implementers emit nothing. Lives in graphify.csharp_dispatch as a registered
resolver.
2026-08-24 13:22:09 +01:00
durmazoguzhan 7f476e1447 fix(csharp): emit calls edges for object creation expressions (#2997)
A `new Foo()` object-creation expression emitted no edge, so constructor usage was invisible
in the graph. Add object_creation_expression to the C# call types and emit a calls edge to
the constructed type (member/qualified/generic forms), resolving a qualified construction
against declared namespaces without binding to an in-file placeholder. Built-in and
out-of-corpus types are not fabricated, and repeated constructions dedup to one edge.
2026-08-24 13:17:23 +01:00
rajatnagda45 be5110a789 fix(powershell): extract enum definitions and their members
A PowerShell enum definition and its members were not extracted, so a [Color] type
reference resolved to a sourceless phantom stub instead of the real enum. Emit the enum as
a real sourced node with its members as contained children (mirroring class_statement), so
references resolve to it; no builtins are fabricated.
2026-08-24 13:16:45 +01:00
rajatnagda45 46d3e5d5b8 fix(commonlisp): keep inherits edge when the superclass is in another file
A defclass whose superclass is defined in another file lost its inherits edge. Mint a
sourceless stub for the cross-file base (source_file empty, origin_file set) like the
import-stub path, so the corpus rewire collapses it onto the real definition and the
inherits edge survives; a same-file superclass still binds locally.
2026-08-24 13:16:39 +01:00
rajatnagda45 3c0eda3bdd fix(julia): extract abstract types declared with a supertype
An abstract type declared with a supertype (abstract type Dog <: Animal end) matched only
the bare-identifier form, so the subtyping declaration dropped the node entirely. Parse the
type_head shape shared with structs (factored into a helper) and emit the inherits edge; a
bare abstract type still works.
2026-08-24 13:15:31 +01:00
rajatnagda45 6930e4fa90 fix(zig): extract methods declared on enums and unions
Zig lets enums and unions carry methods like structs, but only the struct branch recursed
into the container body, so enum/union methods and the calls in their bodies were dropped.
Walk enum/union children the same way, parenting methods to the container with the same id
scheme; variants and fields are not turned into nodes.
2026-08-24 13:15:23 +01:00
safishamsi 512f9863bd docs(changelog): add 0.9.49 entries for the semantic-cache/cross-language/hooks/obsidian batch 2026-08-21 19:27:38 +01:00
abhay-codes07 4cbc8603dd fix(export): adopt a pre-manifest vault's own notes instead of orphaning them (#2863)
An Obsidian vault written before the ownership manifest existed had no record of which
notes graphify wrote, so on the next export those notes were orphaned. Seed ownership by
recognizing graphify's own notes (a graphify/ frontmatter tag for node notes; the
_COMMUNITY_ prefix plus the FROM #community/ Dataview marker for community notes) when the
manifest is absent, so the manifest starts out honest. The .obsidian config is not
adopted (Obsidian writes it too).
2026-08-21 19:22:21 +01:00
SinghAman21 245eb9dc9c fix(extract): scope fresh semantic results to dispatched files (#2926)
The #1757 guard scoped the semantic-cache WRITE to dispatched files, but the unfiltered
fresh result still fed build_merge, whose replace-set logic swapped a non-dispatched
file's entire prior contribution for a stray misattributed fragment (and logged the
'skipped out-of-scope source_file' warning). Apply the same allowlist to the result dict
before it reaches the merge, via a shared _semantic_source_matcher so the write guard and
the graph filter cannot drift.
2026-08-21 19:21:20 +01:00
hopstreax 24cf52d51e fix(cache): retry zero-node semantic results (#2927)
A semantic result with no nodes and no hyperedges (only edges, or nothing) was cached and
stamped into the manifest, so an empty/degenerate LLM reply for a file froze that file:
detect_incremental saw it unchanged and never re-dispatched it. Reject zero-node results
from the cache read and write, drop edges from the manifest stamp tuple, and heal an
existing manifest by re-queueing files that were already stamped with a zero-node result.
2026-08-21 18:26:49 +01:00
santhiprakash 5be36dac0d fix(extract): preserve existing semantic layer on --code-only --force (#2923)
A `--code-only --force` rebuild over an existing graph dropped the doc/paper/image
semantic tier, because force took the full-rebuild path and code-only never re-dispatched
those files. When an existing graph is present, keep incremental mode so build_merge
carries the semantic layer forward; files deleted from disk are still pruned.
2026-08-21 18:26:24 +01:00
santhiprakash 9452ef216b fix(hooks): resolve the uv tool venv when pin and launcher probes miss (#2852)
Installed via `uv tool install`, the post-commit hook could not find graphify: the pin and
launcher/shebang probes miss the uv tool venv, so the hook silently exit-0'd. Add a fourth
fallback probe that scans $UV_TOOL_DIR and the conventional uv tool locations for a python
whose env has graphify importable, firing only after the earlier probes miss and verifying
importability before adopting. Also gate the launcher read on a real #! header so a binary
trampoline is not misparsed as a shebang.
2026-08-21 18:26:11 +01:00
ousamabenyounes 037970159d fix(extract): stop a built-in base class from inheriting across languages (#2812)
A class extending a built-in base (PHP `extends \Exception`) emits a sourceless supertype
stub, and the corpus rewire bound it to the unique same-labelled real definition anywhere
in the corpus — so in a PHP+TS monorepo a PHP class inherited from the TypeScript
Exception, a phantom cross-language edge / god node. Gate the supertype-target rewire with
a per-language curated builtin-base set: refuse the rewire only when the referring file's
language names the base as a builtin and the resolved target is in a different language
family. Same-language inheritance and user classes named like a builtin still link.
2026-08-21 18:26:00 +01:00
safishamsi 0f625b6042 docs(changelog): open 0.9.49 with the tsconfig/csharp/pdf-slicing batch 2026-08-21 16:59:23 +01:00
safishamsi ada1c095ab fix(llm): bisect PDF slices on extracted text; reconcile splittable-PDF tests (#2906)
Three fixes landing the PDF-slicing set coherently:
- bisect_slice read raw container bytes, so the adaptive-retry path (a lone oversized
  slice that still overflows, #2880) searched for the newline cut in binary coordinates
  and could cut mid-line for a compressed PDF. Index unit_source_text instead, matching
  read_slice_text and expand_oversized_files; any converter failure falls back to None.
- #2900's test asserted a PDF is not splittable, which #2906 overturns; rewrite it to
  guard the real invariant (an image has no addressable text and is never sliced). The
  unreadable-PDF passthrough case is covered by test_pdf_slicing.
- add a bisect_slice-on-PDF regression test: the cut lands on an extracted-text line
  boundary and the halves tile the slice exactly.
2026-08-21 16:57:29 +01:00
abhay-codes07 4faa86c8d5 fix(llm): slice oversized PDFs through the converter (#2906)
An oversized PDF was sliced as raw container bytes, so slice offsets indexed binary data
instead of the extracted text the prompt carries. Introduce unit_source_text so both the
oversized-file expansion and per-slice reads index the same extracted text, and make PDFs
splittable through the converter.
2026-08-21 16:51:17 +01:00
abhay-codes07 b6b2fb17c8 fix(llm): slice every text document type, not just five of them (#2900)
The oversized-file slicer only split five suffixes while the doc allowlist reaching the
LLM was larger, so a large .qmd/.skill/.html/.yaml/.yml was truncated at the char cap
and silently dropped past it. Extend the splittable-text set to cover every text
document type, with a contract test so future allowlist additions fail loudly.
2026-08-21 16:51:00 +01:00
abhay-codes07 7c5203dde4 fix(llm): estimate PDF tokens from the extracted text, not the container (#2903)
Token estimation for a PDF read the raw container bytes, which are mostly binary and
bear no relation to the extractable text, so a small-text PDF could be judged oversized
(or vice versa). Estimate from the extracted text instead, memoized on path+size+mtime.
2026-08-21 16:50:44 +01:00
santhiprakash a4cb89083c fix(csharp): walk generic type arguments at call sites (#2911)
A type used as a generic argument at a call site (repo.Get<User>(),
services.AddSingleton<IFoo, Foo>()) did not emit a references edge, so DI registrations
and generic calls dropped their type dependencies. Walk the invocation's type-argument
list (member and static forms, nested args included); builtins and in-scope type
parameters are not fabricated.
2026-08-21 16:50:31 +01:00
brobl2008 09c985c553 fix(csharp): walk generic type arguments in field position
A type used as a generic argument in a field declaration (private List<Order> _orders)
did not emit a references edge to the argument type, so field-injected dependencies were
invisible. Walk the field's type through the shared type-ref collector, bringing fields
to parity with the property handler; builtins and in-scope type parameters are not
fabricated.
2026-08-21 16:50:25 +01:00
safishamsi 762a43a2e6 docs(resolution): note tsconfig caches are cleared per run (#2917)
Record the run-scoped-clear contract on both loader docstrings so the next reader
does not reintroduce the process-durable-cache assumption the fix removed.
2026-08-21 16:50:18 +01:00
sashankh cce41efb7c fix(extract): invalidate tsconfig alias/baseUrl caches per run (#2917)
The tsconfig/jsconfig alias and baseUrl caches were keyed by config path with no
mtime/content component and never cleared, so an edit to compilerOptions.paths or
baseUrl was never observed again for the life of the process — graphify watch and the
MCP server, which call extract() repeatedly in one process, kept resolving imports
through the stale alias map. Clear both caches per run alongside the other run-scoped
caches (within-run caching is preserved).
2026-08-21 16:49:55 +01:00
safishamsiandClaude Opus 4.8 b2cd362674 chore: bump to 0.9.48
Ships this cycle: the LLM-resilience batch — hollow-response same-chunk retry (#2880),
reasoning-first JSON recovery (#2882), deliberately-declined data JSON not counted as
failed (#2879); extractor fixes — C++ nested types + C++/CLI (#2876), markdown vault-wide
wikilinks (#2875); export fixes — control-char no longer aborts export (#2897), graph.html
restored for large graphs (#2853); and the --no-dedup opt-out (#2881).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-20 16:33:07 +01:00
safishamsi 1c6cf4a880 docs(changelog): add 0.9.48 entries for #2897, #2853, #2881 2026-08-20 16:14:04 +01:00
safishamsi e16b01ce48 test(extract): assert --no-dedup graph invariant, not just kwarg propagation (#2881)
The PR's tests spy on the dedup kwarg reaching build/build_merge. Add graph-level
assertions for what the kwarg does: dedup=False preserves a fuzzy near-duplicate pair
that dedup=True merges, and exact-id collisions still collapse to one node either way
(the structural invariant that makes the flag safe).
2026-08-20 16:13:45 +01:00
rajarshidattapy eccc6cf0bf feat(extract): add --no-dedup so incremental merges can skip fuzzy dedup (#2881)
Adds --no-dedup (default off, so dedup stays on) to skip the fuzzy near-duplicate merge
pass on build and incremental merge, for operators who would rather keep distinct symbols
that fuzzy-matched than pay the merge. Exact-id uniqueness is unaffected (it is a graph
structural invariant, not a dedup responsibility), and the flag arms the #479 shrink
guard so a surprising node drop is refused loudly. Mutually exclusive with --dedup-llm.
2026-08-20 16:10:49 +01:00
oleksii-tumanov 05f90f1682 fix(export): restore graph.html for large graphs (#2853)
The label and cluster-only commands did not pass the viz node limit to to_html, so a
graph over the node limit raised and the except branch silently unlinked the graph.html
that update had produced. Always pass the limit (the aggregated community meta-graph
renders instead of raising), preserve the existing file on a failed render via an atomic
publish plus a stale marker, and regenerate a missing graph.html on the no-topology-change
fast path without reclustering.
2026-08-20 16:10:36 +01:00
abhay-codes07 917e331ab4 fix(export): a control character in a label must not abort the export (#2897)
A C0 control character in a node label or id (from a mangled extraction or an odd
filename) crashed the GraphML export (XML 1.0 forbids C0 except tab/LF/CR) and the
Obsidian export (EINVAL on Windows paths), aborting the whole artifact. Fold a
control-char scrub into the existing per-format coercion hooks so only the illegal
characters are stripped; tab/LF/CR and non-ASCII letters are preserved, and to_json
(and its byte-identity round-trip) is untouched.
2026-08-20 16:09:00 +01:00
safishamsi b54a1f00fd docs(changelog): open 0.9.48 with the hollow-response/parser/cpp/markdown batch 2026-08-20 15:48:15 +01:00
rajarshidattapy 69e2c0deae fix(llm): retry hollow responses instead of bisecting them (#2880)
A response that parses but carries no symbols (a "hollow" reply) was routed into the
truncation-bisection path, which just re-split a chunk the model had already answered
emptily, wasting calls. Give hollow its own finish_reason and route it through a bounded
same-chunk retry with backoff instead; on persistent hollow, give up loudly and mark the
files partial. GRAPHIFY_MAX_RETRY_DEPTH=0 now disables the hollow retry too, so a chunk
costs exactly one call. The #2866 timeout and the truncation paths still bisect.
2026-08-20 15:45:18 +01:00
safishamsi e8bef863f0 fix(llm): gate the reasoning-JSON winner on sanitized content, not raw value (#2882)
A reasoning sketch that lists ids as bare strings (`{"nodes": ["A", "B"]}`) has truthy
arrays but no node/edge objects. The winner gate tested the raw parsed value, so the
sketch won and then sanitized to empty, shadowing the real fragment that followed and
re-triggering the #2880 hollow-response bisection. Sanitize before the emptiness gate so
such a sketch is demoted to the empty-fragment tier. Also document the keyed-candidate
cap crowd-out as a known gap.
2026-08-20 15:44:56 +01:00
rajarshidattapy bce2c9b3d3 fix(llm): recover JSON from reasoning-first model replies (#2882)
Reasoning-first models think out loud, fence the answer, or both, so the reply is not a
bare JSON object and the strict parse dropped the whole chunk. Try the whole reply first
(unchanged fast path), then each balanced-brace candidate, preferring braces that carry
the extraction keys so narration braces do not shadow the answer; a shape restatement
that carries the keys but no content is kept only as a last resort.
2026-08-20 15:44:56 +01:00
safishamsi 2b02b7a7dc docs(cpp): note nested enums stay out of scope of the nested-type fix (#2876)
The recovery covers class/struct only; record that nested enums are a known,
intentional gap so the next reader does not assume they are handled.
2026-08-20 15:42:36 +01:00
rajarshidattapy f5743dde2b fix(cpp): keep symbols for nested C++ types and C++/CLI sources (#2876)
Nested class/struct types were dropped because the field_declaration branch returned
before walking the class_specifier in its type field. Walk it instead, so nested types
and their members are emitted with a contains edge from the enclosing type. C++/CLI
(ref class, gcnew, ^/% handles) cannot be parsed by tree-sitter-cpp at all (it produces
ERROR nodes and fabricates symbols), so normalize those tokens to plain C++ before
parsing, preserving byte length and line breaks; SCREAMING_CASE constants and attached
XOR/modulo operators are kept out of the handle rewrite.
2026-08-20 15:42:36 +01:00
BaeHyunJae b3cd74a0cb fix(markdown): resolve wikilinks vault-wide when sibling resolution misses (#2875)
An Obsidian-style [[wikilink]] resolves to a note anywhere in the vault by basename, but
resolution only tried sibling files, so cross-folder links were silently lost. Add a
vault-wide fallback that fires only when relative/sibling resolution misses, with a
deterministic tiebreak on ambiguous basenames (shallowest path, then lexicographic
root-relative path) and a once-per-scan index so it stays O(N).
2026-08-20 15:41:30 +01:00
rajarshidattapy ef282c19fa fix(extract): don't classify a deliberately-declined data JSON as failed (#2879)
A data-shaped JSON that extract_json intentionally declines (returning a `skipped`
marker, not an `error`) was counted as a failed extraction, so it was kept out of the
incremental manifest and re-processed on every run. Treat the `skipped` decline as a
valid empty outcome, disjoint from genuine failures (which still return `error` and are
still reported).
2026-08-20 15:41:07 +01:00
safishamsiandClaude Opus 4.8 b14b52e94e chore: bump to 0.9.47
Ships this cycle: the graph-correctness/UX batch — JS/TS factory-object methods
(#2745), stable graph.json field order (#2582), query names its graph (#2789),
ThinkingBlock-safe claude backend (#2697), manifest churn guard (#2838), C# primary
ctor refs (#2829), AST INFERRED rubric confidence_score (#2813), legacy numeric
confidence normalization; plus the small-fix batch — chunk-bisect on timeout (#2866),
symlink cache identity (#2832), sidecar cache root (#2787), driveless Windows path
guard (#2795), actionable partial-parse warning (#2788), and non-ASCII Obsidian tags
(#2862).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-19 14:11:10 +01:00
safishamsi 2acc62f38f fix(obsidian): make _obsidian_tag docstring a raw string (#2862)
The docstring documents the `\w` regex class; as a non-raw string that is an
invalid escape sequence (DeprecationWarning now, SyntaxError in a future Python).
Mark it raw.
2026-08-19 14:07:48 +01:00
abhay-codes07 4f104e6e1f fix(extract): make the partial-parse warning actionable, and stop citing closed #2551 (#2788)
The partial-parse warning ended every message with a hardcoded (#2551) — a Kotlin-specific
issue that is now closed — which misdirected reporters into recording unrelated failures as
already-tracked. Drop the citation and append real per-file data instead: the surviving
symbol count, distinguishing a total-loss file from a partially-recovered one.
2026-08-19 14:05:58 +01:00
abhay-codes07 e4b85d3b50 fix(hooks): a driveless rooted path is not cwd-relative on Windows (#2795)
The out-of-project read guard treated any non-absolute path as cwd-relative, but on
Windows a rooted-but-driveless path (`\foo\bar`) is not absolute yet resolves against
the current drive root, outside the project. Classify with a platform-correct predicate
(`not root and not drive` under the host path flavour) so the containment check is
reached. On POSIX the predicate reduces to `not is_absolute()`, so no behaviour changes
there.
2026-08-19 14:05:58 +01:00
hopstreax 26092ce5b1 fix: bisect extraction chunks on timeout (#2866)
A timeout on a multi-file extraction chunk failed the whole chunk. Route recognized
timeouts (subprocess.TimeoutExpired, SDK APITimeoutError, botocore read/connect
timeouts) through the same bounded bisection/merge path already used for
context-window-exceeded errors, so a single slow file no longer takes its chunk-mates
down. A single unsplittable file that times out is left unstamped and retried next run,
as before.
2026-08-19 14:05:58 +01:00
oleksii-tumanov dfdcf9e408 fix(cache): preserve symlink path identities (#2832)
file_hash salted the content digest with the resolved (symlink-collapsed) path, so a
symlink alias and its target hashed identically and one displaced the other from the
graph on a warm cache. Salt with the walked (lexical abspath) path relative to root
instead, giving aliases distinct keys; when the scan root itself is a symlink, derive
the leaf-relative salt from the lexical ancestor matching the resolved root. The
detect-layer containment guard (which resolves to block symlink escape) is untouched.
2026-08-19 14:05:58 +01:00
hopstreax c443ee7b3a fix(detect): respect cache root for converted sidecars (#2787)
Converted Office/Google-Workspace sidecars were written to `root/GRAPHIFY_OUT/converted`,
always anchored to the scanned source tree, so `graphify extract --out <dir>` against a
read-only or pinned checkout polluted the source tree. Route sidecar writes through the
cache root while keeping the content hash anchored to the scan root, so sidecar filenames
stay stable across checkouts.
2026-08-19 14:05:58 +01:00
josh-leung-KR 000c71a4a5 test(obsidian): cover non-ASCII community tags and colour-group parity (#2862)
Fails on the current sanitizer in 4 of 5 cases: Korean/Japanese/accented labels
lose their letters, distinct communities collapse to the same tag, and the
graph-view colour group queries a tag no note carries.
2026-08-19 14:05:58 +01:00
josh-leung-KR 4946c711ac fix(obsidian): keep non-ASCII letters in community tags (#2862)
_obsidian_tag stripped every non-ASCII character, so a Korean or Japanese community label collapsed to underscores and every note in that community carried the same tag. Python's \w is Unicode-aware, so switching the filter keeps letters from any script while still dropping spaces and punctuation.

Also route the .obsidian/graph.json colour-group query through the same sanitizer: it was built from the raw label, so on a non-ASCII label it queried a tag that no note carries.
2026-08-19 14:05:58 +01:00
safishamsi 56c1060158 test(query): assert the CLI query call site wires graph_path (#2789)
The header logic is unit-tested, but only a real subprocess run proves the CLI
query command actually passes the resolved graph path through — the wiring that
was the point of #2789. Cover both the under-CWD relative form and an explicit
--graph outside the CWD shown in full. Plus 0.9.47 changelog entry.
2026-08-18 22:38:47 +01:00
abhay-codes07 b8a8b4c4c9 fix(query): name the graph the answer came from (#2789)
The query header now leads with the graph file it opened and its node count,
shown relative to the CWD when the graph sits underneath it and absolute when it
does not — surfacing the case where a query run from a parent project silently
answers from the wrong corpus. graph_path is optional, so the header is
byte-identical for callers that do not pass it; the CLI query command and the MCP
query tool, which already resolve the path for querylog, now pass it.
2026-08-18 22:36:42 +01:00
safishamsi c0b46453d7 docs(changelog): add 0.9.47 entries for #2745 and #2582 2026-08-18 22:35:22 +01:00
safishamsi d0f0ac1c8d fix(js): dedup factory-object contains edge; cover arrow + bare-receiver (#2745)
The factory-object owner path emitted the `contains` edge inside the per-member
loop; add_node dedups on id but add_edge does not, so N methods assigned to one
object flooded the graph with N identical contains edges. Emit it once per owner.

Tests: assert a single contains edge across four methods, cover arrow-function
assignment (the dominant modern factory shape), and lock the negative case that a
non-object-literal receiver (`external.handler = fn`) is not captured.
2026-08-18 22:32:41 +01:00
rajanpanth 61228be167 fix(js): extract methods assigned to factory object APIs (#2745)
Preserve callable members assigned to a local object-literal factory API
(`const api = {}; api.foo = fn`), modeling the API object beneath its factory
and attaching the assigned functions as methods. The lazy owner-node minting
(only for identifiers proven to be object-literal bindings in the enclosing
function) avoids the #1077 config-object flood.

Partially addresses #2524 (the object-literal-method shorthand form
`return { foo() {} }` remains out of scope).
2026-08-18 22:29:47 +01:00
safishamsi 120c7d861f test(export): lock non-ASCII round-trip byte-identity for field-order fix (#2582)
Covers the ensure_ascii write path the field-order stabilization implicitly
relies on: a reordered node dict carrying escaped-unicode values must serialize
byte-identically across a read-rebuild.
2026-08-18 22:27:27 +01:00
C0KERNELandClaude Opus 4.8 b1f847d716 fix(export): stabilize graph.json field order across a read-rebuild round-trip (#2582)
node_link_data always appends the node key (id) last, so id sat mid-dict on a
cold build but last after a read-rebuild — churning graph.json key order with
no content change and defeating byte-stable caching. to_json now canonicalizes
each node/link dict (id / source,target,relation first, remaining keys sorted)
before serialization, so a load -> rebuild -> write round-trip is byte-identical.
Pure key permutation; values are untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 22:20:57 +01:00
safishamsiandClaude Opus 4.8 7047411678 test(claude): lock first-text-block (not concatenation) for the ThinkingBlock helper (#2697)
Adds the multiple-text-block test the deep-dive flagged: the helper must return
the FIRST text block (graphify's claude calls carry a single JSON payload, so
concatenating would corrupt it). Adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 22:20:19 +01:00
mdshzb04andClaude Opus 4.8 55822b0399 fix(claude): read text blocks after a leading ThinkingBlock (#2697)
Extended thinking is on by default on current Claude models, so a response's
content[0] is a ThinkingBlock and the old content[0].text raised AttributeError
on the SDK claude backend. A shape-aware helper (mirroring the existing
_bedrock_response_text) skips leading non-text blocks and returns the first
text block; a thinking-only response falls back to the default. Only the two
SDK claude call sites are touched; the claude-cli JSON-envelope path is unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 22:19:29 +01:00
safishamsiandClaude Opus 4.8 97f2bb7540 test(detect): cover ast-kind no-op churn and corrupt-manifest write (#2838)
Adds the two cases the deep-dive flagged: the kind='ast' path (the literal
graphify update scenario) stays byte-identical on a no-op and updates on a real
edit; and a corrupt/unparseable existing manifest still gets written (the
byte-equality skip's except must never silently drop a real update). Also adds
the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 18:09:59 +01:00
hopstreaxandClaude Opus 4.8 173a8814d2 fix(detect): prevent manifest timestamp churn on unchanged updates (#2838)
save_manifest unconditionally stamped a fresh 'seen' timestamp for every file
on every run, so a no-op graphify update rewrote all manifest entries and left
graphify-out/ permanently dirty (a trailing graph commit on every push). Now
the per-file 'seen' is preserved for genuinely unchanged entries, and the disk
write is skipped entirely when the serialized manifest is byte-identical to
what is already on disk; a real change still refreshes and persists.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 18:08:32 +01:00
safishamsiandClaude Opus 4.8 1eb356cde1 test(csharp): cover builtin-not-fabricated and struct primary-ctor (#2829)
Adds the two cases the deep-dive flagged: a built-in-typed primary-ctor param
(int count) must not fabricate a referenced node, and the branch's struct_declaration
claim is locked by a struct primary-ctor test. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 18:07:12 +01:00
brobl2008andClaude Opus 4.8 3e8ec33994 fix(csharp): walk primary-constructor parameters for references and calls (#2829)
A C# 12 primary constructor puts its parameters on the class/record declaration
itself, which the extractor never walked: class Holder(IDep dep) emitted no
references edge Holder->IDep, and because dep was never registered in the class
receiver table, a dep.Method() call inside the class was dropped too. Scan the
declaration's parameter_list, register each param name->type, and emit the
param type reference — mirroring the field/property handlers. Built-in and
type-parameter types are not fabricated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 16:30:16 +01:00
safishamsiandClaude Opus 4.8 7c10a961b0 docs(changelog): add the AST INFERRED rubric confidence_score entry (#2813)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 16:12:01 +01:00
abhay-codes07andClaude Opus 4.8 3bbf420bc3 fix(extract): give AST INFERRED edges a rubric confidence_score (#2813)
AST-emitted INFERRED edges landed at the rubric-forbidden 0.5 (or a hardcoded
0.8). Each AST INFERRED emission site now sets a discrete rubric score keyed to
the relation (uses -> 0.95 direct structural evidence, indirect_call and
unresolved cross-file calls -> 0.85), and the INFERRED write-time default moves
0.5 -> 0.55 so any score-less INFERRED edge is on the rubric set. EXTRACTED /
AMBIGUOUS tiers are unchanged; uses stays INFERRED (not promoted to EXTRACTED)
to keep audit percentages honest.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 16:02:02 +01:00
safishamsiandClaude Opus 4.8 74abbfa30c test(build): assert legacy-confidence normalization is idempotent; open 0.9.47
Adds the round-trip idempotency check the deep-dive flagged: after the first
load heals a legacy numeric confidence to INFERRED, reloading the persisted
graph stays silent with a stable score (the warning must not just move one run
later). Dates 0.9.46, opens 0.9.47.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 15:59:23 +01:00
Trantor-developsandClaude Opus 4.8 5ad221c3f4 fix(build): normalize legacy numeric edge confidences to INFERRED on load
A pre-enum graph.json stored a numeric edge confidence (a float) instead of a
string tag, which tripped the per-edge 'invalid confidence' validator warning on
every incremental reload. _fold_edge_aliases now moves a numeric confidence into
confidence_score (when none is present) and sets the tag to INFERRED — never
EXTRACTED, since a recovered legacy float is not structural provenance. Modern
string tags are untouched (no churn) and the raw float survives in
confidence_score.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-18 15:54:27 +01:00
safishamsiandClaude Opus 4.8 558df6d57d chore: bump to 0.9.46
Ships: Common Lisp extractor; the graph-correctness batch (edge-relation
collapse #2803, orphaned-import sweep #2807, hyperedge member rewire #2805,
non-UTF-8 ignore #2798, id-less hyperedge #2775, Go case-only #2779,
.graphify_root validation #2603, #2694 part 2); the fresh-contributor batch
(markdown node_kind #2533, post-checkout skip #2421, underscore query #2473,
Java annotation refs #2426); and the normalize_id caseless-stability fix.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 19:21:39 +01:00
safishamsiandClaude Opus 4.8 0929519ec1 fix(ids): make normalize_id caseless-stable via a casefold+NFKC fixpoint loop
casefold and NFKC do not commute and neither is a fixpoint of the other, so a
single NFKC(casefold(...)) pass left normalize_id(s) != normalize_id(s.casefold())
for some combining-mark sequences (e.g. Greek ypogegrammeni U+0345 + a combining
accent): pre-casefolding turned U+0345 into iota, which NFKC then composed with
the accent into a form the single pass never saw. Iterate casefold-then-NFKC to
a bounded fixpoint (casefold first, on the raw input) so the result is stable
regardless of prior casefolds. No churn: letter/digit-bearing ids and every
CONTRACT_CASE are byte-identical; idempotency, word-only, and the Turkish (#2614)
cases still hold. Adds a deterministic regression pin so the fix does not rely on
hypothesis re-drawing the codepoints.

This was a pre-existing latent bug (present in released 0.9.45), surfaced by the
hypothesis property test; ids.py was untouched by the PRs landed alongside it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 19:00:46 +01:00
safishamsiandClaude Opus 4.8 356b50df6f test(java): make the annotation no-dup test effective + add string/enum guard (#2426)
The no-dup test asserted on _edge_labels (a set), so count()==1 was trivially
true whether or not the dedup ran. Count raw edge occurrences (normalized
labels) so a regressed dedup — @Uses({X, X}) emitting 2 edges — actually fails
the test. Adds a guard that string/enum annotation arguments (@RequestMapping(
"/x"), @Retention(RetentionPolicy.RUNTIME)) do not fabricate type refs. Adds
the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 18:42:21 +01:00
oleksii-tumanovandClaude Opus 4.8 eadef76a68 fix(extract): emit Java annotation type references (#2426)
Java annotation extraction read only the annotation's name field, dropping
class-literal arguments (@Repeatable(RubricsFor.class), @Uses({A.class,B.class}))
and annotation-member return types (RubricFor[] value()), so a container
annotation became a disconnected island. Emit references edges for both, with
qualified-identity preservation; string/enum annotation arguments are not
treated as type refs, and JDK annotations resolve to sourceless stubs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 18:33:35 +01:00
safishamsiandClaude Opus 4.8 4be19990aa test(serve): add over-match guard for underscore token splitting (#2473)
The fix broadens seeding (splitting user_service into user + service), so add
the negative test the deep-dive flagged: an unrelated single-token node must not
out-rank the node matching the full multi-token query. (Note: _search_tokens
does not split camelCase, so the fix covers underscore/hyphen, not camelCase.)
Adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 18:30:50 +01:00
nadiadatepe-engandClaude Opus 4.8 236ed9e548 fix(serve): treat _ as a token separator so underscore queries match hyphenated labels
_search_tokens split on \w+, which counts _ as a word char but not -, so a
query spelled with underscores stayed one un-matchable token while a hyphenated
label tokenized into parts. Splitting on [^\W_]+ makes both sides tokenize
consistently, so `graph_first_guard` matches `graph-first-guard`. Both query
and label route through _search_tokens, keeping the two sides symmetric.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 18:01:01 +01:00
safishamsiandClaude Opus 4.8 355b6628b4 test(hooks): replace static string-match with a runtime same-head test (#2421)
The PR's test only asserted the guard line exists in the source — the exact
static-assertion anti-pattern #2126/#2641 removed for providing zero coverage.
Replace it with a runtime test that runs the real emitted post-checkout script
under sh up to the guard (with a sentinel, before the launch): same-head skips,
different-head falls through, file-checkout skips at the earlier guard. Adds the
CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 17:53:43 +01:00
nothariharanandClaude Opus 4.8 5c88af7617 fix(hooks): skip post-checkout rebuild when PREV_HEAD equals NEW_HEAD (#2421)
git checkout -b <new> reports a branch switch (flag=1) but passes the same SHA
for prev and new HEAD, so the post-checkout hook fired a full changed_paths-less
rebuild — the most expensive graphify op — on essentially every new branch. Add
a POSIX-sh guard that exits 0 when PREV_HEAD == NEW_HEAD; a real branch switch
(PREV != NEW) still rebuilds.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 17:47:56 +01:00
safishamsiandClaude Opus 4.8 e7cb399ac3 test(markdown): cover PyYAML-absent fallback and heading id-stability (#2533)
Adds the two gaps the deep-dive flagged: a direct test of
_parse_frontmatter_fallback (the PyYAML-absent path, previously unexercised)
and an assertion that heading ids stay _make_id(stem, title) regardless of
frontmatter/node_kind (pins no id-churn). Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 17:47:16 +01:00
evanthomasgeldersandClaude Opus 4.8 cf4dac387f feat(markdown): tag page vs heading nodes and extract frontmatter
Adds an additive node_kind ("page"|"heading") attribute so a docs corpus can
distinguish the page node from its heading nodes, and parses leading YAML
frontmatter onto the page node via the bounded sanitize_metadata (values become
capped attributes, not graph nodes). Also fixes a leading YAML `#` comment in
frontmatter being extracted as an H1. Node ids/labels/file_type are unchanged,
so existing markdown graphs are not re-keyed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 17:21:01 +01:00
safishamsiandClaude Opus 4.8 7765d610d8 fix(commonlisp): mint sourceless stubs for import targets so edges don't dangle
The extractor emitted `imports` edges to _cl_id(mod_name) with no node created,
so a :use/require edge dangled (verified: sample.lisp left 'cl' and 'alexandria'
as edgeless targets) and never resolved to an in-corpus defpackage. Mint a
sourceless stub for each import target (the established cross-file pattern):
edges now have real targets, the corpus rewire collapses a stub onto a unique
in-corpus defpackage of the same name (:use :mylib -> the real package), and an
external one (cl) persists as a clean leaf. origin_file is stripped before
persist. Adds a no-dangling-edges regression test. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 16:08:55 +01:00
fadeandClaude Opus 4.8 038ada6f0f feat(commonlisp): add Common Lisp .lisp/.cl/.lsp/.asd extractor (optional tree-sitter-commonlisp extra)
tree-sitter-commonlisp-backed extractor for packages, classes, functions,
methods, generics, macros, variable definers, and same-file calls. Handles the
grammar's dedicated defun node (defun/defmacro/defmethod/defgeneric via
defun_header) and the generic list_lit + leading-symbol forms (defvar/defclass/
defpackage), recurses into wrapper macros (eval-when/progn) and reader
conditionals, and maps CL operator chars (= < > ? ! + *) to readable id
suffixes. Wired into detect/extract dispatch, the extractor registry, a
[commonlisp] optional extra, and the README; ships a fixture and a 23-test suite
behind an importorskip guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 16:05:33 +01:00
safishamsiandClaude Opus 4.8 c44a6cf7f1 cleanup(serve): drop dead <=budget sub-branch in the overshoot notice (#2784)
The `if len(output) <= char_budget: return output` inside the cut_count==0
block sits within `if len(output) > char_budget`, so it can never be true.
Remove it and note why the branch is reached only when nodes fit but edges
overrun. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:41:59 +01:00
AromalBiju1andClaude Opus 4.8 7d01244a03 fix(serve): honest overshoot notice when edges push a complete answer over budget (#2784)
An unconditional early return once no whole node line was cut returned the full
edge section unchecked, so a query could emit ~6x the requested budget with no
indication — and the truncation banner advised raising the budget, the exact
trigger. When the node set fits but appending edges overruns the budget, prepend
an honest 'complete answer over budget' notice (real counts, estimated vs
requested tokens) without truncating edges, preserving the #2601 completeness
guarantee. The genuinely-fits case is byte-identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:40:56 +01:00
safishamsiandClaude Opus 4.8 7722e23900 fix(detect): decode a UTF-16-BOM ignore file instead of latin-1 garbage (#2798)
The #2799 fallback (utf-8 -> host codepage -> latin-1) turned a BOM'd UTF-16
ignore file (what PowerShell Set-Content / Notepad 'Unicode' write) into
NUL-laden mojibake via latin-1, so its rules matched nothing. Detect the
UTF-16 BOM and decode as utf-16 before the latin-1 fallback. Adds an
end-to-end UTF-16 exclusion test and a direct no-NUL-garbage test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:40:19 +01:00
abhay-codes07andClaude Opus 4.8 7d855bbc98 fix(detect): stop silently dropping rules from a non-UTF-8 ignore file (#2798)
Ignore files were read with errors="ignore", so a mis-encoded byte in a rule
(e.g. a cp1252 accented directory name) was deleted, turning the pattern into
one that matches nothing — an exclusion that silently failed open. Both
rule-read sites now decode UTF-8-BOM first, then fall back to the host codepage
and latin-1 (never raising, never dropping bytes), with a one-time warning; the
rule survives intact instead of being truncated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:36:14 +01:00
safishamsiandClaude Opus 4.8 5929edf984 test(dedup): pin chained-collapse and kept-single-member for hyperedge rewire (#2805)
Adds the two cases the deep-dive flagged: a chained collapse (a_old, a_mid -> a)
lands directly on the final survivor (the whole fix rests on the union-find
remap being fully flattened), and a hyperedge collapsing to one distinct member
is kept, not dropped (pinning the deliberate sub-two-member policy). Adds the
CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:35:53 +01:00
abhay-codes07andClaude Opus 4.8 0d145fe110 fix(dedup): rewire hyperedge members onto survivors instead of dropping them (#2805)
Node dedup rewired edge endpoints to survivors but never remapped hyperedge
members, so a member naming a merged-away node silently vanished from the
rebuilt graph (the group shrank with no dangling reference). deduplicate_entities
now rewires hyperedge member ids through the same union-find survivor map the
edges use, de-duplicating members within each hyperedge; id-less/malformed
hyperedges pass through untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:34:16 +01:00
safishamsiandClaude Opus 4.8 795102cc28 test(build): pin shrink-guard safety and shared-stub survival for orphan sweep (#2807)
Documents the target-only invariant that makes a single sweep pass sufficient,
and adds two tests: the sweep does not trip the #479 shrink guard (swept
source-less orphans count as explained loss), and a stub still referenced by a
surviving file is not swept. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:33:34 +01:00
abhay-codes07andClaude Opus 4.8 ab73657432 fix(build): sweep external-import nodes a prune leaves orphaned (#2807)
An external-import stub (source_file: "") is only ever an edge target of the
file that imported the symbol. When prune_sources removes that file, the stub
is stranded at degree 0 but no stale-node path reaches it (they all key on
source_file), so it accumulates in the node count, GRAPH_REPORT and exports.
build_merge now sweeps source-less degree-0 nodes that the prune just orphaned,
guarded against nodes that were already isolated beforehand so real content is
never touched.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:26:44 +01:00
safishamsiandClaude Opus 4.8 01921dbc35 test(build): assert metadata survives demotion + unknown-relation is specific; open 0.9.46 (#2803)
Adds a numeric-metadata-preserved test (surviving specific edge keeps its own
weight/confidence, not the demoted generic's) and an unknown-relation test
(a non-denylisted relation is treated as specific in either arrival order, so
the denylist can't drift into an ordering). Dates 0.9.45, opens 0.9.46.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:25:39 +01:00
abhay-codes07andClaude Opus 4.8 a359b7f39b fix(build): keep the specific relation when an edge pair collapses (#2803)
When two edges connect the same (source, target) pair with different relations,
the simple-graph collapse was last-write-wins by alphabetical relation, so a
specific `calls` was systematically overwritten by a generic `references`/
`uses` — and `references` is not in the callflow filter, so those call sites
dropped out of the call graph. A generic relation can no longer clobber a
stored non-generic one; the outcome is now order-independent and the edge count
is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-17 15:24:13 +01:00
safishamsiandClaude Opus 4.8 0738af373a chore: bump to 0.9.45
Ships: id-less hyperedge load tolerance (#2775), per-platform version stamp
completing #2694, Go case-only symbol collision (#2779), and .graphify_root
anchor validation (#2603).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 21:12:56 +01:00
safishamsiandClaude Opus 4.8 f0345da28b harden(watch): document cwd anchor fallback, align bucket tuple, add tests (#2603)
Two small hardening tweaks on top of #2778: comment that in the hook path
Path.cwd() is the load-bearing anchor rescue (project_root == watch_root ==
the bad marker), and add hyperedges to the _anchors_stored_sources bucket
tuple to match the sibling loop. Adds a deletion-still-evicts test (the anchor
validation must not over-preserve) and an incremental==cold id-parity test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 19:22:06 +01:00
catpotdandClaude Opus 4.8 6f05172521 fix(watch): validate .graphify_root before anchoring stored sources on it (#2603)
A graph built on a subfolder stores source_file relative to the repo root but
the skill writes .graphify_root as the absolute subfolder, so an incremental
rebuild anchored stored paths under the wrong root, judged every unchanged
source deleted, and collapsed the graph. The anchor is now adopted only if the
stored sources actually resolve under it, falling back to the build root / cwd
otherwise, so a stale subfolder marker can no longer evict the whole corpus.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 18:36:22 +01:00
safishamsiandClaude Opus 4.8 05e1e4c01d test(go): cover method-level and all-exported case-only collisions (#2779)
Adds the two cases the deep-dive flagged as untested: a receiver-based method
collision (Get/get on the same type) and the all-salted branch where no member
is the unique exported one (Run/RUN). Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 18:35:46 +01:00
catpotdandClaude Opus 4.8 1e68a7aa76 fix(go): keep both halves of a case-only symbol collision (#2779)
Node ids casefold (deliberately, for AST/LLM/builder parity), but Go is
case-sensitive and uses case for visibility: exported `Run` and unexported
`run` in one file collapsed to one id, so the second was dropped by add_node
and a local `run()` call phantomed to a same-named symbol in another package.
The Go extractor now salts the non-canonical half of a same-file case-only
collision (exported keeps the stable plain id), so both survive and the
in-file resolver binds the unexported call locally. ids.py / normalize_id are
untouched, so the id contract holds and non-Go corpora are unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 18:34:46 +01:00
safishamsiandClaude Opus 4.8 7addee1159 test(install): assert stale untouched platform still warns end-to-end (#2694)
Adds the end-to-end assertion the version-stamp fix was really about: after
installing one platform, a different stale platform actually emits the
staleness warning on stderr (the behavior the over-stamping suppressed). Adds
the CHANGELOG entry closing #2694.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 18:34:11 +01:00
Ousama Ben YounesandClaude Opus 4.8 a59a4e812e fix(install): stamp .graphify_version only for the platform being installed (#2694)
install() called _refresh_all_version_stamps(), which stamped every installed
platform's .graphify_version with the current version WITHOUT rewriting that
platform's skill content — so a genuinely stale platform was stamped current
and its staleness warning was suppressed. Removes that bogus refresh; each
platform's stamp now advances only when its own content is (re)written via
_copy_skill_file, so a not-reinstalled stale platform correctly still warns.
Completes #2694 (part 1 shipped in 0.9.44 via #2753).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 18:30:13 +01:00
safishamsiandClaude Opus 4.8 0524982346 test(export): cover many/empty id-less hyperedges; open 0.9.45 (#2775)
Adds the multi-id-less case (the real corpus had 183/234 id-less) and the
empty-string-id case (falsy, treated as id-less). Dates the released 0.9.44 and
opens the 0.9.45 section.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 18:28:53 +01:00
Ousama Ben YounesandClaude Opus 4.8 ae8d059231 fix(export): tolerate id-less persisted hyperedges in attach_hyperedges (#2775)
The semantic extractor emits hyperedges with no id and build.py persists them
verbatim, so a prior graph.json can contain id-less hyperedges. Seeding the
dedup set with a hard h["id"] raised KeyError: 'id' on every incremental
re-extract, silently failing the whole graph load. Guard the comprehension with
h.get("id"), symmetric with the incoming-set guard already below it; id-less
entries are retained in the graph, id-bearing dedup is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-16 18:27:34 +01:00
safishamsiandClaude Opus 4.8 4fca621532 chore: bump to 0.9.44
Ships the accumulated 0.9.44 fixes: OCaml qualified-call fix; cross-file uses
attribution (#2652), nested JS functions incl. arrow idioms (#2653), bash
source-path resolution + traversal gate (#2596), wiki verbatim links (#2597),
export MAX_PATH budgeting (#2655), external-import & function-expression
indirect_call shadows (#2757/#2752), lazy CommonJS requires (#2700), affected
absolute-seed root (#2706), cpp doctest TEST_CASE recovery (#2594), git-tracked
gitignored files (#2759), CLAUDE_CONFIG_DIR always-on install (#2694), and
committed viz-node-limit config (#2760).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 22:10:43 +01:00
safishamsiandClaude Opus 4.8 c389b3ee75 fix(hooks): baked viz limit must yield to a per-run override; status resilient (#2760)
Two fixes on top of #2768: (1) the baked line was an unconditional
export GRAPHIFY_VIZ_NODE_LIMIT="<n>", which clobbered an explicit
GRAPHIFY_VIZ_NODE_LIMIT=... git commit; use the ${VAR:-<n>} default form
(mirroring GRAPHIFY_MAX_WORKERS) so the per-run value wins, and widen the
status drift regex to read the new form (still accepting the old bare one).
(2) A malformed .graphifyrc turned the read-only hook status into a traceback;
status now catches the parse error, warns, and continues. Adds precedence and
malformed-status tests. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 22:00:53 +01:00
hopstreaxandClaude Opus 4.8 dc895a2f7c fix(hooks): persist viz node limit in project config (#2760)
Adds a committed .graphifyrc (viz_node_limit=<int>) that `graphify hook install`
reads and bakes into the generated post-commit/post-checkout hooks, so a
project-wide viz node limit is shared via version control and survives hook
regeneration instead of needing a hand-edit that the next --force clobbers.
`hook status` reports the value and flags drift.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 21:55:47 +01:00
safishamsiandClaude Opus 4.8 65b33b0e62 test(install): cover CLAUDE_CONFIG_DIR always-on registration (#2694)
Adds the coverage the fix lacked (the shared home sandbox deletes
CLAUDE_CONFIG_DIR, so it must be set explicitly): env set -> registration lands
in $CLAUDE_CONFIG_DIR/CLAUDE.md and the default ~/.claude profile is untouched;
env unset -> unchanged ~/.claude/CLAUDE.md with the tilde skill ref. Also adds
the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 21:54:36 +01:00
AromalBiju1andClaude Opus 4.8 4910dccc4a fix(install): honor CLAUDE_CONFIG_DIR in always-on CLAUDE.md registration
The always-on registration wrote `~/.claude/CLAUDE.md` unconditionally, so
installing from a Claude profile relocated via CLAUDE_CONFIG_DIR mutated the
DEFAULT profile instead — the same fix _platform_skill_destination already
applies to the skill-copy path, missed for this path. The global branch now
writes to $CLAUDE_CONFIG_DIR/CLAUDE.md with a matching skill reference; env
unset/blank still falls back to ~/.claude. Refs #2694 (part 1; the version-stamp
half is unaddressed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 21:49:01 +01:00
safishamsiandClaude Opus 4.8 c2a676d215 fix(js): also shadow generator function-expression bindings; lock .tsx coupling (#2752)
Closes the gap #2752's title implies: a generator function EXPRESSION
(function*(k){}) parses as generator_function, which was in neither
_JS_DESCEND_TYPES nor the JS/TS function_boundary_types, so it still fabricated
an indirect_call to a same-named callable. Adds generator_function to both.
Adds a generator-FE regression test and a .tsx test that locks the
_TSX_CONFIG-by-reference coupling (untested before). Full JS/TS indirect_call
/calls regression re-run green (812 passed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 20:11:13 +01:00
imagineers-tylerandClaude Opus 4.8 3512585ed0 fix(js): shadow untracked function-expression bindings from indirect_call args
An inline/nested function expression's own params and locals were not folded
into the indirect_call shadow set, because function_expression was missing from
the JS/TS function_boundary_types even though walk_calls' closure-descend branch
already handles it. A bare reference to such a param, passed as a call argument,
fabricated an INFERRED indirect_call to an unrelated same-named callable. Adding
function_expression to the boundary sets routes it through the same shadow path
arrows use. Same family as the catch/arrow/loop/external-import (#2757) shadows.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 19:22:02 +01:00
safishamsiandClaude Opus 4.8 3460500fff perf(detect): skip the git ls-files probe when no .gitignore contributes (#2759)
#2766 ran `git ls-files` on every scan of a git repo. Gate it on .gitignore
actually contributing patterns beyond the explicit (.graphifyignore/--exclude)
set — with no .gitignore in play nothing can be gitignore-dropped, so the
tracked-file exemption is moot and an ordinary corpus pays no subprocess cost.
Adds a spy test asserting the probe is skipped without a .gitignore and runs
once with one. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 19:20:34 +01:00
NithishandClaude Opus 4.8 95ad0adcaa fix(detect): preserve Git-tracked files matched by a .gitignore pattern (#2759)
A file that is git-tracked but also matches a .gitignore pattern (a committed
file later added to .gitignore, or a force-added one) was silently dropped from
the corpus, even though git never un-tracks such a file — so the graph lost
real, shipping source. detect now runs `git ls-files` once per scan, keeps a
set of tracked-file identity keys plus their ancestor directories (so a
git-only-ignored parent dir is not pruned before the walk reaches the tracked
file below it), and exempts tracked paths from .gitignore. .graphifyignore and
--exclude stay authoritative, and a non-git corpus is unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 19:09:57 +01:00
safishamsiandClaude Opus 4.8 e6b0efb66b fix(cpp): guard empty-normalize collapse for punctuation-only test names (#2594)
The #2751 recovery minted node ids via _make_id(stem, name); a punctuation-only
name (TEST_CASE("***")) normalizes to empty, collapsing onto the bare file-stem
id — colliding with the file namespace and swallowing every later such test
under one id via seen_ids (#1899). Detect the collapse and fall back to a stable
line-positional id so each stays distinct. Adds a regression test (also covers
SCENARIO) and the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 17:24:35 +01:00
Ousama Ben YounesandClaude Opus 4.8 54b3b78955 fix(cpp): recover doctest/Catch2 string-named TEST_CASE nodes (#2594)
doctest/Catch2 register tests with a string-literal name (TEST_CASE("...")),
which tree-sitter-cpp parses as an ERROR node, so every test function was
silently dropped. Adds a line-anchored regex fallback that appends one code
node per top-level TEST_CASE/TEST_CASE_TEMPLATE/SCENARIO plus a contains edge
from the file node, mirroring the Groovy Spock fallback.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 17:17:29 +01:00
safishamsiandClaude Opus 4.8 6f1cbe5fda test(affected): cover outside-root clean-miss and non-out-dir graph layout (#2706)
Adds the two gaps the deep-dive flagged: an absolute seed outside the derived
root must miss cleanly (not resolve to a same-basename in-root node), and a
--graph pointing at a graph.json NOT under graphify-out uses the else gp.parent
fallback root. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 17:16:53 +01:00
Ousama Ben YounesandClaude Opus 4.8 243a1801f1 fix(affected): resolve an absolute-path seed via the graph-derived root (#2706)
affected anchored an absolute-path seed to Path.cwd(), so running it from
anywhere but the repo root made relative_to(cwd) raise and the query fell
through unmatched, silently returning nothing. It now derives the repo root
from the graph's own location (<root>/graphify-out/graph.json) and anchors the
seed there, so an absolute seed resolves regardless of cwd. Composes with the
#2707 relative-seed fix (root defaults to cwd for other callers).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 17:12:16 +01:00
safishamsiandClaude Opus 4.8 e5d662eb63 test(js): cover dynamic-require skip and no-double-count for lazy requires (#2700)
Adds the two invariants the deep-dive flagged: require(variable) must not
fabricate an edge, and a module-scope require still yields exactly one
imports_from edge (guards the module-vs-body pass partition against future
double-counting). Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 16:46:04 +01:00
rajanpanthandClaude Opus 4.8 259bb6acfb fix(js): retain lazy CommonJS require dependencies (#2700)
A require(...) written inside a function body (the canonical lazy-require idiom
for breaking circular deps) produced no edge at all, while the identical require
at module scope resolved as EXTRACTED imports_from/imports edges. walk_calls now
feeds nested require declarations to the same _require_imports_js routine,
attributing the edge to the enclosing callable; dynamic require(var) is still
skipped and no bare local node is minted (#1077 scope guard).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 16:44:34 +01:00
safishamsiandClaude Opus 4.8 94c2050f93 test(js): cover external-import-shadow vs same-named local callable (#2757)
Adds the collision case the fix must survive: a name both imported externally
and defined as a callable in another corpus file. The external use must not
fabricate a cross-file indirect_call while a genuine local by-name reference
still binds. Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 16:43:11 +01:00
phudayyyandClaude Opus 4.8 ceeafb05ce fix(js): an import from outside the corpus shadows indirect_call resolution (#2757)
An identifier bound by an import whose target resolves OUTSIDE the scanned
corpus (e.g. a lucide-react icon) is now shadowed within the file, so using it
as a value no longer fabricates an INFERRED indirect_call onto an unrelated
same-named callable elsewhere in the corpus. The internal-vs-external decision
is delegated to the existing import resolver, so a relative/in-corpus import
still resolves to its real target. Same shadow family as #2241/#2568/#2685.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 16:42:12 +01:00
safishamsiandClaude Opus 4.8 774b12fe9e docs(readme): add YouTube channel badge to the social links
Adds a YouTube badge linking to https://www.youtube.com/@graphifylabs in both
the header badge row and the footer social block, alongside Discord/LinkedIn/X.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-15 16:39:46 +01:00
safishamsiandClaude Opus 4.8 9e2387f3e8 fix(ocaml): don't bind a qualified external call to a same-named local def
A qualified call `M.f` where `M` is not a module defined in the same file is
an external-library call (e.g. Hardcaml's `Reg_spec.create`, `Scope.create`).
Resolving it by bare last name bound it to a same-named local `let f`,
producing a false `calls` edge and a `create -> create` self-loop when the
caller was that local `f`. Now: track locally-defined module names; a
qualified call whose root module is not local and whose bare name collides
with a local def is kept as a distinct external target (stub labelled by the
full path), so it neither self-loops nor collapses onto the local def.
Unqualified calls and calls into a locally-defined module still resolve
locally, and cross-file `Geo.area` still collapses onto another file's `area`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 21:09:32 +01:00
safishamsiandClaude Opus 4.8 7281f27eac chore: bump to 0.9.43
Cuts a 0.9.43 section (OCaml extractor + #2652/#2653/#2596/#2597/#2655) and
dates the released 0.9.42.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 15:36:55 +01:00
safishamsiandClaude Opus 4.8 3429264799 feat(js): extend nested-function extraction to arrow components/callbacks (#2653)
#2705 fixed `function` nested in a `function`, but the React idiom that
motivated the issue -- a function declared inside an arrow-defined component
(`const Panel = () => { function handleClick(){} }`) or an arrow callback
(`useEffect(() => { function h(){} })`) -- was still missed: the main walk
never recurses into arrow bodies and the scan bailed at the arrow boundary.

Refactors the inline scan into a module-level _scan_js_nested_function_
declarations that also descends through arrow / function-expression bodies
(attributing nested declarations to the nearest enclosing named scope), and
invokes it from the const-arrow branch of _js_extra_walk. Nested bodies join
function_bodies, so the central _tracked_body_ids guard prevents double-walk.
Adds tests for both arrow idioms.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 15:02:15 +01:00
himanshupatro-334andClaude Opus 4.8 b401e8c29f fix(js): extract nested function declarations (#2653)
A named `function`/`generator_function` declaration nested inside another
function body now gets its own node, a `contains` edge from the enclosing
function, and its own call-attribution scope, so calls made from inside such a
function are no longer dropped as dangling.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:49:56 +01:00
safishamsiandClaude Opus 4.8 f52b8dbc69 harden(bash): stop .. source paths escaping the corpus tree (#2596)
The #2690 form-3 (`$(dirname …)`) branch had no `..` guard and the tracked
form-4 branch let `..` walk past the base to an arbitrary host path, so a
hostile corpus could make the extractor stat and record an out-of-tree file
(source "$(dirname "$VAR")/../../../../etc/passwd") — a corpus-side info leak,
since resolve_bash_source_edges only filters *resolved* cross-file edges, not
the extractor's own edge/probe. Adds a lexical _within_tree gate: form 3
rejects `..` outright (its base is a guess), and a tracked form-4 base may
reach a sibling via $VAR/../lib but cannot escape past base.parent. Adds two
traversal-rejection tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:48:56 +01:00
Josh HudsonandClaude Opus 4.8 b345dc4993 fix(extractors/bash): resolve dirname cmdsubst and dotdot suffix in source paths (#2596)
Extends variable-built `source` resolution to two path-construction forms
that were silently dropped: `source "$(dirname "$VAR")/lib/x.sh"` (command
substitution in the source argument) and `source "$VAR/../lib/x.sh"` (a
`..` suffix when the leading var is a tracked var_bases entry).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:48:35 +01:00
safishamsiandClaude Opus 4.8 d79520198d harden(export): widen dedup reserve to 5 and add multibyte budget test (#2655)
Widens _SLUG_SUFFIX_RESERVE/_DEDUP_SUFFIX_RESERVE from 4 to 5 so a four-digit
collision suffix (_1000..) can't push a truncated stem past MAX_PATH; the
suffix is technically unbounded but 5 chars covers ~10k identical stems. Adds
an end-to-end test that CJK labels at a tight budget stay within the window,
keep their non-ASCII characters, and produce links that resolve on disk.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:26:12 +01:00
abhay-codes07andClaude Opus 4.8 b7c709e13d fix(export): budget export filenames against the destination path, not just NAME_MAX (#2655)
Adds paths.stem_filename_budget(output_dir, *, reserve, limit=200) and threads
it through the Obsidian and wiki exporters so a filename stem is budgeted
against the whole Windows MAX_PATH window (drive + dirs + name + NUL), not
just the per-component 200-char NAME_MAX cap. On POSIX the helper returns the
limit unchanged, so existing vaults stay byte-identical; on Windows a long
output directory no longer pushes the total path over MAX_PATH and aborts the
export mid-write.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:24:01 +01:00
safishamsiandClaude Opus 4.8 6c29d988bd test(wiki): make the bracketed-label parity case non-vacuous (#2597)
The parity check keyed on the whole [display](target) pattern, so a link
whose display text contains brackets (Array[T] Models) never matched and the
bracket case asserted nothing. Key on the ](target) boundary instead — wiki
targets contain no ) or whitespace — so bracketed labels are actually checked.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:21:34 +01:00
abhay-codes07andClaude Opus 4.8 fc00f673c6 fix(wiki): make a link target the article filename verbatim, not its percent-encoded twin (#2597)
The wiki exporter wrote each article as {slug}.md but emitted the link as
quote({slug}.md), so any label with ( ) & # or non-ASCII produced a
percent-encoded target that names no file on disk. Removes the quote() fork
and hardens _safe_filename so the slug is URL-safe by construction; the link
and the on-disk filename are now the same string.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:20:04 +01:00
safishamsiandClaude Opus 4.8 bd1ede9584 test(extract): cover per-symbol fan-out and module-top-level drop for #2652
Adds two regression tests on top of #2684: each referencing symbol gets its
own INFERRED uses edge (guarding against the old every-class fan-out and
against source collapse), and a true module-top-level reference emits no edge
(the deliberate drop). Also adds the CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:18:54 +01:00
Ousama Ben YounesandClaude Opus 4.8 c08d9afa93 fix(extract): attribute cross-file INFERRED uses edges to the referencing symbol (#2652)
Rewrites Pass 2 of the Python cross-file import resolver so an INFERRED
`uses` edge anchors on the symbol whose body actually references the
imported name (a class as a unit, or a module-level function) at the real
reference line, instead of fanning out from the import statement line to
every class in the importing file.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:17:45 +01:00
safishamsiandClaude Opus 4.8 0302bfa7af feat(ocaml): add OCaml .ml/.mli extractor (optional tree-sitter-ocaml extra)
New graphify/extractors/ocaml.py handles both the implementation grammar
(language_ocaml, .ml) and the interface grammar (language_ocaml_interface,
.mli). Emits nodes for modules, top-level/module-level values and functions,
types and their variant constructors; edges for defines/contains, open ->
imports_from, and application -> calls. Qualified paths (Geo.area) resolve to
the final value name, not the module qualifier; local let ... in bindings do
not mint nodes or steal call attribution. Cross-file open/call targets are
sourceless stubs so the corpus rewire collapses them onto the unique real
definition (no #1402 sourced-stub leak).

Wired into detect.py (CODE_EXTENSIONS), extract.py (dispatch +
_EXTRA_FOR_EXTENSION), pyproject.toml ([ocaml] extra + all + dev dep), and
README. Adds tests/test_ocaml.py (behind importorskip).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 14:17:07 +01:00
safishamsiandClaude Opus 4.8 7fe58b0b0f docs(changelog): add #2463/#2466/#2465/#2453/#2449/#2408 to the 0.9.42 section
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-13 14:33:56 +01:00
safishamsiandClaude Opus 4.8 40316d19e7 docs(detect): cross-link _MTIME_COARSE_S to cache.py's granularity constant (#2466/#2612)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-13 14:21:56 +01:00
Kai a2a9137d05 fix(detect): re-queue a same-tick same-length rewrite in incremental runs (#2466) 2026-08-13 14:21:22 +01:00
Kai c1f39954e3 fix(detect): skip non-regular files so a FIFO can't hang extraction (#2463) 2026-08-13 14:20:36 +01:00
Aryan 48fbe30ebc fix(build): exclude global MCP ids from legacy-id detection (#2408) 2026-08-13 14:17:42 +01:00
JAESOL SHIN a4e8446479 fix(html): trace hyperedge perimeter in convex-hull order (#2449) 2026-08-13 14:17:42 +01:00
Benjamin S. Leveritt 613c45cc7e fix(install): make the staged skill bundle writable so a read-only package installs (#2453) 2026-08-13 14:17:42 +01:00
Kai 5e4ab1dfa0 fix(manifest): capture package version in the apm.yml fallback parser (#2465) 2026-08-13 14:17:41 +01:00
safishamsiandClaude Opus 4.8 ded1feb88a chore: bump to 0.9.42
Correctness (#2685 loop-binding shadow, #2699 provenance, #2707 affected
seed, #2688 py subpackage imports, #2602 sql grammar, #2683 cache
integrity, #2682 report basename) + Windows portability/docs batch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-13 13:36:32 +01:00
Ousama Ben Younes b3ca490408 fix(report): use a portable basename in the GRAPH_REPORT header (#2682) 2026-08-13 13:30:24 +01:00
Ousama Ben Younes 5d8d6113db fix(cache): surface corrupt semantic cache entries instead of silently missing (#2683) 2026-08-13 13:30:24 +01:00
Ousama Ben Younes a30b56e2df fix(sql): distinguish a broken tree-sitter-sql grammar from a missing one (#2602) 2026-08-13 13:30:24 +01:00
Ousama Ben Younes 51cf1481b6 fix(python): resolve relative subpackage imports to their __init__ (#2688) 2026-08-13 13:30:24 +01:00
phudayyy a05b4084d9 fix(affected): resolve a seed given as ./relative or absolute path form (#2584 follow-up) 2026-08-13 13:30:24 +01:00
C0KERNEL cc0ee60c40 fix(export,cli): stamp graph provenance from the analysed repo, not the shell cwd (#2534 family) 2026-08-13 13:30:24 +01:00
Ousama Ben Younes a995921026 fix(js): shadow for...of / for...in loop bindings from indirect_call args (#2568 family) 2026-08-13 13:30:24 +01:00
rajashidattapy c1e41ea90e docs: refresh ARCHITECTURE.md module table + add a doc-parity test (keeps the #2558 'an' fix) 2026-08-12 20:57:39 +01:00
nelsondeleonc-source 39beeb9b4b docs: fix article typo (an extract_<lang>) in ARCHITECTURE.md 2026-08-12 20:56:28 +01:00
Redzwan Mutalib 28aaf20197 docs: document Windows test prerequisites in the README 2026-08-12 20:56:28 +01:00
Redzwan Mutalib 6b40338d96 docs: document CI parity checks in the README 2026-08-12 20:56:28 +01:00
rajashidattapy 5cc20a4811 test: skip the unreadable-dir detect test on non-POSIX / as root 2026-08-12 20:56:28 +01:00
rajashidattapy cdf1f65656 test: probe-and-skip symlink tests where symlink creation is unavailable (#2642) 2026-08-12 20:56:28 +01:00
rajashidattapy 243f3e32c1 test(hooks): stop argv mangling the shell-arg verdict test on Windows (#2126) 2026-08-12 20:56:28 +01:00
rajashidattapy 0df2a701a5 fix(paths): clear read-only bit before unlinking the atomic-write temp on Windows (#2622) 2026-08-12 20:56:28 +01:00
rajashidattapy 1aab181d15 test: Windows path portability in tests; llm emits POSIX source_file to the model (#2620) 2026-08-12 20:56:28 +01:00
safishamsiandClaude Opus 4.8 e4bfd2ad1a docs(changelog): add #2663/#2601/#2661/#2457/#2674 to the 0.9.41 section
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-12 14:22:46 +01:00
Arthuro0103 ee2fbf954b fix(benchmark): guard against a node with a None label (#2674) 2026-08-12 14:20:21 +01:00
rohit-jsfreaky 8be72ef7bf fix(js): stabilize unresolved local import target ids (#2457) 2026-08-12 14:20:21 +01:00
Ben Younes c285a94d45 fix(extract): resolve prefixed PHP use-imports to their target (#2661) 2026-08-12 14:20:21 +01:00
Ben Younes b645a3a7f1 fix(serve): suppress the query truncation banner when no nodes were cut (#2601) 2026-08-12 14:20:21 +01:00
Ben Younes 4730ed9abb fix(watch): refuse a shrink caused by an extractor failure during update (#2663) 2026-08-12 14:20:21 +01:00
safishamsiandClaude Opus 4.8 26c034a696 docs(changelog): add #2627/#2632/#2635/#2634 to the 0.9.41 section
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 20:11:19 +01:00
rohit-jsfreaky cd04bf1bf3 fix(csharp): extract members inside #if preprocessor blocks (#2634) 2026-08-11 20:09:59 +01:00
rajashidattapy bedf32e07c fix(wiki): count each incident edge once in the audit trail (#2635) 2026-08-11 20:09:59 +01:00
rajashidattapy c838df83c5 fix(cache): re-anchor CWD-relative source_file on warm cache hits (#2632) 2026-08-11 20:09:59 +01:00
rajashidattapy ce942e144f fix(extract): canonicalize source_file to POSIX separators (#2627) 2026-08-11 20:03:55 +01:00
safishamsiandClaude Opus 4.8 33283f5356 chore: bump to 0.9.41
Fixes: #2517 (JS/TS catch-binding indirect_call), #2434 (Cargo.toml
manifest), #2468 (scan-root vs parent .gitignore + NFC follow-up), #2482
(API rationale prompt).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 17:36:27 +01:00
safishamsiandClaude Opus 4.8 80ce81ef31 fix(detect): NFC-normalize the recomputed scan-root-relative path (#2468 follow-up)
The #2475 fix recomputed the match path against the explicit scan root but
skipped the _nfc() normalization rel_anchor gets, so an NFD-named path
could miss a parent ignore pattern under the #2544 NFC-matching regime.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 17:06:53 +01:00
Jaeung Jang 33d217c02f fix(extract): shadow JS/TS catch bindings from indirect_call args (#2568 family) 2026-08-11 16:54:35 +01:00
himanshupatro-334 cb06a7decc fix(detect): preserve explicit scan roots vs parent unanchored .gitignore (#2468) 2026-08-11 16:54:35 +01:00
Ben Younes 638d9e2c37 fix(ingest): recognize Cargo.toml as a package manifest (#2434) 2026-08-11 16:54:35 +01:00
himanshupatro-334 91e43c7678 fix(llm): add rationale guidance to the API extraction prompt (#2482) 2026-08-11 16:54:35 +01:00
safishamsiandClaude Opus 4.8 26128abf69 chore: bump to 0.9.40
Batch of correctness/determinism fixes (#2610/#2599, #2612, #2618, #2614,
#2582, #2467, #2544, #2493, #2568-followup, #2605, #2608, #2598).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 15:30:34 +01:00
safishamsiandClaude Opus 4.8 6926f7ac00 fix(export): make graph.html title marker-truncation take precedence (#2598 follow-up)
The #2600 title helper preferred a cwd-relative label, which still leaks
host/user path segments when the graph is built from a directory above the
project. Keep from the graphify-out / GRAPHIFY_OUT marker onward first
(portable in every case); fall back to cwd-relative only for a fully custom
output path with no marker.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 15:19:54 +01:00
michaelxer fe67768b93 fix(export): use portable path in graph.html document title
The <title> previously embedded str(output_path), so Windows absolute
host paths leaked into a tracked artifact (regression of #433, #2598).

Prefer a cwd-relative label, else keep from the graphify-out segment
onward, else the filename only.
2026-08-11 15:18:33 +01:00
Jaeung Jang d06bab0629 fix(extract): shadow a single unparenthesised arrow parameter from indirect_call args
tree-sitter gives an arrow with one unparenthesised parameter a `parameter`
field (singular) and no `parameters` list node, so `_js_local_bound_names`
never saw it: `x => sink(x)` bound nothing, and `x` read as a by-name
reference to any same-named callable in the corpus, fabricating an
indirect_call edge (INFERRED, 0.8).

The parenthesised form was always handled, so `(x) => …` and `x => …`
behaved differently. Same singular/plural trap as `catch_clause.parameter`.

Strictly subtractive on real code: +0/-88 indirect_call edges over 5,402
files of node_modules, +0/-98 over a 6,000-file mixed corpus.
2026-08-11 15:18:33 +01:00
rohit-jsfreaky 3c843bd0cc fix: skip Obsidian vault metadata directories 2026-08-11 15:18:33 +01:00
Bruno Santanna 5ffaaa606a fix(detect): normalize Unicode so accented ignore patterns match on macOS
An ignore rule naming a directory with an accent silently does nothing on
macOS, and the files it was meant to exclude get scanned anyway.

macOS (APFS/HFS+) returns filenames in NFD — "ç" comes back as "c" + U+0327
COMBINING CEDILLA — while editors write ignore files in NFC, where the same
"ç" is the single codepoint U+00E7. The two render identically and compare
unequal, so `fnmatch` never matches and the pattern is a no-op.

Found in a real repo: a `.graphifyignore` containing `Orçamento/` failed to
exclude that directory, and 9 client contract PDFs were picked up for semantic
extraction — i.e. queued to be sent to an LLM — despite an explicit rule
against it. The failure is silent: there is no warning, and the only symptom
is a file count that does not match what you expect. A user who does not
count would never know. That is what makes this worth fixing rather than
documenting: the rule appears to work.

Both sides are now normalized to NFC before matching, at three boundaries:
the pattern (in `_parse_gitignore_line`, so it covers .graphifyignore,
.gitignore and $GIT_DIR/info/exclude alike) and the two path forms used in
`_is_ignored` (`target.name` and the anchor-relative path).

NFC is already the form Linux and Windows produce, so this is a no-op there
and only repairs the macOS mismatch.

Tests: two regression tests cover both directions (NFC pattern vs NFD path on
disk, and the reverse); both fail before this change and pass after. A third
asserts ASCII patterns are unaffected, so the normalization cannot regress
existing behavior.

Full suite: 3833 passed. The 13 failures in tests/test_terraform.py are
pre-existing on a clean upstream checkout (optional tree_sitter_hcl not
installed) and unrelated to this change.
2026-08-11 15:18:33 +01:00
sean-soomgo 1fdd11fa76 fix(serve): resolve punctuated and non-ASCII node ids in _find_node (#2467)
`_find_node_tiers` builds two normalizations of the query: `term`, which
tokenizes on \w+ so punctuation becomes a space, and `norm_query`, which
keeps it. The exact tier compared the node id against `term` only, so
`term == nid_lower` was false for every id carrying punctuation, and
`norm_query` — which already held the right form, and is even one of the
two trigram needles — was never compared against the id at all. Comparing
`norm_query` to the folded id closes that half.

It does not reach ids carrying non-ASCII text. `_node_search_text`
indexed the id raw while every query path folds through
`_strip_diacritics`, which NFKD-decomposes. Hangul syllables decompose
into conjoining jamo, and jamo have combining class 0, so they survive
the combining-character filter: the needle's trigrams and the posting's
trigrams were disjoint, `_trigram_candidates` returned a candidate list
without the node, and it was dropped before any predicate ran. The
folded id is now part of the indexed text.

Both halves are additive. An id that resolved before resolves to the
same node; only ids that previously resolved to nothing can now resolve.
The folded field is appended, and only when the fold actually differs,
so field positions do not move and an all-ASCII graph indexes byte for
byte what it indexed before. Index build, median of 7 runs:

    graph                     trigrams   postings   build
    5k all-ASCII     before        1723     238876    96ms
    5k all-ASCII      after        1723     238876    97ms
    17k real         before       33442    2311784   998ms
    17k real          after       33490    2312462   990ms
    5k half-Hangul   before        1735     256381   116ms
    5k half-Hangul    after        1739     266381   124ms

The real graph is the 17269-node one measured below; 354 of its ids are
non-ASCII, so the index grows 0.03% and the build stays inside run-to-run
noise. The half-Hangul row is a deliberate worst case — every other node
id Korean — and even there the cost is paid once per graph load, on a
graph where id lookup previously returned nothing at all.

On a real 17269-node graph with Korean source filenames, every node id
fed back to itself, full population:

    id class                  total   before   after
    contains punctuation       2326        0    2326
    contains Hangul             354        0     354
    ASCII, no punctuation     14589    14589   14589

And every query that graph can produce — all 17269 ids plus all 16537
distinct labels — through `_find_node_tiers` on both variants in one
process: 31126 identical, 2680 that returned nothing before and resolve
now, 0 with a changed first result, 0 lost, 0 with a widened exact tier.
Every difference is a query that previously returned nothing.

Left alone deliberately: `_score_query` compares the id raw in the same
way, so `path` and query seeding still cannot take a punctuated id, and
the prefix tier also matches ids against `term` only. Both are behaviour
changes beyond this defect rather than part of it.

One note for the regression tests: the non-ASCII case needs a graph of
at least ~10 nodes. `_trigram_candidates` bails out to a full scan when
`min(present) > int(n * 0.10)`, so on a small synthetic graph the index
path is never taken and the test passes with the defect still present.
2026-08-11 15:18:33 +01:00
hjotha 36b47ba25d fix(export): stabilize graph JSON collection order 2026-08-11 15:18:33 +01:00
rajashidattapy 21e75cfae4 fix(normalize_id): address idempotency issues with Turkish identifiers and update related test cases 2026-08-11 15:18:33 +01:00
rajashidattapy d3d9ef8340 fix(normalize_id): ensure idempotency and valid character output by adjusting casefolding order 2026-08-11 15:18:33 +01:00
safishamsiandClaude Opus 4.8 4b76ee127f fix(extract): gate the #2551 partial-parse warning on plausible symbol loss (#2610, #2599)
The 0.9.37 #2551 warning fired on valid TypeScript/TSX: tree-sitter-typescript
sets root.has_error on tiny fully-recovered errors (a `&` in a JSX string
attribute; a semicolon-less `in_*` interface member) that still extract every
symbol. The warning now fires only when recovery plausibly cost symbols — the
file yielded <=1 node, or a materialized ERROR region spans more than one line —
so the genuine Kotlin one-line-body (#2551) and Luau (#2520) cases still warn
while valid TS goes silent. Warning also prints a root-relative path.

Thanks @Sid-AutoWisdom and @atlasplatformu-ai.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 15:18:12 +01:00
BackendDev e4d132b7da fix(go): resolve qualified symbols by import path
Prevent package-qualified calls and types from collapsing onto unrelated bare-name symbols. Preserve Go import evidence, resolve internal packages exactly, canonicalize external type stubs, and support incremental resolution context.

Investigation, implementation, and regression fixtures prepared with OpenAI Codex.
2026-08-11 14:40:01 +01:00
SinghAman21 5fd4ab650b fix(python): avoid crash resolving overdeep relative imports 2026-08-11 14:40:01 +01:00
rajashidattapy 717b7b464a fix(paths): implement cross-platform absolute path detection for stored paths 2026-08-11 14:40:01 +01:00
rajashidattapy 26245b0841 fix(cache): implement racily-clean guard for file hashing; enhance stat signature checks 2026-08-11 14:40:01 +01:00
safishamsiandClaude Opus 4.8 50556baaea fix(extract): affected traverses in-function dynamic imports; Python member-call gating; ObjC resolver arm; bump to 0.9.39 (#2584, #2586, #2589, #2591)
These land together because they are interleaved in extract.py/engine.py.

#2584 (PR #2588, thanks @phudayyy): the 0.9.38 dynamic-import dedupe keyed
only on target, so an in-function import() suppressed the file-level edge
affected follows. Dedupe now keys on the importing file, emitting one
file-level dynamic_import edge per file/target while keeping the call-site
edge.

#2586 / #2417 (PR #2586, thanks @EZZEASY): a Python member call on an
untyped receiver (x.get(...)) no longer binds by name to a same-named
module function. walk_calls now defers non-self/cls/super Python member
calls to the evidence-gated resolver; super().method() still resolves.
Known trade: same-file x = Thing(); x.method() loses its evidence-free
edge (precision over recall, per #2553).

#2589/#2591 resolver arm (in _resolve_objc_member_calls): the @protocol
exclusion and the self.field/_ivar receiver resolution (paired with the
objc.py extractor changes committed separately).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-10 18:07:20 +01:00
safishamsiandClaude Opus 4.8 ba8254b3ab fix(objc): protocol not a receiver type, category fold, property/ivar receivers (#2589, #2590, #2591)
#2589 (PR #2500): a @protocol declaration (labeled <Name>) is excluded from
the receiver-type index, so it no longer collides with a same-named class.
#2590 (PR #2501): a category/class-extension interface is keyed off the
base stem and folds into the base class instead of minting a duplicate
node.
#2591 (fresh): @property and ivar declarations are captured into a
per-class field-type table, and a message send to a self.field / _ivar
receiver resolves through it (bare field name only, so Foo.shared cannot
fabricate to a FooShared class). All hold the single-definition guard and
emit INFERRED.

Adapts PRs #2500/#2501 (thanks @xiongjianxu); #2591 fresh.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-10 18:06:50 +01:00
safishamsiandClaude Opus 4.8 978f87cb67 fix(watch): rebuild on a doc-only deletion batch so deleted docs are evicted (#2580)
graphify watch only rebuilt on a code-file event, so deleting only doc
files while watching flagged needs_update but evicted nothing until the
next code change. A batch containing any vanished path now triggers a full
reconcile rebuild (which evicts the deleted source); a surviving modified
doc still writes the needs-LLM flag. The general deleted-file leak was
already fixed in 0.9.10; this closes the live-watcher residual.

Thanks @angmeng.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-10 18:06:50 +01:00
safishamsiandClaude Opus 4.8 92274745ad fix(dedup): don't over-merge distinct same-file labels differing by a content word (#2576)
Fuzzy dedup compared same-file labels with prefix-weighted Jaro-Winkler, so
two distinct entities differing by one content word (asset contribution
flow vs asset consumption flow) cleared the threshold and one was lost. A
one-token difference is now judged on the differing tokens (any distinct
content word blocks; stopword/typo variants still merge), with a
same-length Damerau-Levenshtein typo escape. Genuine typo and
whitespace/case/punct variants still collapse. The #2532 collision path is
untouched.

Adapts PR #2587 (thanks @wilyan09007) with two hardening deltas.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-10 18:06:50 +01:00
safishamsiandClaude Opus 4.8 10ad921b42 fix: JS/Kotlin/Swift/SQL extractor correctness batch; bump to 0.9.38 (#2568, #2565, #2561, #2577, #2575)
These changes are interleaved across engine.py/extract.py by function, so
they land as one batch.

#2568 (thanks @imagineers-tyler): the 0.9.37 #2552 callback-body fix
unioned sibling closures' local names under the shared declaration, so a
local in one callback suppressed a real indirect_call in a sibling. Locals
are now scoped per body (keyed by body id, via walk_calls' extra_locals).
Restore-only, never fabricates; #2552 capture preserved.

#2565 (thanks @kskchaitanya1993): Kotlin property initializers — class,
top-level, companion, and `by lazy {}` — now seed call extraction, so
`val repo = createRepo()` produces a calls edge; literal initializers
produce none; FQ calls compose with the #2550 resolver.

#2561 (thanks @fakewaffle): Swift receiver typing now handles
`@Environment(Store.self)` (whitelisted; @Query/keypath/dotted skipped to
avoid a wrong edge) and in-corpus factory bindings via a marked concrete
return type; opaque/array/out-of-corpus returns stay unresolved.

#2577 (thanks @wilyan09007, PR #2579): the SQL extractor no longer emits a
reads_from edge to a CTE name. WITH names are scoped per query (a subquery
CTE no longer suppresses an outer real table of the same name), so a CTE
no longer mints a bare stub that binds to an unrelated same-named symbol.

#2575 (thanks @phudayyy, PR #2574): a dynamic `import('…')` inside a nested
function or at module scope now produces an edge, dynamic_import is
included in affected, and calls inside nested named functions are
collected; a dynamic import already captured as a deferred imports_from is
not double-counted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-09 23:19:08 +01:00
safishamsiandClaude Opus 4.8 09a34ad87a fix(update,llm): retry failed extractions; surface claude-cli envelope errors; bump to 0.9.37 (#2543, #2554)
#2543 (adopts PR #2546, thanks @michaelxer): a failed extraction is no
longer stamped in the incremental manifest as up-to-date, so graphify
update retries it instead of skipping it forever; a manifest already
poisoned by the old behavior is healed on the next run; genuinely
unchanged files are not re-processed. Extended to the watch save_manifest
paths too.

#2554 (adopts PR #2555, thanks @annieyii): the claude-cli backend now
inspects the stdout envelope for an is_error result (e.g. a rate limit
returned with exit code 0) and raises it on both the zero and non-zero
exit paths, instead of parsing it as an empty success and bisecting
against a live rate limit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-08 23:37:49 +01:00
safishamsiandClaude Opus 4.8 cfc6a75c86 fix(extract): TS member-call gating + Kotlin grammar match (#2553, #2552, #2526, #2550, #2551)
TypeScript (#2553, #2552, thanks @Earthfreedom):
- _resolve_typescript_member_calls matched a receiver type by name alone
  and emitted EXTRACTED, so a third-party import could bind to an unrelated
  local class of the same name. It now requires the matched type to be
  same-file or imported by the caller's file, and tiers table-inferred
  receivers to INFERRED.
- calls inside a callback passed to another call (const h = wrapper(arrow))
  were never walked; the callback body is now walked and attributed to the
  declaration, through the same import-gated resolution so it cannot
  fabricate edges. The #2553 gate lands with #2552 by design.

Kotlin (#2526, #2550, #2551; adapts PR #2531, thanks @Mustaqeem66;
reports from @spaceBrownie and @thomasrengot-hub):
- match the bundled tree-sitter-kotlin 1.1.0 import node and resolve each
  import to the real target node (imports were silently dropped), so
  genuine calls promote to EXTRACTED via import evidence;
- a fully-qualified call com.example.Foo.bar() now produces a calls edge;
- a file the grammar cannot fully parse (e.g. one-line class C { val x })
  now warns instead of silently extracting nothing, and declarations
  recovered inside an error span keep their enclosing class.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-08 23:37:32 +01:00
safishamsiandClaude Opus 4.8 3d19463484 fix(skill): make the Windows skill variant runnable on PowerShell; bump to 0.9.36 (#2528)
The Windows skill variant had a PowerShell Step 1 but its later steps came
from the shared core fragment as bash-only shell (cat-piped interpreter
invocations, rm -f, find -delete). The skillgen renderer now translates the
composed core to PowerShell for powershell-shell platforms (here-string
interpreter invocations, Remove-Item cleanup); POSIX skills are unchanged
and step / #2490 parity is enforced by a generator check. Not a regression
from 0.9.35 (skill files were unchanged between 0.9.34 and 0.9.35).

Thanks @tannermosher2015-debug.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-07 22:49:51 +01:00
safishamsiandClaude Opus 4.8 3c17238b4e fix(dedup): deterministic node-id collision rank, active over archived (#2532)
_collision_rank no longer falls through to raw lexical source_file order.
It now ranks by a lifecycle penalty (active over archived) computed on the
root-relative path, then a reversed-segment tie-break, so the winner of a
collision (e.g. plans/_done/x.md vs plans/in-progress/x.md) no longer
depends on ASCII filename order, absolute-vs-relative path form, or the
checkout directory name.

Active/archived idea from PR #2540 (thanks @michaelxer); the root-relative
and reversed-segment determinism is implemented here.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-07 22:49:25 +01:00
safishamsiandClaude Opus 4.8 22c41c1b23 fix(swift): cross-file extension no longer drops static/singleton calls (#2538)
swift_extensions[].nid is now remapped in the in-process id/sym remap
passes (not just the cache path), so a cross-file extension merges onto
its base type before call resolution; static Foo.bar() and singleton
Foo.shared.bar() calls resolve again. The merge candidate set is gated by
language family + type-def predicate so it never absorbs a same-named
type from another language.

Folds in PR #2539 (thanks @pawelo446).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-07 22:49:25 +01:00
safishamsiandClaude Opus 4.8 6ba0868228 fix(cli): surface four silent success-exit failures (#2534)
cluster-only warns when --backend/--model/--batch-size are ignored on the
label-reuse path; the community-label prompt key no longer collides with
the discard sentinel (an echoed key was silently dropped); tree --root
exits non-zero when it matches no source file instead of flattening the
tree; and cluster-only stamps built_at_commit from the analysed graph, not
the shell cwd. Also folds in the cluster-only refused-write guard from
PR #2522 (thanks @aniJani).

Thanks @elecnix for the report.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-07 22:49:25 +01:00
safishamsiandClaude Opus 4.8 9f25a3aaa1 fix(callflow,query): direction-aware callflow; drop relational-verb seed pollution; bump to 0.9.35
#2508 (thanks @Tomaskobel): callflow loads the graph directed and recovers
direction from _src/_tgt markers (consistent with the path fix), so
caller/callee columns are correct; indirect calls are now counted.
#2507 (thanks @filipechagas): relational-intent verbs (calls/uses/extends/
...) are excluded from the per-term seed guarantee, so a decoy matching
only the verb no longer becomes a traversal root, while a verb that is a
real symbol name can still be seeded on merit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-06 17:29:18 +01:00
safishamsiandClaude Opus 4.8 2320f2adc1 fix(update,java): prune newly-ignored files; stop external-annotation/local-class conflation (#2495, #2504)
#2495 (thanks @alisson-acioli): graphify update now evicts a file newly
added to .graphifyignore/--exclude even though it still exists on disk
(positive ignore-rule evidence), with .gitignore-driven eviction gated on
an explicit full update; unchanged in-corpus files and fail-closed #1795
cases are preserved.
#2504 (thanks @te7ina-honey): the Java type resolver runs before the
unique-label stub rewire and parks imported-but-external types on their
FQN, and cross-file import resolution checks the package, so a local
class and a same-named external annotation (e.g. Spring @Component) no
longer collapse into one node. In-corpus annotation resolution unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-06 17:29:18 +01:00
safishamsiandClaude Opus 4.8 b8d609732c fix(build_merge): revive the #479 shrink guard and fix absolute-path prune (#2497, #2446)
#2497 (thanks @sortakool): the shrink guard read the post-replace node
count and was skipped under prune_sources, so a broken partial re-extract
could silently destroy nodes. It now diffs the on-disk baseline by node
identity and refuses any loss from a source neither re-extracted nor
pruned this run, and reports replaced-node counts.
#2446 (thanks @AI-invest): prune_sources given absolute paths under a
non-standard layout now derives the scan root by suffix-matching stored
source paths, reports the accurate matched count, and warns instead of
saying 'already clean' when nothing matched.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-06 17:29:18 +01:00
safishamsiandClaude Opus 4.8 07b9143d4b fix(hyperedge,skill): merge/load hyperedge integrity + community labels; bump to 0.9.34
#2486 (thanks @adminwat): normalize dict-shaped hyperedge members to ids
(or drop with a warning) so a malformed hyperedge can't abort a completed
merge with a TypeError.
#2484 (thanks @sortakool; approach from @oleksii-tumanov's #1691):
merge-graphs relabels hyperedge member ids and ids with the repo prefix,
unions both inputs' hyperedges instead of clobbering, and writes both
persistence slots.
#2485 (thanks @sortakool): build_from_json reads hyperedges from the
top-level and nested slots; a full validation wipeout is reported loudly.
#2490 (thanks @PapiScholz): the skill Step-5 flow passes curated
community_labels to to_json, so graph.json ships community_name.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-05 22:08:29 +01:00
safishamsiandClaude Opus 4.8 94ebee18b7 fix(path): respect edge direction by default in path and shortest_path (#2487)
graphify path and the MCP shortest_path tool now build a digraph from the
true _src/_tgt directions and respect edge direction by default, so a
returned path no longer traverses edges backwards. --undirected (CLI) /
undirected=true (MCP) opt out; no directed path is reported plainly
instead of silently returning a reversed one.

Thanks @luliaz0601.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-05 22:08:29 +01:00
safishamsiandClaude Opus 4.8 e300587439 fix(csharp): scope receiver types per declaration so an untypeable rebind can't drop a true call (#2472)
Track C# receiver types per lexical declaration scope (byte ranges) and
resolve by the call's position, instead of a method-wide flat table that
poisoned a name on any None-typed binding. A typed static local-function
parameter now keeps resolving even when an out var reuses the name in the
enclosing body. Fixes a regression from #2346; #2299 cross-method
independence and field-conflict poisoning are unchanged.

Thanks @JensD-git for the bisect and repro.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-05 22:08:29 +01:00
safishamsiandClaude Opus 4.8 4e7e6b1f7e fix(extract,watch): C# assembly-aware partial merge, incremental edge preservation, extract crash recovery; bump to 0.9.33
#2411 (thanks @JensD-git): key the C# partial-class merge on assembly
(nearest ancestor .csproj/.fsproj/.vbproj) in addition to namespace and
name, so same-name partial classes in different assemblies stay distinct
while genuine partial halves within one project still merge. Fixes a
0.9.32 regression from #2332.

#2437/#2438 (thanks @aryanbonigala, builds on PR #2439): incremental
rebuilds no longer drop member-call and indirect_call edges from a
changed file into an unchanged target. Re-resolution now sees the
unchanged corpus (nodes, contains/method edges, and _callable markers,
which now persist to graph.json like _origin); edges to a genuinely
removed target are still evicted.

#2444/#2445 (thanks @Baziar, builds on PRs #2461/#2458): a
BrokenProcessPool triggers the sequential fallback instead of being
swallowed per future, a failed worker file is retried sequentially
rather than merged as empty, and a whole-pass AST failure on a fresh
build exits non-zero instead of writing a zero-node graph
(--allow-partial opts into a best-effort partial graph).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-05 01:41:12 +01:00
safishamsiandClaude Opus 4.8 a426d63414 feat(install): point users to the hosted platform after install
Print a one-time note about free early access to app.graphify.com at the
end of the install summary. Not shown on any other command.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-05 01:41:12 +01:00
safishamsiandClaude Opus 4.8 00efd6e796 fix(ruby): resolve compact/nested mixin targets, prevent phantom concern hub (#2302)
module Foo::Bar and nested module Foo; module Bar are canonicalized to
one fully-qualified label, and include/extend/prepend keep the full
constant path, so include Foo::Bar resolves. Mixin resolution is scoped
and lexical: a qualified external name (extend ActiveSupport::Concern)
no longer binds to a local module named Concern, while a genuine
in-corpus include Foo::Concern still resolves. Nested-declared classes
keep a last-segment index so typed-receiver calls (Processor.new) keep
resolving.

Adapts the approach from #1394 (thanks @FolatheDuckofDuckingburg) to the
post-refactor extractors/engine.py, with an added last-segment guard for
nested-class receiver resolution.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-01 15:36:17 +01:00
safishamsiandClaude Opus 4.8 7db00fcc1a chore: bump to 0.9.32; changelog for #2333/#2334/#2336/#2342/#2326/#2323/#2316/#2339/#2273/#2346/#2332/#2347/#2328
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-01 13:07:07 +01:00
safishamsiandClaude Opus 4.8 4a9613f726 fix(extract): C# inline-declared + partial-class receivers, Kotlin anonymous-object members (#2346, #2332, #2347)
- C# receivers declared inline via out-var / is / case / switch-arm patterns
  are now typed into the per-method table, so their member calls resolve (#2346).
- partial class halves across files now merge to one class node (new
  _merge_csharp_partial_class_nodes pass, mirroring the Swift-extension merge),
  so cross-half member calls resolve instead of splitting the class (#2332).
- Kotlin anonymous-object (object : Foo {}) members now get nodes, contains/
  implements edges, and their calls resolve (#2347).
All in-corpus only, never a wrong edge.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-01 12:21:04 +01:00
safishamsiandClaude Opus 4.8 97656fae2d fix(build,watch): tier-aware merge so re-extract keeps the other layer (#2333, #2334, #2336)
Node/edge ownership was keyed on source_file alone, but each file has an AST
tier and a semantic tier. A semantic-only re-extract deleted a doc's AST
headings, and a full _rebuild_code deleted document AST nodes. Add an
_is_ast_tier() predicate (with a source_location legacy fallback for the
unreliable _origin marker, #2334), backfill _origin on load so graphs
self-heal, make build_merge / merge_raw_extraction replace by (source_file,
tier) instead of source_file (coexist policy: an AST re-extract replaces only
AST nodes and keeps the semantic layer, and vice versa), and scope the
full-rebuild AST drop to sources actually regenerated (#2336) so a
semantic-backed doc keeps its AST layer. Deletion prune stays tier-blind.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-01 12:21:04 +01:00
Rishet Mehra c262478792 fix(watch): inherit the directed flag on the graphify update rebuild path (#2342)
The build_merge fix only covers the incremental path reached by
`graphify <path>`. `graphify update` rebuilds through _rebuild_code in
watch.py and never calls build_merge at all, so it still downgraded a
directed graph — which is the symptom named in the issue.

Two sites: the clustered path called build_from_json(result) with no
directed=, taking its directed=False default, and the --no-cluster path
built candidate_graph_data straight from the raw merged extraction, which
never carries a directed key, so the written file lost it entirely. Both
now inherit from existing_graph_data, defaulting to False when there is no
existing graph, matching build_merge's semantics.

_canonical_graph_for_compare normalizes a missing directed key to False so
an older graph.json without the key does not register as changed against a
candidate that now writes it explicitly.
2026-08-01 11:36:30 +01:00
Rishet Mehra e8436b411e fix(build): inherit the on-disk directed flag in build_merge (#2342)
build_merge took graph direction from its caller only, defaulting to
directed=False, and rebuilt with that default at build.py:1327 — discarding
the direction of the graph it had just loaded from graph_path. Since the
only call site (cli.py:3547) passes no directed=, every incremental
`graphify update` through the merge path silently returned an undirected
graph for a directed one.

_load_existing_graph now also returns the on-disk `directed` flag, parsed
from the JSON it already reads, and build_merge's parameter becomes
bool | None: None inherits that flag when a graph exists and falls back to
False when there is none, while an explicit True/False still wins.
2026-08-01 11:36:30 +01:00
stupidprogrammer4andClaude Opus 5 0c01da1932 perf(dedup): remove O(nodes x components) scan from remap construction
deduplicate_entities() rebuilt its remap table by re-scanning the whole
unique_nodes list once per merged union-find component, costing
O(nodes x components) -- roughly 137M membership checks on a 50k-node
corpus with 2.5k merged components, about a third of dedup wall-clock.

Build an id -> (position, node) index once and slice each component out of
it instead: O(members log members) per component.

The index carries the enumeration position, not just the node, because
_pick_winner() selects via min(), which returns the first minimum -- so
ties (equal chunk-suffix status and equal id length) are resolved by list
order. Sorting the group by id instead changed 179 of 2358 survivors on a
tie-heavy corpus. Sorting by position reproduces unique_nodes order
exactly, leaving survivors and edges byte-identical.

Benchmark, median of 5 runs:

    nodes    before     after   speedup
     5000     2.37s     2.29s     1.03x
    20000    10.58s     9.70s     1.09x
    50000    31.72s    21.92s     1.45x

Isolated remap loop at 50k nodes / 2.5k components: 6.838s -> 0.019s (370x).
Merge counts and output node counts are identical at every scale.

This does not address the pre-existing arrival-order dependence of the
component structure itself, which originates in the fuzzy-merge loop's
uf.find() short-circuit and is out of scope here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 11:36:30 +01:00
oleksii-tumanov 1b93c08697 fix(detect): prune only configured output path 2026-08-01 11:36:30 +01:00
Manoj21k 1cdbf48c57 fix(detect): gate coverage/ pruning on report artefacts (#2339)
"coverage" was an unconditional _SKIP_DIRS entry and _is_noise_dir matches
directory names at any depth, so a repo where coverage is a legitimate
package name lost the whole package from the graph — no warning, no
skipped_sensitive entry, nothing in the report. The failure is quiet in
the worst way: the package's dependents survive, so queries keep
returning plausible neighbours while the package itself has no nodes.

The entry's comment cites Vitest/Istanbul/nyc HTML reports (#870), but
the pruning is language-agnostic, so it also removes Python/Go/Rust
packages that happen to be called coverage.

detect.py has been fixed twice for this exact shape — #1666 gated a bare
snapshots/ on real .snap evidence, #2058 gated env/.env/*_env on real
virtualenv markers — so this applies the established pattern rather than
a new mechanism. _has_coverage_artifacts() mirrors _has_venv_markers():
same OSError guard, same "cannot verify, keep a possibly-real code dir"
contract when no parent is available. Evidence is a file a coverage tool
actually writes (lcov.info, coverage-final.json, clover.xml,
coverage.xml, cobertura-coverage.xml, jacoco.xml, .coverage, index.html)
or an lcov-report/ / html-report/ subtree, covering lcov, nyc/Istanbul,
coverage.py, JaCoCo and Cobertura.

lcov-report stays unconditional: it has no false-positive class, so
gating it would add filesystem probes for no benefit — the same split
#1666 made between the unambiguous __snapshots__ and the bare snapshots.
2026-08-01 11:36:30 +01:00
Rishet Mehra 1a7be303f5 test(watch): cover manifest location, anchor and commit provenance (#2316)
Seven tests, all red on 4fe1109 and green with the fix:

- location, parametrized over the clustered and --no-cluster write sites
- the unchanged-topology early return, the third write site; asserts the
  "No code-graph topology changes detected" line so the test cannot
  silently drift onto a different branch and keep passing
- the invoking project's own manifest survives an update of another
  project (the data-loss half)
- a relative target stores relative keys
- the resulting manifest is actually consumable by detect_incremental
- built_at_commit matches the target repo's HEAD, not the caller's
2026-08-01 11:36:30 +01:00
Rishet Mehra 144a3ff8fb fix(watch): write manifest.json to the target's graphify-out (#2316)
_rebuild_code computed the correct output dir as `out = watch_path /
_GRAPHIFY_OUT` and routed every artifact through it except the three
save_manifest calls, which omitted manifest_path= and fell back to
detect._MANIFEST_PATH — a module-import-time constant built from the
relative out_path("graphify-out/manifest.json"), so it resolved against
the process CWD. `graphify update <target>` therefore wrote the target's
manifest into the invoking project and left the target with none.

save_manifest also read-modify-writes that path and full-scan callers
pass scan_corpus (#1908 pruning), so the invoking project's own rows were
pruned as out-of-corpus and overwritten. Both projects lost their
incremental baseline, not just the target.

Anchor the manifest keys to watch_root at the same three calls. root=
previously followed project_root, which is CWD-derived for a relative
invocation, so `graphify update ../other` stored out-of-root files under
absolute keys and broke #777/#1964 portability. project_root itself is
left alone: the persisted graph deliberately rehomes source_file against
it across invocation styles.

Also pass cwd= to _git_head. Without it `git rev-parse HEAD` inherited
the caller's directory, stamping the invoking repo's commit into the
target's graph.json built_at_commit (cf. #2081).
2026-08-01 11:36:30 +01:00
Rishet Mehra 875c7df8f6 fix(query): render every edge between visited nodes, not just traversal edges
`graphify query` returned the right nodes but dropped real edges between them.
Both traversals recorded an edge only when it discovered an unvisited
neighbour, so the result was a traversal tree rather than the induced subgraph
over the node set the query reports.

`_bfs` marks every seed visited before the loop starts, so an edge between two
seeds could never be recorded — the reported symptom, where both endpoints
render and the edge between them does not. It drops ordinary cross-edges and
hub-adjacent edges for the same reason.

`_dfs` needed the same completion for a narrower case. It appends on push
rather than on visit, so it already captured seed-to-seed and cross-edges; an
exhaustive search over every connected four- and five-node graph found no miss.
Its one gap is an edge between two non-seed hubs, where the hub guard means
neither endpoint is ever expanded and so neither records it.

The new `_complete_induced_edges` runs at the end of both. It scans only edges
incident to the visited set, so cost tracks the subgraph rather than the whole
graph. A visited hub is rescanned in full, which is unavoidable: a hub-to-hub
edge is exactly the case `_dfs` misses. Placing the pass inside the traversals
rather than at the call site binds it to the context-filtered `traversal_graph`
by construction, so a relation the user filtered out cannot reappear.

Dedup keys on the ordered pair for directed graphs and the unordered pair
otherwise: on a DiGraph `u->v` and `v->u` are distinct edges (mutual recursion,
circular imports) and collapsing them would drop a real one. Parallel edges on
a multigraph collapse to one entry, matching the renderer, which already shows
only the first. Self-loops are skipped, since no traversal ever recorded one
and surfacing recursion edges is a separate output change.

Traversal edges keep their discovery order; completions are appended after.

Closes #2323
2026-08-01 11:36:30 +01:00
Rishet Mehra a2dc3d9ce2 fix(build): coerce non-string node ids so a numeric id cannot abort the build
A backend can emit {"id": 10} where the schema says {"id": "10"}. Every id
consumer downstream assumes str, so one numeric id aborted the whole run at
the final merge step, after the full extraction had already been paid for.

There are three crash sites, not the one in the report:

  - dedup._pick_winner's _CHUNK_SUFFIX.search(n["id"]) raises
    "expected string or bytes-like object, got 'int'" (the reported
    traceback), but only when the node lands in a duplicate or fuzzy group
  - build_from_json's sorted(node_set) raises "'<' not supported between
    instances of 'str' and 'int'" for a lone node with nothing to dedup
  - the same sort, reached via the fuzzy-group path

A str() cast at the reported line therefore does not fix the common case:
a single numeric-id node never reaches _pick_winner. Coerce at ingest
instead, in _coerce_non_string_ids, called from build() before dedup (which
keys on id) and from build_from_json (the direct entry used by cli.py,
watch.py and diagnostics.py, which never goes through build()). The nested
call on the build() path is an idempotent no-op.

Edge endpoints and hyperedge members are coerced alongside the nodes on
purpose: coercing node ids alone would renumber 10 to "10" and leave every
edge pointing at the vanished 10, trading a loud crash for a silently
disconnected graph. The legacy from/to aliases are included because dedup
reads them directly (#803).

Only bool-free numeric scalars are coerced. A None, list or dict id is left
for validate_extraction to report, since str(None) == "None" would fabricate
an id that no edge references.

Closes #2326
2026-08-01 11:36:30 +01:00
safishamsiandClaude Opus 4.8 3b243d644e docs(readme): early-access CTA at the top + refresh the waitlist line to app.graphify.com
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-01 01:52:47 +01:00
safishamsiandClaude Opus 4.8 4fe11092cc chore(release): 0.9.31
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 19:15:26 +01:00
safishamsiandClaude Opus 4.8 5d1d1031f2 chore: bump to 0.9.31; changelog for #2308/#2299/#2324/#2309/#2266/#2313/#2233/#2319
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 18:44:09 +01:00
safishamsiandClaude Opus 4.8 50be9dcd36 fix(cli): recover edge direction from _src/_tgt in path and explain (#2309)
graphify path decided hop direction from the persisted source/target order,
so a link stored in flipped order (pre-#563 graphs, raw dumps, merge-driver
output) printed backwards; explain had the same defect, and the query/merge
load shims clobbered in-file _src/_tgt markers. All now honor _src/_tgt (the
build-side direction truth), falling back to arc order for markerless files.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 18:38:58 +01:00
safishamsiandClaude Opus 4.8 c8163d8338 fix(sql): sourceless stubs + identifier normalization for cross-file table references (#2324)
SQL references to a table defined in another file (e.g. prisma m2 -> m1) were
minted as node-less absolute-stem ids under the referencing file, leaking the
scan path and losing the FK. They now mint a sourceless bare-name stub (Go
#1402 pattern) that _rewire_unique_stub_nodes collapses onto the real table.
Also normalize identifiers (strip quotes, lowercase, bare-name alias) on both
table_nids writes and reference lookups, so a quoted definition ("public".
"users") resolves an unquoted reference (public.users) in-file instead of
stubbing — which also fixes pg_introspect's reconstructed-DDL views/FKs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 18:38:58 +01:00
safishamsiandClaude Opus 4.8 f99f8d70c8 fix(csharp): per-method receiver typing so cross-method name reuse stops dropping true calls edges (#2299)
The C# receiver-type table was per-FILE and poisoned a name on any
conflicting/untypable rebind anywhere in the file, so `var item = items[i]`
in one method silently deleted the true calls edge in another method where
the same name was a typed parameter (~2.3% of calls lost, per the reporter).
Ported C# to a per-method table mirroring the Java resolver (per-class field
scope + method params/locals, method-local poisoning only) and retired the
file-wide table. The namespace resolver, ambiguity bail, and inherits-chain
guards are unchanged, so the no-wrong-edge bar holds.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 18:38:58 +01:00
0bLoM 2ca565ac1a fix: explain no longer resolves an ambiguous name to an arbitrary file
`_find_node` ranks matches but never reports that a tie was broken, so callers
taking `matches[0]` present one arbitrary file as the answer. Two workspaces
that each define `MetricsPort` put both nodes in the same `exact` tier,
separated only by `G.nodes()` iteration order — reorder the graph and the same
query answers with a different file, equally confidently.

`affected` already declines this via `resolve_seed()` returning None, and
`path` warns when the top two scores are within 10%. Only `explain` (and the
MCP `get_neighbors` tool, which shares the matcher) was silent.

Split `_find_node` into `_find_node_tiers` (logic unchanged, tiers exposed) plus
a flattening wrapper, and add `find_node_ambiguity()`, which returns rivals only
when the winning tier spans multiple source files. Matches within one file (a
file node plus its members) stay ordinary precedence and resolve as before.

`_disambiguate_file_node_labels` (#2032) already relabels colliding *file*
nodes; this covers the symbol case it does not reach.
2026-07-30 17:13:48 +01:00
PathGaoandClaude Opus 5 3868434942 fix(go): scope the predeclared-function filter to Go bare identifiers
Review feedback on #2296: the previous revision added Go's predeclared
names to _LANGUAGE_BUILTIN_GLOBALS, which ~11 languages consult through
engine.py and the cross-file pass, and whose check wraps the in-file
EXTRACTED branch as well as raw_calls. Two confirmed regressions:

  * Rust normalizes 'Widget::new(3)' to the bare token 'new', so every
    in-file 'Type::new()' edge disappeared. Rust keeps its own
    _RUST_TRAIT_METHOD_BLOCKLIST, deliberately on the cross-file branch
    only — this change follows that language-local pattern.
  * Go 'h.append(v)' is a selector_expression call to a real method and
    was dropped with it. On the 3x-ui corpus this cost a genuine
    'systemMetrics.append(...)' -> '(*metricHistory).append' edge.

The filter now lives in extractors/go.py as _GO_PREDECLARED_FUNCS and
fires only when the callee node is a bare identifier, so selector calls
('h.append(v)', 'pkg.Delete(x)') and every other language are untouched.
Go raw_calls now carry language="go" and the shared pass gates on it,
mirroring the bash gate, as a backstop for Go raw_calls minted
elsewhere. The set is the Go spec's predeclared list in full: being
Go-local and bare-identifier-only makes 'len'/'max'/'min'/'print' safe
to include, and a spec boundary beats a hand-picked subset.

Remeasured on the same 466-file Go corpus:

  upstream v8      16904 edges, 334 inbound to 'append'
  previous rev     16571 edges,   1 inbound  (332 phantom gone, but the
                                              genuine selector call too)
  this rev         16572 edges,   2 inbound  (332 phantom gone, genuine
                                              call restored)

Tests kept, plus three regressions: builtin 'append' must not bind
in-file (the branch a cross-file-only gate would miss), the Go selector
call must survive, and the in-file Rust 'Type::new()' edge must survive.
The last two fail on the previous revision.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 17:13:48 +01:00
PathGaoandClaude Fable 5 773250ad31 fix(go): filter Go predeclared functions from call-target resolution
graphify/extractors/go.py already consults _LANGUAGE_BUILTIN_GLOBALS
when resolving a callee, but the table covered JS/TS, Python and Swift
(#726, #2147) and never Go. Because the Go resolver looks the callee up
by bare name, an unexported method sharing a builtin's name absorbs
every builtin call in the repository.

Measured on a real 8.9k-node Go+TS codebase: a
'func (h *metricHistory) append(...)' method collected 330 phantom
inbound calls edges from the project's ordinary append(slice, x) calls,
which in turn invented twelve database-layer -> service-layer edges —
a layering violation absent from the source. After the fix, phantom
cross-file edges to builtin-named nodes drop from 325 to zero; the 8
that remain are all same-file (struct -> method, and real calls to that
method), and the user's method node is untouched.

Builtin types are deliberately not listed. Go conversions are
call-shaped too, but they produced no phantom edges on that corpus and
listing them would suppress genuine constructor-like calls.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 17:13:48 +01:00
oleksii-tumanov d7cb5b1b1c fix(extract): emit nodes for exported scalar bindings 2026-07-30 17:13:48 +01:00
MalikHaroonKhokhar bdf62ce275 fix(install): stop hardcoding the global skill path in the Antigravity workflow (#2319)
`_ANTIGRAVITY_WORKFLOW` is shared by the global and project-scoped installs,
which write SKILL.md to different locations (~/.gemini/config/skills vs
.agents/skills). The template named the global path unconditionally, so
`install --project --platform antigravity` (and `antigravity install
--project`) emitted a workflow pointing at a file that scope never writes -
a dangling reference on any machine without a prior global install.

Refer to the skill by name rather than by location, matching what every
block in always_on/ already does. Antigravity resolves it from the
`name: graphify` frontmatter in either scope, so no path interpolation is
needed and neither scope can dangle.

The existing tests only asserted the workflow file exists, which is why this
shipped; add coverage that the generated workflow names no skill path, in
both project and global scope.
2026-07-30 17:13:48 +01:00
Nicola AvanciniandClaude Fable 5 b1613b3083 chore: re-lock uv.lock for the mcp>=1,<3 extra specifier
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 17:13:48 +01:00
Nicola AvanciniandClaude Fable 5 576d5cbb61 feat(serve): dual-compat with MCP SDK 1.x and 2.x
mcp 2.0 removed the low-level decorator API the server was built on and
changed several models. _build_server now defines the four handlers as
plain coroutines and binds them at the end in a version-aware way: the
@server.list_tools()/... decorators on 1.x, the on_list_tools=/...
constructor callbacks (with explicit ListToolsResult/CallToolResult/
ListResourcesResult/ReadResourceResult wrapping) on 2.x. Model diffs
handled: Tool.inputSchema is input_schema on 2.x (constructor aliases
work on both, attribute access does not); Resource.uri is a plain str
on 2.x and rejects AnyUrl instances, so resource URIs are passed as
strings (1.x coerces them). The 2.x server also reports graphifyy's own
version in serverInfo. Extras relaxed from mcp>=1,<2 to mcp>=1,<3.

Verified: full stdio handshake (initialize / tools/list / tools/call /
resources/list / resources/read) and the tests in test_serve.py +
test_serve_http.py (145 passed) under BOTH mcp 1.29.0 and mcp 2.0.0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 17:13:48 +01:00
Nicola AvanciniandClaude Fable 5 50008cdf36 fix(serve): cap the mcp extra below 2.0; AnyUrl fallback for the 2.x SDK
mcp 2.0 removed the low-level decorator API (Server.list_tools/call_tool/
list_resources/read_resource) that serve.py is built on, so an install
that resolved the unpinned extra to 2.0.0 crashed at server startup
(first at `from mcp.types import AnyUrl`, then at @server.list_tools()).
Pin mcp>=1,<2 in the `mcp` and `all` extras; import AnyUrl with a
pydantic fallback so that piece is already 2.x-ready. Verified with a
full stdio handshake (initialize / tools/list / tools/call) against the
installed graphify-mcp with mcp 1.29.0. Porting to the 2.x API is a
separate work item.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 17:13:48 +01:00
safishamsiandClaude Opus 4.8 ecfcd160d5 chore(release): 0.9.30
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 17:34:24 +01:00
safishamsiandClaude Opus 4.8 1c6b3dbc58 chore: fold the batch into a single 0.9.30 release; changelog for #2262/#2257/#2287/#2284/#2261/#2268
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 17:27:40 +01:00
safishamsiandClaude Opus 4.8 ffc6dc0207 fix(llm): correct bedrock max_attempts semantics + stub botocore.config in the reasoning test (follow-up to #2283/#2288)
botocore max_attempts counts the initial call, so GRAPHIFY_MAX_RETRIES must
map to _resolve_max_retries() + 1 (a value of 6 -> 7 total attempts; 0 ->
1, i.e. no retry). Also stub botocore.config in the #2288 reasoning-model
test, which broke once #2283 added the botocore.config import.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 17:25:08 +01:00
safishamsiandClaude Opus 4.8 3c332ba72a fix(extract): parse .tsx with the TSX grammar so symbol-resolution stops leaking absolute-slug ids (#2262)
_parse_js_tree parsed .tsx with language_typescript(), so JSX misparsed and
error-recovery floated nested handlers to top level; the symbol-resolution
pass then emitted calls edges whose SOURCE was an absolute-stem id for a
caller that owns no node — a leak the 0.9.29 backstop (learns only from
nodes) can't see. Fix: use language_tsx() for .tsx; never emit a calls
use-edge from an unowned source (reattribute to the file node); and teach
the backstop stem-form prefixes so any node-less absolute-derived endpoint
canonicalizes. No node id or edge endpoint now carries the scan-root slug.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 17:25:08 +01:00
Kartik Gupta b4865ffcbf fix(serve): bound multi-project graph contexts (#2268) 2026-07-29 17:02:00 +01:00
himanshupatro-334 6d6b674b20 fix: preserve edge direction in merge-graphs 2026-07-29 17:02:00 +01:00
Zhi Yan Liu a428378ad3 fix(llm): honor GRAPHIFY_API_TIMEOUT in the bedrock backend
The two bedrock-runtime clients (primary extraction in _call_bedrock and
the secondary dispatch path in _call_llm) were built with no botocore
config, so Converse used botocore's 60s default read timeout and ignored
GRAPHIFY_API_TIMEOUT / --api-timeout entirely. A long opus-class
generation then died with "Read timeout on endpoint URL" no matter how
high the timeout was set.

Both client constructions now pass a botocore.config.Config wiring
read_timeout to _resolve_api_timeout() (default 600s), a 10s
connect_timeout, and retries from _resolve_max_retries() in adaptive
mode. This mirrors the fixes that closed the same gap for the claude-cli
subprocess (#1112/#1111) and the secondary LLM dispatch path (#1442) --
bedrock was the last cloud backend still ignoring the knob.

Also updates the README env-var row, which listed the timeout as
applying to HTTP/claude-cli/Anthropic only, and the _fake_boto3 test
fixture to register botocore.config and capture the client config so the
new coverage can assert the timeout is wired.
2026-07-29 17:01:49 +01:00
Zhi Yan Liu d47f3ea152 fix(llm): read the first text block of a bedrock Converse response
Converse returns output.message.content as a list of blocks and does not
promise a text block is first. Reasoning-capable models emit a
reasoningContent block ahead of the answer, and toolUse or future block
types can precede it too, but both bedrock call sites indexed position 0:

    content", [{}])[0].get("text", "{}")

For those models the default was returned on every call, so _parse_llm_json
saw an empty object, _response_is_hollow reported a hollow result,
finish_reason was rewritten to "length", and the adaptive retry bisected the
chunk. Splitting could not converge because the position assumption fails
identically at every chunk size, and raising GRAPHIFY_MAX_OUTPUT_TOKENS did
nothing because output length was never the constraint. stopReason on those
responses was end_turn, i.e. the model had answered correctly.

Selection now keys on the block's shape rather than its position, at both
_call_bedrock and the bedrock branch of _call_llm. A response whose first
block is already text -- every non-reasoning model today -- is unaffected.

On a 48-document corpus the hollow warnings and the bisection to the
recursion cap disappear, the 17 files previously reported as producing no
nodes are extracted, and output tokens drop from 217,538 to 53,274 as the
wasted retries stop.

Fixes #2287
2026-07-29 17:00:15 +01:00
Kaushik Samadder c5d432710f fix(cache): re-anchor cached ids so a warm hit can't replay another root (#2257)
Extractors mint node ids from the path STRING they are handed
(_make_id(str(path)), _file_node_id(path)), so an AST cache entry written
under root A embeds A's slug in every id and edge endpoint. save_cached
relativized only source_file, never the ids. Because extract()'s
id-remap / final-canonicalization passes key their rewrites off the
CURRENT run's paths, an A-derived id matches no key on a warm hit under
root B (a clone, a moved checkout, a second mount) and the stale
machine slug survives into graph.json. Distinct from #2231/#2243, which
fix producers on a cold run, and from #2199 (stat-index portability).

Entries are now stored root-anchored and re-anchored on read, the same
store-portable/re-anchor-on-load contract source_file (#777) and the
stat index (#2199) already use: _relativize_ids_in replaces the root's
contribution with a $graphify-root$ marker on write, _absolutize_ids_in
restores what the current run's extractor would mint on read. That is
the pre-remap form every downstream pass in extract() expects, so a
replay reproduces a cold run exactly and no other pass changed.

The anchor is derived per entry rather than assumed equal to the scan
root (normalize_id distributes over path joins), so a symlinked root or
relative inputs decompose exactly; only absolute root spellings may
anchor, or a relative root ("src") would rewrite an already-canonical
src_utils_foo into an absolute-derived id on the semantic path. The
walk covers the whole payload rather than a bucket list, since the id
form is self-identifying: that also reaches raw_calls[].caller_nid,
swift_extensions[].nid, edges[].target_file, bash_sources[].source_file
and *_type_table.path, the last three being resolution inputs that
would otherwise still point at root A. save_cached's deepcopy is now
unconditional; the old truthiness gate skipped it for a payload whose
only content lives outside nodes/edges, which would have let the
transform mutate the caller's dict and break cold-run remapping.

Pre-fix entries carry no marker and their content hash never changes,
so they cannot self-heal; they are swept when the release bumps the
version, since AST entries live under cache/ast/v{version}/.

Tests: extract a python/C/bash/markdown corpus under root A, copy the
tree and graphify-out to root B, extract under B on the warm cache, and
assert the run is genuinely warm (zero extractor calls), that no node id
or edge endpoint carries A's slug, that the on-disk entries hold neither
A's slug nor an absolute path, that a cold run still yields canonical
ids, and that warm and cold match exactly. The fixture avoids JS/TS on
purpose: those suffixes bypass the cache, which would make the warm
assertions vacuous.
2026-07-29 17:00:15 +01:00
safishamsiandClaude Opus 4.8 6d81a8290f fix(deps): cap mcp<2 so fresh installs of the MCP server work (#2277, #2279, #2291)
mcp 2.0.0 dropped mcp.types.AnyUrl and the Server decorator-registration
API graphify/serve.py relies on, so an unpinned resolve broke graphify-mcp
on every fresh graphifyy[mcp]/[all] install. Cap mcp>=1,<2 (resolves 1.29.0)
and starlette>=1.3.1,<2 in both extras; re-lock. Bump to 0.9.30. Porting to
the mcp 2.x API is a tracked follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 16:59:16 +01:00
safishamsiandClaude Opus 4.8 0b2bd938c4 chore(release): 0.9.29
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-28 10:52:23 +01:00
safishamsiandClaude Opus 4.8 0411dede19 chore: bump to 0.9.29; changelog for #2231/#2243/#2251/#2241/#2253/#2206/#2184/#2205/#2052
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-28 10:21:25 +01:00
safishamsiandClaude Opus 4.8 829224acd0 fix(export)+test: all-dots Obsidian label falls back to unnamed; .env.example regression test (#2205, #2184)
Follow-ups on the cherry-picked #2242/#2232: an all-dots label ('...') no
longer produces an empty 'dot-' Obsidian stem (falls back to 'unnamed'),
and the .env.example carve-out gets the regression test it shipped without
(templates graphable, real .env still sensitive, secrets/.env.example still dropped).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-28 10:18:01 +01:00
safishamsiandClaude Opus 4.8 2099873ae6 fix(watch): refuse to overwrite an unreadable existing graph in the hook rebuild (#2251)
_reconcile_existing_graph loaded graph.json inside a swallowing try, so a
graph that was merely unreadable (over the size cap or unparseable) was
silently replaced by the code-only extraction, in both the clustered and
--no-cluster hook paths (force made it worse). It now loads through the
fail-closed build._load_existing_graph and _rebuild_code refuses the write
(prints and returns False) on a load failure, matching the CLI path; the
--no-cluster write is now atomic with a protected-graph backup.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-28 10:18:01 +01:00
safishamsiandClaude Opus 4.8 f67113361b fix(extract): close the absolute-path node-id leak class (#2231, #2243)
Absolute/machine-slug ids still leaked into edge endpoints from producers
the target_file-stamp loop didn't reach. Three fixes: apply id_remap to
raw_calls caller_nid so module-top-level indirect_call sources canonicalize
(#2231); a general backstop in the final relativization pass that learns
_make_id(abs source_file) -> canonical id for every node and rewrites all
node ids and edge endpoints (in-root -> _file_node_id, out-of-root -> ext_),
suffix-aware for __entry; and target_file stamps on bash source/entry edges
so they ride the same canonicalization. No node id or edge endpoint now
carries the scan-root slug for any file in the batch. Builds on #2250.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-28 10:18:01 +01:00
Yyunozor 4d9d64b228 fix(extract): canonicalize out-of-root import/include edge targets (#2243)
Follow-up to #1899. That fix taught the relativization pass to catch a NODE
whose id was minted from an absolute out-of-root path and give it a portable
"ext_"-namespaced id, by matching the node's own id against
_make_id(str(its source_file)). But several cross-file resolvers (Python
relative imports, C/C++/ObjC quoted #include) only ever emit an EDGE for an
import target, no node -- so when that target lives outside the scan root,
the belt-and-braces pass has nothing to learn the old->new id from, and the
edge keeps the raw _make_id(str(absolute_path)) slug forever. The scan path,
including the OS username, ends up in links[].source/target, and differs
between machines/checkouts even though the node id sets are identical.

_import_c also never stamped the transient `target_file` hint (#1814/#2169)
its Python/JS siblings already use for exactly this kind of cross-file
target canonicalization, so it could not benefit from that machinery either.

Fix, in the two places this root cause actually lives:

- _import_c now stamps target_file on a resolved #include, mirroring
  _import_python/_import_js.
- The id_remap pass that already walks target_file-stamped edges to
  canonicalize in-root-but-unscanned targets now also handles the
  out-of-root branch it previously skipped ("leave its ids alone"): an
  existing out-of-root target gets the same portable ext_-namespaced id an
  out-of-root NODE already gets, so an edge with no node of its own is
  covered too. A target that does not exist on disk still stays dangling,
  unchanged from before.

_portable_out_of_root_sf moved next to id_remap so both the new edge-target
branch and the existing node-level pass share one implementation.

Four tests in tests/test_extract.py: the out-of-root #include gets a
portable id instead of the raw slug, and its transient target_file hint
never leaks into the returned edge; the same corpus built from two
differently-nested checkout paths produces a byte-identical target (the
reported non-determinism, made explicit); an in-root, same-batch include
still resolves to the real node's id (negative/regression guard); and the
equivalent out-of-root Python relative import is fixed too, since the gap
was in the shared remap path, not language-specific.

Known limitation: this covers every current target_file-stamping resolver
(Python relative imports, C/C++/ObjC #include, JS/TS/Svelte/Astro/Vue
rescued imports). A resolver that mints a path-derived edge target WITHOUT
stamping target_file at all -- none do today -- would still leak; the fix
closes the gap in the shared mechanism, not a per-language allowlist.
2026-07-28 09:37:39 +01:00
Sfahad7 8046334fed fix(detect): allow committed .env.example-style templates through Stage 2
Stage 2's .env regex treated .env.example / .sample / .template / .dist
like live secret files and dropped them from the graph. Carve out those
suffixes for .env / .envrc basenames only — real .env.local etc. stay blocked.

Fixes #2184
2026-07-28 09:37:39 +01:00
Sfahad7 788c64883e test(export): cover Obsidian/canvas stems for leading-dot labels
Assert .env / .gitignore become dot-env / dot-gitignore on disk and in
the canvas file nodes, so Obsidian cannot hide them again (#2205).
2026-07-28 09:37:39 +01:00
Sfahad7 f74c6326f2 fix(export): stop Obsidian from hiding notes for leading-dot labels
safe_name left stems like .env intact, so the vault wrote .env.md which
Obsidian treats as a hidden file — invisible in the explorer and as
unresolved wikilinks. Prefix with dot- (shared _obsidian_safe_stem for
vault + canvas). True label stays in the note body.

Fixes #2205
2026-07-28 09:37:39 +01:00
Yyunozor 6deb27f204 fix(scala): dispatch self-type annotations to requires edges (#2052)
self_type (`self: Logging with Database =>`, `this: T =>`) was never
dispatched on anywhere in the Scala extractor, so a trait/class's
structural precondition on its enclosing type produced zero edges, in
any context. The type node sits at a fixed position among self_type's
unnamed-field children (binder identifier first, type second when
present), and _scala_collect_type_refs already handles every shape
that position can take (type_identifier, compound_type for `with`,
refinement bodies) -- reused unchanged, one new dispatch branch.

Also add the new `requires` relation to DEFAULT_AFFECTED_RELATIONS,
mirroring how `indirect_call` was wired into blast-radius traversal
when it was introduced, so `graphify affected` follows it like the
existing inherits/mixes_in/embeds structural relations.

Covers: single type, `with`-compound, structural refinement (base
type only, matching how refinement bodies are already unscanned
elsewhere), the binder-only `self =>` shape (no requires edge),
coexistence with an unrelated `extends`, and a plain class without a
self-type (no spurious edge).
2026-07-28 09:37:39 +01:00
Yyunozor 51b7b9f317 fix(extract): shadow untracked JS/TS closure params from indirect_call args (#2241)
walk_calls flattens an inline/untracked arrow or function-expression argument
(one not separately tracked in function_bodies) onto the enclosing named
function's caller_nid, so its calls resolve as if made directly by that
function (#1630). But the closure's own parameters and locals were never
folded into the shadow set used to guard argument-based indirect_call
resolution, so a call argument inside the closure that happened to share a
name with an unrelated callable elsewhere in the corpus produced a fabricated
indirect_call edge, confidence 0.8 — even though the identifier was, in fact,
a local binding one lexical scope down:

  rows.map((r) => c.get(r))   // `r` is the arrow's own param, not a
                               // reference to some other same-named function

Single-letter names make this common, since they collide with same-named
symbols anywhere else in the repo (loop vars, test helpers).

Fix: thread an extra_locals set through walk_calls's recursion. Entering an
untracked closure folds that closure's own bindings (computed the same way as
a tracked function's, via _js_local_bound_names) into extra_locals for its
subtree only; deeper untracked closures compound the same way on their own
recursion. All six call sites that build the caller's shadow set now union in
extra_locals, so the fix applies uniformly to the argument, collection, and
assignment/return capture paths already sharing that guard, not just the
argument one that surfaced it. Tracked closures (const-assigned arrows,
methods) are unaffected — they already get their own caller_nid and their own
correctly-scoped shadow set.

Scope: this fixes the shadow-set gap for closures. A `for (const x of xs)`
loop variable not wrapped in a variable_declarator is a separate, pre-existing
gap in the same shadow computation, already addressed by #1985 — not
duplicated here.
2026-07-28 09:37:39 +01:00
Yyunozor b1eadad05b fix(extract): normalize whitespace before truncating rationale labels (#2206)
_extract_python_rationale / _extract_js_rationale sliced the raw
docstring/comment text to 80 characters before collapsing whitespace,
so the cut could land mid-word, leave a run of literal spaces where a
newline + indentation used to be, and, when the cut landed on a ".",
produce an Obsidian export filename ending in "..md".

Both _add_rationale sites now share _shorten_rationale_label, which
normalizes whitespace first via textwrap.shorten (word-boundary safe,
adds a placeholder only when it actually truncates) and falls back to
a plain character truncation when shorten collapses to a bare
placeholder -- which it does when the first word alone is already
>= 80 chars (e.g. a comment opening with one long URL), a case that
would otherwise regress to a content-free label.
2026-07-28 09:37:39 +01:00
himanshupatro-334 952b477a3f test(hooks): update comment to refer to #2253 2026-07-28 09:37:39 +01:00
himanshupatro-334 3bac3df666 fix(hooks): replace DETACHED_PROCESS with CREATE_NO_WINDOW on Windows 2026-07-28 09:37:39 +01:00
safishamsiandClaude Opus 4.8 16442303e1 chore(release): 0.9.28
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 10:57:57 +01:00
safishamsiandClaude Opus 4.8 bbc4e5167c chore: bump to 0.9.28; changelog for #2211/#2213/#2210/#2212/#2215/#2221/#2181/#2218
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 10:47:30 +01:00
safishamsiandClaude Opus 4.8 753a6ac2cc test(detect): regression for NFC manifest keys on macOS --update (#2221)
Adds the regression test PR #2224 shipped without: an NFD-keyed manifest
(portable and legacy-absolute) must match an NFC scan so --update is a
no-op instead of re-extracting everything.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 10:46:47 +01:00
safishamsiandClaude Opus 4.8 bdb678858b fix(install): scope uninstall to project_dir instead of always deleting the global skill (#2215)
claude_uninstall/gemini_uninstall/codebuddy_uninstall accepted project_dir
but, with the default project=False, still deleted the user-global skill
tree, so a library/test caller passing a project_dir nuked ~/.claude et al
(the API trap behind #2168). They now take remove_user_skill and treat a
passed project_dir as authoritative; uninstall_all opts in explicitly to
preserve 'graphify uninstall' behavior. Also fixes a live CLI bug where
'uninstall --project' deleted the global codebuddy skill.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 10:46:47 +01:00
safishamsiandClaude Opus 4.8 2f78439ffd fix: load raw edges-keyed graphs + stop pruning alive files as deleted (#2212, #2210)
#2212: benchmark, the merge-driver graph load, and callflow_html crashed
or silently failed on a --no-cluster graph.json (edges stored under
'edges', not 'links'). A shared load_node_link_graph helper normalizes
links/edges before node_link_graph and is used at all three sites.

#2210: _stale_graph_sources compared graph source_file spellings to the
scan with a raw string test (no NFC), and pruned any non-match with no
liveness check, so alive files (macOS NFD paths, legacy basenames) were
pruned as 'deleted'. It now compares NFC-on-both-sides and is fail-closed:
a corpus-missing source whose file still exists is pruned only when the
exclusion is provable, else kept with a warning. Prune message corrected
to 'deleted or excluded'.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 10:46:47 +01:00
safishamsiandClaude Opus 4.8 d91a987aa5 fix(extract): stamp target_file on Python imports and markdown refs so incremental targets canonicalize (#2211, #2213)
The #2169 incremental canonicalization only rewrites edge targets that
carry a target_file stamp. Python relative imports and markdown reference
links emitted absolute-path-derived target ids without one, so on an
incremental/subset extraction they dangled on an absolute id instead of
resolving to the canonical root-relative node (dropping md->md references
and leaving a dangling imports_from on --no-cluster). Both now stamp the
resolved target (existence-gated); the stamp is popped before graph.json
ships. Also register the unresolved target form in the remap loop so a
symlinked root (macOS /tmp) can't cause an id-form mismatch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 10:46:47 +01:00
Bob Spryn 498b76ba32 fix(watch): keep a visualization when the graph outgrows the viz cap
Crossing MAX_NODES_FOR_VIZ left the project with no graph.html at all:
_rebuild_code unlinked the existing file and wrote nothing in its place. The
delete on its own is defensible — a kept graph.html would describe an older,
smaller graph — but the file is gone before the user reads the message, and
the next incremental rebuild silently removes it again, so a repo that grows
past the threshold just loses its visualization with no way to keep one.

The export path already solved this (#1019): over the cap it re-renders the
community-aggregation view rather than going without. Do the same here, so
the artifact is current AND present instead of current OR present.

GRAPHIFY_VIZ_NODE_LIMIT=0 still means "no HTML viz" (CI runners) rather than
"aggregate", and if the aggregated render also fails the old skip-and-remove
behaviour stands.
2026-07-27 10:22:48 +01:00
Bob Spryn 6d42c48f4d fix(watch): stop incremental rebuilds from reusing stale community labels
Community labels are saved keyed by community id, but re-clustering
reassigns those ids: after a rebuild that adds nodes, cid 30 can cover a
completely different community and its saved name is then simply wrong.
cluster-only already guards this — it validates each reused label against
the `.graphify_labels.json.sig` membership fingerprints and re-hubs any
community that changed (the case community_member_sigs() was written for).

_rebuild_code() skipped that check entirely: it reused every label whose
cid was present and hub-filled only the *missing* ones, so stale names
survived — and then wrote them back to labels.json, laundering them as
current. It also never refreshed the .sig sidecar, so the signatures kept
describing an older clustering and drifted out of step with the labels
they sit beside, leaving the cluster-only guard nothing accurate to check.

Adding ~3.5k nodes to a real graph re-clustered 463 -> 515 communities and
mislabeled 162 of them this way: a `domain.audit` namespace reading
"ACH / bank payments", a `domain.auth` namespace reading
"document-sensitivity.up.sql". Node and edge data stayed correct, so
nothing failed loudly — only the names lied.

Apply the same signature check in the incremental path, write the sidecar
in step with the labels, and print the same "run `graphify label`" notice
cluster-only emits so a drifted community set is visible rather than
silent.
2026-07-27 10:22:48 +01:00
Sfahad7 072698a176 fix(detect): NFC both sides of relpath for portable manifests on macOS
Stamped keys can already be NFC while Path(root).resolve() is NFD, so
os.path.relpath treated in-root files as ../ and kept them absolute.
Normalize both operands inside _to_relative_for_storage (and the join in
_to_absolute_from_storage).
2026-07-27 10:22:48 +01:00
Sfahad7 06e5978309 fix(detect): NFC-normalize manifest keys so --update survives macOS path forms
macOS yields NFD paths from os.walk/getcwd while skill path literals are
often NFC. Raw string compare treated every file as deleted+new and forced
a full re-extract. Canonicalize at the manifest boundary (same idea as #1226).

Fixes #2221
2026-07-27 10:22:48 +01:00
ozdemirsarman d1f303e237 fix(swift): extract computed & observed properties (#2181)
function_types only recognised func/init/deinit/subscript, so computed properties (var body: some View { ... }) and willSet/didSet observers produced no node and their bodies were never walked — erasing the whole SwiftUI view layer. Emit a function-like member node for them and defer the body to the call-walk via function_bodies; stored properties are unchanged. Adds tests.
2026-07-27 10:22:48 +01:00
safishamsiandClaude Opus 4.8 62b1d4370b docs(readme): link the YC badge to the company page
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 00:19:11 +01:00
safishamsiandClaude Opus 4.8 f5a3592882 chore(release): 0.9.27
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 13:01:17 +01:00
safishamsiandClaude Opus 4.8 b4dd6d7b25 docs: changelog for the Track A / node-identity / C# batch (0.9.27)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 13:00:06 +01:00
safishamsiandClaude Opus 4.8 0858954db9 feat(csharp): namespace-aware member-call resolution + shadow poisoning (#1609)
Adapted from #1620 by @TheFedaikin, reworked onto v8 as a focused change
(without the module split or the references-fallback behavior change).

Builds on the shipped #1609 resolver: instead of bailing when a receiver's
class name is ambiguous corpus-wide, the declared type is resolved with a
shared CsharpNameResolver (same-namespace, using-directive, and alias aware)
against the caller's namespace/scope, falling back to the unique bare match
only when scoping is non-decisive. Adds base./this.field receivers and
inherited-member lookup through the inherits chain (an out-of-corpus base
poisons the lookup, so no wrong edge). The per-file type table now poisons a
name on any conflicting rebinding, killing the wrong-edge class where a local
shadows a field of a different type. C#-gated; never emits a wrong edge.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 12:43:17 +01:00
safishamsiandClaude Opus 4.8 8adb261d16 fix(build): fold legacy node/edge aliases and re-key absolute-derived semantic ids (#2194, #2197)
build_from_json now folds name->label, path->source_file, edge type->relation,
and confidence_score->confidence=INFERRED before validation, so alias-carrying
nodes stop entering the graph without label/source_file (invisible, unmergeable
ghosts); the same folds run before dedup. _semantic_id_remap now also learns the
absolute-path stem form, so a Windows absolute-derived semantic id re-keys to the
canonical root-relative id. The extraction warning now breaks errors down by cause.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 11:52:20 +01:00
safishamsiandClaude Opus 4.8 334cff6172 fix(cache): portable stat-index keys + normalized semantic source_file (#2199, #2197)
stat-index.json keyed entries by absolute path and never pruned, so a
moved/cloned corpus got 0% cache hits and the index grew unbounded. Keys
are now stored root-relative and re-anchored on load (mirroring the
manifest.json portability fix), and dead-file entries are pruned on flush.
save_semantic_cache also normalizes source_file to root-relative before
persisting so an absolute/backslash fragment can't poison later updates.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 11:52:20 +01:00
safishamsiandClaude Opus 4.8 e395ff9b43 fix(dedup): merge cross-file concept nodes with identical normalized labels (#2182)
Pass 1 deferred cross-file exact matches to Pass 2, but Pass 2's candidate
filter keeps only the first node per normalized label, so identical-label
cross-file concept pairs could never merge (while fuzzy pairs did). Pass 1
now unions the cross-file residue of each label group, gated to concept
nodes with provenance and above the entropy floor, so code/rationale/
document/image/empty-source and cross-repo guards are all preserved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 11:52:20 +01:00
safishamsiandClaude Opus 4.8 d16510ed4a fix(extract): canonicalize regex-rescue import target ids (#2195)
The Svelte/Astro/Vue regex-rescue import passes minted stub target nodes
with absolute-path ids (ghost nodes alongside the real file node, plus
dangling imports_from edges). They now resolve via _resolve_js_module_path
and stamp edge target_file so the #2169 canonicalization repoints them;
when the target is an in-root real code file, only the edge is emitted (no
duplicate stub). The final relativization pass also remaps ids in its
in-root branch, closing the residual class.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 11:52:20 +01:00
safishamsiandClaude Opus 4.8 9eb76ace30 fix: review follow-ups for the bash/SQL contributor PRs (#2171/#2172/#2180)
- bash: mark the bare-name `source lib.sh` sibling binding INFERRED (it
  resolves via $PATH at runtime, so it's a heuristic, not EXTRACTED) (#2171)
- bash: un-join a comment accidentally merged onto the _BASH_SCRIPT_RUNNERS
  line during #2172
- sql: gate the global routine-recovery raw-text scan on root.has_error so a
  cleanly-parsing file can't fabricate routines from commented-out DDL,
  EXECUTE-string bodies, or MySQL 'CREATE FUNCTION IF NOT EXISTS' (#2180)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 11:18:13 +01:00
Souptik Chakraborty 911d58178f fix: document the Codex PreToolUse hook as an intentional no-op (#2165)
`graphify codex install` registers `graphify hook-check` in .codex/hooks.json,
and #2165 reported that as a stale/unrecognized subcommand producing a silent
no-op. `hook-check` is in fact a real, deliberate no-op command: Codex Desktop
rejects hookSpecificOutput.additionalContext on PreToolUse, so the Codex hook
intentionally does nothing and AGENTS.md carries the always-on guidance
(cli.py dispatches `hook-check`; __main__.py lists it in _silent_cmds).
Repointing the installer at `hook-guard` would reintroduce the #522-class
breakage on Codex Desktop, so the behavior is left as is.

What actually misled the report was the documentation and the installer's own
output, which both describe the Codex hook as if it enforced graph usage:

- README: the Codex row claimed a PreToolUse hook that "fires before every Bash
  tool call, same always-on mechanism as Claude Code". It now states that the
  hook is a deliberate no-op, why (Codex Desktop rejects additionalContext), and
  that AGENTS.md is the always-on mechanism on this platform.
- `_install_codex_hook` printed "PreToolUse hook registered (... hook-check)"
  with no hint that the entry is inert. It now says so inline.

Also adds the regression guard the issue implicitly asks for: a test that reads
the command out of the generated .codex/hooks.json and asserts its subcommand is
one the CLI actually dispatches. A genuinely renamed/stale hook command now
fails the suite instead of shipping a permanently dead hook.

Note: contrary to the report, an unrecognized subcommand already exits non-zero
(`graphify totally-bogus-subcommand` -> "error: unknown command", exit 1), so no
change was needed there.
2026-07-26 11:10:35 +01:00
Souptik Chakraborty ffa2a2471a fix: recover every declared SQL routine from unparseable PL/pgSQL (#2180)
tree-sitter-sql cannot parse PL/pgSQL-only statements, and #1910's ERROR-node
name recovery only covered one of the shapes that produces. Two others dropped
the routine silently -- no node, no warning, exit code 0:

1. The statement is shredded into loose top-level tokens (keyword_create,
   keyword_function, object_reference, ..., keyword_begin) and the ERROR node
   holds only the offending body line, e.g. `PERFORM other_fn();` or `x := 1;`.
   No ERROR node contains any CREATE text, so scanning ERROR nodes finds
   nothing. This is what still dropped PERFORM and := after #1910.
2. The routine name is a quoted identifier -- CREATE OR REPLACE FUNCTION
   "public"."fn"(...) -- which the recovery's bare [\w$.]+ pattern cannot match,
   because it stops dead at the leading quote. Generated schema dumps quote
   every identifier, so whole files recovered nothing.

Verified on the reported repro: the same body that drops under a quoted name is
recovered fine under an unquoted one, which is why the drop looked like it
depended only on the body statement.

Fix mirrors the global REFERENCES fallback already in this extractor: after the
tree walk, scan the raw source for every CREATE [OR REPLACE] FUNCTION/PROCEDURE
and emit any routine the walk missed. Name parts accept bare or double-quoted
identifiers. _add_node dedupes by node id, so routines already recovered from
the tree are not emitted twice.

Adds tests/fixtures/sample_plpgsql_quoted.sql -- generated-style quoted DDL whose
bodies use RAISE, RAISE NOTICE, PERFORM, :=, IF..THEN and bare NULL; -- plus
tests that every routine is recovered and that the file stays clean (tables
before and after still extract, no duplicate ids or labels, no empty/ERROR
labels, and every routine keeps its contains edge from the file node).
2026-07-26 11:08:10 +01:00
Souptik Chakraborty cfe15f9161 fix: pin interpreters whose path contains a space (#2166)
`graphify hook install` emitted `_PINNED=''` for some Windows uv-tool installs,
so every interpreter probe failed, each commit printed "could not locate a
Python with graphify installed" and the graph never rebuilt.

Root cause is the install-time allowlist in `_pinned_python()`, not the uv
layout: it accepted `[a-zA-Z0-9/_.@:\-]` but not a plain space, so any
`sys.executable` under a profile whose name contains one -- `C:\Users\First
Last\AppData\Roaming\uv\tools\graphifyy\Scripts\python.exe`, or the equally
common `C:\Program Files\Python312\python.exe` -- was rejected wholesale and
nothing was recorded. A space-free Windows uv path pins correctly, which is why
this looks layout-specific.

A space is safe to allow because every consumer already quotes the value: the
hook scripts embed it as `_PINNED='<path>'` and dereference `"$_PINNED"`, so a
space can neither split a word nor start a command. Adding it to the allowlist
therefore fixes the pin without weakening the injection guard -- `$`, backtick,
`;`, `'` and `"` are all still rejected.

`_register_merge_driver` did interpolate the path unquoted into the
`merge.graphify.driver` command, which git runs through a shell; that would
split a spaced path into two words, so it is now double-quoted. Double quotes
are safe here precisely because the allowlist keeps `$` and backticks out.

Tests: spaced Windows/POSIX paths are pinned; metacharacter paths are still
rejected (including `'` and `"`); the merge driver quotes a spaced interpreter;
and the installed post-commit/post-checkout hooks carry the real path rather
than `_PINNED=''`.
2026-07-26 11:08:10 +01:00
Souptik Chakraborty 44241dd10c fix: resolve ${VAR} bash sources against the variable's real base (#2172)
#2079 resolved `source "${VAR}/lib/x.sh"` by stripping the leading expansion and
resolving the literal suffix against the sourcing script's own directory. That is
correct for the canonical
`DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` idiom, but wrong whenever
the variable points somewhere else. With

    ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    source "${ROOT}/lib/utils.sh"

the real target is <root>/lib/utils.sh, yet a same-named decoy under the script
dir (<root>/scripts/lib/utils.sh) won: a wrong imports_from edge to a real node.

Track top-level variable assignments and use the assigned base for the leading
variable:

- the script-dir idiom, including any number of trailing `/..` hops (and the
  `$0` spelling), resolves to the script dir walked up that many times
- a literal value resolves as-is when absolute, or against the script dir when
  relative
- anything else -- a value built from other variables, or command substitution we
  do not model -- stays untracked, so the previous script-dir guess is kept

Only the base changes. The suffix guards are untouched: an expansion left in the
suffix, an empty suffix, and a `..` component in the suffix are all still
rejected, the edge is still gated on is_file() and still emitted as INFERRED.
2026-07-26 11:08:10 +01:00
Souptik Chakraborty 4710b864ea fix: resolve bash sources for extensionless libs and bare names (#2171)
Two coverage gaps left by #2141 / #2157, both misses rather than fabrications.

1. Extensionless shebang scripts. _SHEBANG_DISPATCH already routes a
   `#!/usr/bin/env bash` file with no extension to extract_bash, so its functions
   are indexed, but the cross-file source-resolution pass picked participants by
   filename suffix (`p.suffix in (".sh", ".bash")`). A sourced extensionless lib
   was therefore excluded and calls into it never bound. Select by shape as well:
   the bash extractor tags every node it emits with metadata.language == "bash".
   The suffix check stays so an empty .sh file, which has no nodes to inspect,
   still participates.

2. Bare `source lib.sh` (no ./ prefix). Only the `raw.startswith((".", "/"))`
   branch recorded a bash_sources entry; a bare name fell through to the opaque
   `imports` fallback, so neither the source edge nor calls into the lib resolved
   even though the file usually sits beside the script. The else branch now binds
   a sibling of that name when one exists.

The existence gate from the ./-prefixed branch carries over: a bare name that
resolves to no sibling keeps the old `imports` edge and records no bash_sources
entry, so nothing is invented. is_file() is wrapped against OSError so a name
that is invalid for the platform degrades instead of raising.

Transitive sources (a->b->c) remain unresolved, as the issue notes.
2026-07-26 11:08:09 +01:00
Souptik Chakraborty 556e615cc6 fix: skip the process pool when only one worker is available (#2173)
`_extract_parallel` spawned a ProcessPoolExecutor whenever there were at least
_PARALLEL_THRESHOLD (20) uncached files, even when the resolved worker count was
1. A one-worker pool buys no parallelism: it still pays a process spawn plus an
IPC round trip per file, and it is the one residual case where the parent's
rebuild watchdog (os._exit) can orphan a worker that is mid-task.

The Windows post-commit hook exports GRAPHIFY_MAX_WORKERS=1, so this was the
default there for any rebuild touching 20+ uncached files.

Gate the pool on the resolved worker count -- after the GRAPHIFY_MAX_WORKERS
override and the win32/floor clamps -- and return False when it is 1. That reuses
the existing contract: the caller already falls back to `_extract_sequential`
in-process when `_extract_parallel` returns False.

Tests: no pool is constructed with GRAPHIFY_MAX_WORKERS=1 and 25 uncached files,
and a multi-worker run still takes the pool path.

Only item 2 of #2173 is addressed here. Item 1 (the `graphify watch` rebuild
timeout) needs a maintainer decision first: `watch()` currently arms no timeout
at all on any platform -- there is no signal.SIGALRM branch in graphify/watch.py
to add an `else` to -- so applying the hook's shape means adding a watchdog that
os._exit(1)s a long-running foreground watcher on a slow-but-healthy rebuild.
That is a behaviour change rather than a Windows-compat fix, so it is left out of
this PR.
2026-07-26 11:08:09 +01:00
safishamsiandClaude Opus 4.8 4191b7dee3 chore: sync uv.lock to 0.9.27
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 11:06:51 +01:00
safishamsiandClaude Opus 4.8 52e1ed4050 test(resolution): assert canonical import-target ids in jsconfig tests (follow-up to #2169)
#2169 canonicalizes cross-file edge targets to the root-relative file-node
id (the same id the target file gets as a node) instead of the old
absolute-path form. The #2153 baseUrl tests asserted the absolute form;
update them to the canonical id via a _cid() helper. Resolution behavior
is unchanged — only the expected id form.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 23:16:52 +01:00
safishamsiandClaude Opus 4.8 a8da0d3821 chore: bump to 0.9.27; changelog for #2167/#2169/#2154/#2153/#2147/#2168
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 22:54:48 +01:00
safishamsiandClaude Opus 4.8 fbc24c7d3f fix(extract): suppress builtin/stdlib Python decorators from reference edges (follow-up to #2154)
The decorator reference edges added in #2154 fabricated sourceless stub
nodes for @property/@staticmethod/@dataclass/@functools.wraps and, via
the unique-function rewire, could stamp a false edge onto a corpus's own
def wraps(). Add _PYTHON_DECORATOR_NOISE (mirroring _PYTHON_ANNOTATION_NOISE)
and skip those names, same accepted tradeoff as patch/Mock in annotations.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 22:53:43 +01:00
safishamsiandClaude Opus 4.8 137dcf23fe fix(extract): incremental --no-cluster merges instead of overwriting the graph (#2169)
An incremental `extract --no-cluster` wrote only the changed files over
graph.json with no merge, dropping every node/edge owned by an unchanged
file; and the id-canonicalization pass only learned batch files, so the
changed file's cross-file edges kept absolute-path target ids and
dangled. The raw path now merges the existing graph forward with the same
replace/prune semantics as the clustered path (new merge_raw_extraction
helper in build.py, shared loader), refuses to overwrite a corrupt
existing graph, and the remap pass now also learns in-root edge
target_file paths (existence-gated) so cross-file targets canonicalize.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 22:53:43 +01:00
safishamsiandClaude Opus 4.8 05ee568969 fix(install): never clobber an unparseable settings file; back up before write (#2167)
The hook installers fell back to settings={} on any JSON parse error and
then overwrote the whole file, destroying the user's config (the likely
trigger is a UTF-8 BOM, same class as #2163). All four installers now
read utf-8-sig, refuse to modify a file that isn't a JSON object (naming
the path) instead of clobbering it, back up to <name>.graphify-bak before
any modifying write, skip the write when content is unchanged, and guard
the PreToolUse filter against non-dict entries.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 22:53:43 +01:00
safishamsiandClaude Opus 4.8 c18ec81741 test: sandbox HOME for the whole suite so installers can't touch real config (#2168)
Several test files call install/uninstall functions that operate on the
real user home (~/.claude, ~/.gemini, ~/.codebuddy, ~/.copilot), so
running the suite deleted/overwrote the developer's actual config. An
autouse conftest fixture now points HOME/USERPROFILE/LOCALAPPDATA at a
throwaway dir and clears CLAUDE_CONFIG_DIR/XDG_CONFIG_HOME for every
test. Supersedes the per-file sandbox proposed in #2057 (thanks
@erlandl4g for surfacing it).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 18:02:33 +01:00
MasterFede5andClaude Fable 5 33aa89c722 fix(extract,analyze): filter Swift/Foundation/SwiftUI builtins from resolution and god-node ranking (#2147)
_LANGUAGE_BUILTIN_GLOBALS and _BUILTIN_NOISE_LABELS covered only JS/TS and
Python, so on Swift codebases framework symbols (Foundation, NSLock, View,
Data, Sendable, ...) ranked as god nodes, and the Swift member-call resolver
could bind a builtin-typed receiver (let d: Data) to a same-named user symbol
in another file — the same phantom-edge shape #1726 fixed for TypeScript.

- extractors/base.py: add Swift stdlib value types, conformance protocols,
  Foundation types, and SwiftUI View/Color/Font to _LANGUAGE_BUILTIN_GLOBALS
- analyze.py: add the same set plus framework module names (Foundation,
  SwiftUI, UIKit, AppKit, Combine) to _BUILTIN_NOISE_LABELS
- extract.py: _resolve_swift_member_calls now skips builtin receiver types,
  matching the guard the TS/Python member-call resolvers already have (#1726)
- tests: god_nodes exclusion (parametrized) + Swift builtin-receiver
  no-bind regression + user-type-still-resolves guard

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-25 15:44:50 +01:00
Rishet Mehra 6107f14545 test(resolution): cover jsconfig/baseUrl module resolution (#2153)
Eleven cases: the webpacker repro (jsconfig + baseUrl, no paths) for
static, dynamic and extensionless specifiers; the same for tsconfig;
tsconfig winning over jsconfig in one directory; and four preservation
guards that pass before and after — declared paths and directory-prefix
aliases are not shadowed, relative imports are untouched, an absent
baseUrl changes nothing, and an external package is not fabricated.
2026-07-25 15:44:50 +01:00
Rishet Mehra 9be345951c fix(resolution): honor jsconfig.json and compilerOptions.baseUrl (#2153)
Non-relative imports produced no edge in a Rails/webpacker project, so
every module under `baseUrl` was orphaned and `affected` answered nothing.

Two defects. First, only `tsconfig.json` was probed, never
`jsconfig.json` — the plain-JS spelling of the same file, which
json_config.py already indexes, so the config's nodes appeared in the
graph while resolution ignored it entirely. Second, `baseUrl` was
consumed only as the base that `paths` targets resolve against, so a
config declaring `baseUrl` and NO `paths` produced an empty alias map and
every bare specifier died.

`_find_js_config` now probes both names, tsconfig winning within a
directory as tsc and editors do. `baseUrl` is exposed separately and used
as a resolution root of LAST RESORT, tried only when no declared alias
matches, so `paths` precedence (#1269, #927, #1531) is untouched. It is
deliberately not modelled as a synthesized `*` alias: that would score
(1, 0) in _match_tsconfig_alias and beat a declared non-wildcard
directory-prefix alias at (2, -len), silently shadowing it. The fallback
also returns a candidate only when it is a real file, so an external
package import is not fabricated into a <baseUrl>/<pkg> edge.

Threaded through the three regex-rescue dynamic-import paths (Svelte,
Astro, TS/TSX) as well as static resolution, since the issue reports both.
2026-07-25 15:44:50 +01:00
Rishet Mehra 8d8005b835 test(extract): cover Python decorator reference edges (#2154)
Nine cases: the issue's imported-decorator repro, same-file resolution to
the local definition, called and attribute decorators, stacked
decorators, class-qualified method owners, a decorated class, the #1050
@property class-qualification regression guard, and an absence control.
2026-07-25 15:44:50 +01:00
Rishet Mehra 794cf9ebb6 fix(extract): emit references edges for Python decorators (#2154)
Applying a Python decorator emitted no edge to the decorator symbol, so
`affected <decorator>` answered "No affected nodes found" for every
function it wraps — a silent false negative on reverse-impact queries.

TS/JS already emit these edges via `_ts_emit_decorator_edges`. The Python
`decorated_definition` branch walked its children only to propagate the
parent class id (#1050) and never looked at the `decorator` children.

Python now emits the same shape: a `references` edge with
context="decorator" from the decorated function/class to each decorator
symbol. Owner ids reuse the definition branches' own formulas, so the
edge lands on the node the walk creates. Targets go through
`ensure_named_node`, so an imported decorator becomes a sourceless stub
the corpus rewire collapses onto its real definition. Stacked, called
(`@retry(3)`) and attribute (`@app.route`) decorators are covered; the
attribute form targets the symbol, not the module alias, matching
`_ts_decorator_name`.
2026-07-25 15:44:50 +01:00
safishamsiandClaude Opus 4.8 66d8110a53 chore(release): 0.9.26
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 00:09:40 +01:00
safishamsiandClaude Opus 4.8 a4fb87d1bd chore: bump to 0.9.26; changelog for #2137/#2126/#2148/#2141/#2079/#2163
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 23:48:21 +01:00
safishamsiandClaude Opus 4.8 eebf030f5b test(extract): cover calls into a ${VAR}-sourced bash lib (follow-up to #2139)
The #2139 ${VAR} source handler now also records bash_sources so
resolve_bash_source_edges binds calls into the sourced lib's functions,
not just the source edge. Add the end-to-end oracle plus the previously
untested _bash_source_suffix guards (mid-path $, whole-var, .. traversal
fabricate nothing).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 23:47:25 +01:00
safishamsiandClaude Opus 4.8 7e955d223b fix(detect): honor ignore files saved with a UTF-8 BOM (#2163)
.gitignore/.graphifyignore/info-exclude read with encoding=utf-8 kept a
leading BOM (U+FEFF) on the first line, so the first pattern (e.g. *.log
or .fable-wt/) silently matched nothing and a BOM'd full-line comment
became a bogus pattern. git strips a single leading BOM; switching the
two ignore read sites to utf-8-sig matches git exactly (strips at most
one, file-start only).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 23:47:25 +01:00
HerenderKumar 0019fc4d90 fix(extract): resolve bash source edges built from ${VAR} paths (#2079)
`source "${BENCH_DIR}/lib/x.sh"` (the `dirname "${BASH_SOURCE[0]}"` idiom)
took the bare-name branch, which baked the unexpanded `${BENCH_DIR}` text
into the target id via `_make_id`. That id matches no node, so the edge was
flagged dangling and dropped at export — shared shell libraries looked
orphaned and were split into separate communities.

Detect a `$`-expansion in the source argument, strip the leading
expansion segment(s), and resolve the literal suffix against the script's
own directory (which is what the canonical idiom makes the variable). Emit
`imports_from` as INFERRED only when it resolves to a real file on disk;
skip otherwise instead of emitting a dead id. Bare-name sources keep their
existing behavior.
2026-07-24 23:41:28 +01:00
HerenderKumar bdcae25a26 fix(extract): resolve bash calls into sourced-file functions (#2141)
extract_bash only linked calls whose callee was defined in the same file, so a
call to a function from a `source`d library was silently dropped and shell
scripts looked disconnected from the libraries they use. The resolver for exactly
this, resolve_bash_source_edges, already existed with tests but had no call site
and no raw_calls/bash_sources to work from.

extract_bash now emits `bash_sources` (the files it `source`s) and `raw_calls`
(calls whose callee isn't defined locally), and the pipeline runs them through
resolve_bash_source_edges after the id-remap passes, so caller and function node
ids are final and the already-emitted source edge is de-duped. Resolution is
scoped to the source relationship: a call to an external command never binds to a
same-named function in an unsourced file, and bash raw_calls are excluded from the
generic global-name resolver for the same reason.
2026-07-24 23:37:14 +01:00
Rishet Mehra 0da6929e57 fix(hooks): match the post-checkout log prefix in the timeout fallback
The post-checkout body logs with [graphify] throughout, but the new
non-SIGALRM fallback used [graphify hook], so the same timeout read
differently depending on the platform. The post-commit body does use
[graphify hook] everywhere, so only the checkout copy was wrong.

Assert each body uses a single log prefix so this cannot drift again.
2026-07-24 23:37:14 +01:00
Rishet Mehra ca3113ac7b fix(hooks): arm the rebuild timeout without SIGALRM on Windows
The GRAPHIFY_REBUILD_TIMEOUT watchdog in both embedded rebuild bodies was
guarded by hasattr(signal, 'SIGALRM') with no else branch, so on Windows it
never armed and a hung rebuild survived indefinitely -- the exact tail case
the #791 timeout was added to catch.

Fall back to a daemon threading.Timer that prints the same message and calls
os._exit(1). The hard exit is deliberate: the process is already stuck, so a
clean shutdown may itself be blocked, and _rebuild_lock degrades to a no-op
yield on platforms without fcntl, so there is no lock to leave stale.
2026-07-24 23:37:14 +01:00
Rishet Mehra ce9ea7d7b4 test(hooks): surface bash failures in _shell_verdict helper
Assert returncode == 0 so a malformed case snippet fails fast with
stderr instead of silently returning an empty string. Addresses
Copilot review feedback on #2133.
2026-07-24 23:37:14 +01:00
Rishet Mehra e1e041b09b fix(hooks): accept Windows backslash paths in interpreter allowlist (#2126)
The post-commit/post-checkout hook's interpreter-detection allowlist
silently rejected valid Windows paths (C:\...\python.exe) on Git-Bash.
bash treats a lone backslash inside [...] as an escape that consumes
itself, so the emitted glob never matched a real backslash at runtime,
even though the pattern looked correct in Python's install-time re dialect.

Fix both allowlists (.graphify_python file path and shebang-parsed
launcher path) to emit [!a-zA-Z0-9/_.@:\\-], a doubled-backslash form
verified against bash and dash: it accepts Windows paths and still
rejects ; ` $ injection. The shebang allowlist additionally lacked :
and backslash entirely. Install-time _pinned_python() re is left as-is.

Add shell-runtime tests that execute the emitted case/esac glob directly
against Windows paths and shell metacharacters.
2026-07-24 23:37:14 +01:00
Rishet Mehra 26cac4192d test(extract): cover cross-file class-ref indirect_call suppression (#2137)
Copilot flagged that the #2137 regression test only exercised the
intra-file suppression path; a regression in the cross-file resolver
guard in extract.py would still pass. Add a cross-file test: class and
function imported from another module, asserting the imported class is
never an indirect_call target while a genuine imported callback still
emits its edge.
2026-07-24 23:37:14 +01:00
Rishet Mehra f6742bb6f0 fix(extract): exclude class refs from indirect_call edges (#2137)
Classes are callable via their constructor but are frequently referenced as
descriptive values, not invoked: ORM args (select(Model), db.get(Model, id)),
exception tuples (except (ErrorA, ErrorB)), and string-literal getattr resolving
to a same-named class. The indirect_call guard treated any callable-def target
identically, so these produced false edges (~41% of indirect_call edges in the
reported sample targeted classes), inflating centrality and traversals.

Track class defs in a callable_class_nids set parallel to callable_def_nids,
mark class nodes with a _callable_class attribute, and exclude class targets
from indirect_call emission in both the intra-file (_emit_indirect_by_name) and
cross-file resolver paths. Marker is stripped before output like _callable.

Covers all languages: both class-node creation sites (the generic
config.class_types branch and the Ruby Struct.new/Class.new/Data.define
synthesis) register into the new set.

Tradeoff: suppression is context-blind, so a genuine higher-order class
callback (e.g. map(Point, coords)) also loses its indirect_call edge. This is
far rarer than the false-positive noise removed and matches the issue framing.

Verified before/after on the same input: 4 class-targeted indirect_call edges
-> 0, function callbacks preserved.
2026-07-24 23:37:14 +01:00
safishamsiandClaude Opus 4.8 2fa6cd3d55 chore(release): 0.9.25
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 23:56:15 +01:00
safishamsiandClaude Opus 4.8 ba7f9ea9d8 chore: relicense from MIT to Apache-2.0
Apache 2.0 adds an explicit patent grant, a patent-retaliation clause,
and explicit inbound-contribution terms. MIT's sublicense right permits
relicensing the combined work, so this needs no per-contributor consent;
prior contributions were made under MIT and remain available under those
terms. The original MIT text is retained in LICENSE-MIT and referenced
from NOTICE.

- LICENSE: verbatim Apache License 2.0
- LICENSE-MIT: preserved MIT text for prior contributions
- NOTICE: attribution + pointer to LICENSE-MIT
- pyproject: license = "Apache-2.0" (PEP 639 SPDX), license-files, setuptools>=77

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 23:50:47 +01:00
safishamsiandClaude Opus 4.8 363f036e5e docs(readme): drop the broken star-history chart
The inline api.star-history.com SVG rate-limits on a repo this large and
serves a 503 instead of a chart, so the image was permanently broken.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 22:30:22 +01:00
safishamsiandClaude Opus 4.8 0d1f25c221 refactor(detect): remove dead .graphifyinclude handling (#2112)
The .graphifyinclude loader and its two matcher helpers had no consumers:
commit df40e4d (#873, index dot dirs) removed the blanket dot-prefix
exclusion and with it the only call sites, leaving detect() parsing the
file on every run and then discarding the result. A .graphifyinclude was
silently a no-op.

Delete _load_graphifyinclude, _is_included, _could_contain_included_path
and the orphaned assignment; add .graphifyinclude to _SKIP_FILES so a
leftover file no longer lands in unclassified; and print a one-time
stderr note when one is present at the scan root, pointing to ! negation
patterns in .graphifyignore. Bump to 0.9.25.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 20:35:54 +01:00
safishamsiandClaude Opus 4.8 ad53f751f9 chore(release): 0.9.24
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 19:46:09 +01:00
safishamsi 9b1ac65de5 docs: changelog for the XAML .cs-scan hang fix (0.9.24) 2026-07-22 19:31:42 +01:00
safishamsi 2da192db56 fix(extract): bound the XAML code-behind .cs scan so it can't hang
_xaml_csharp_class_nodes did `sorted(root.rglob("*.cs"))` where `root` comes from
_xaml_project_root walking up for a .csproj/.sln marker. On a standalone
extract_xaml call (no corpus boundary), a .xaml under a large/shared parent (a
temp dir, or a big monorepo) could resolve `root` to a broad ancestor, and the
rglob then recursively scanned the entire tree — effectively hanging (it stalled
the test suite intermittently once the shared temp dir grew). Replace the rglob
with an os.walk that prunes noise/hidden dirs (node_modules/.venv/.git/...) during
traversal and caps directories visited, so a real project scans fully while a
runaway root degrades to a fast, partial scan instead of a hang. Regression test
asserts a decoy .cs in node_modules is pruned and the real ViewModel still links.
2026-07-22 19:31:19 +01:00
safishamsi 8658cc3105 fix(skillgen): commit rendered skill artifacts for the #2106 traceability line (missed in 65b81bf) 2026-07-22 19:01:53 +01:00
safishamsi a3e283e109 docs: changelog for #2106 (0.9.24) 2026-07-22 18:41:21 +01:00
safishamsi 65b81bfa80 fix(skillgen): skill flow lists skipped-sensitive filenames, not just a count (#2106) 2026-07-22 18:40:19 +01:00
safishamsi 36b5e770eb fix(detect): stop the sensitive-file filter from dropping topic docs and real source (#2106)
The heuristic over-matched and silently dropped legitimate files:
- prose `.md`/`.rst` whose topic slug ends in a keyword (privacy-tokens.md,
  token-economics.md) — only code was exempt, not prose;
- the unbounded Stage-2 `service.account` substring (regex `.` wildcard) matched
  real source (google/oauth2/service_account.py) and prose slugs.
It also MISSED real secrets (.npmrc, .pypirc, secring, .git-credentials, and
case variants on case-insensitive filesystems), which were being indexed.

Fix: move service_account/aws_credentials to the boundary-checked keyword path
(so real source is spared, downloaded key files still drop), add a prose-note
carve-out (multi-word slugs indexed, bare `secrets.md`/`token.md` still dropped),
tighten id_rsa with a left boundary, add the missed secret dotfiles + secring,
lowercase the dir/segment comparisons, and count multi-dot slugs as multi-word.
Net effect is stricter on real secrets and stops the false-positive data loss.

Traceability: `graphify extract` now names the files skipped as sensitive (not
just a count), so a wrongly-flagged file is visible.
2026-07-22 18:40:11 +01:00
safishamsi 82c46e5358 docs: changelog for #2093/#2102/#2095/#2094 (0.9.24) 2026-07-22 16:19:26 +01:00
safishamsi 866d503b48 fix(dedup): order-independent gap-fill, source_file gate, _origin/None handling (follow-up to #2102) 2026-07-22 16:11:15 +01:00
Synvoya 5a4b207ddf fix(dedup): preserve same-source node attributes 2026-07-22 16:03:42 +01:00
safishamsi 16315f1956 fix(llm): parse claude-cli structured_output, not the prose result field (follow-up to #2095) 2026-07-22 15:57:54 +01:00
Yyunozor 7116a6f5f5 fix(llm): pin claude-cli output to a JSON schema when supported (#2076)
The claude-cli backend delivers the extraction schema in the user turn and
trusts the model to emit raw JSON. Newer Claude Code releases treat that
prompt as an agentic task and report the result in prose instead ("Knowledge
graph extracted — 21 nodes, 20 edges…"), so the graph parses empty, reads as
truncation, and adaptive-retry bisects without ever converging.

Pass --json-schema (structured output) when the CLI advertises it — probed
once via `claude --help` and cached — so the object shape is constrained
regardless of prompt framing. Older CLIs that predate the flag keep the
user-turn prompt as a fallback. The `result` envelope still carries the JSON
string, so the parse path is unchanged.
2026-07-22 15:51:03 +01:00
safishamsi 8c5f585587 test(extract): external-alias negative + warm-cache coverage for #2082 (follow-up to #2093) 2026-07-22 15:40:00 +01:00
Yyunozor cc70085f3b fix(extract): resolve calls edges through an aliased Python import (#2082)
`from pkg import mod as alias` correctly emits the file-level
`imports_from` edge, but every downstream `alias.func()` call was
dropped: the module arm of the cross-file member-call resolver
(#1883, _resolve_python_member_calls in extract.py) matches a call
receiver against the imported module's own file stem, with no
awareness that the local binding in the importing file can be a
different name. `from pkg import mod` / `mod.func()` resolves because
the receiver ("mod") equals the stem; aliasing breaks the match
because the receiver ("alias") never does, and the calls edge
silently disappears while imports_from stays present -- the graph
looks connected, only the symbol-level reverse query comes back
empty. `import pkg.mod as alias` regresses the same way through the
same resolver.

Root cause is a missing propagation, not a missing feature: the local
alias is already parsed correctly in two places (_python_imported_names
in extractors/resolution.py, and the aliased_import branch of
_import_python in extract.py) but discarded before it reaches the
edges the module arm reads.

Fix threads the alias through as a `local_alias` field on the
`imports`/`imports_from` edge (mirroring the existing `target_file`
transient-hint pattern, #1814, including its pop-once-consumed
hygiene so the hint never reaches graph.json):
- _import_python now splits the alias off `import pkg.mod as alias`
  and stamps it on the edge instead of only using it to compute the
  bare module_name.
- _SymbolResolutionFacts.module_imports gains a 4th `local_name` slot
  so the `from pkg import submod [as alias]` submodule path (#1146)
  carries the binding through to _apply_symbol_resolution_facts,
  which now stamps `local_alias` on the edge whenever it differs from
  the submodule's own stem.
- The module arm's receiver match now accepts the tracked alias in
  addition to the module's real stem, keyed per (importing file,
  target module) so two files aliasing the same module differently
  each match their own binding.
- extract() pops `local_alias` off every edge right after
  run_language_resolvers runs, and build_from_json drops it from edge
  attrs too -- the same two spots target_file is dropped at (#1814),
  except the extract()-side pop has to happen AFTER the resolver
  reads the field, not at the earlier point _disambiguate_colliding_
  node_ids already pops target_file: that function runs before
  run_language_resolvers, so popping local_alias there would strip it
  before the resolver ever sees it and silently undo the fix above.

Known limitation, left out of scope: two different aliases bound to
the same module in the same file only resolve the last one
registered, since the match is one alias slot keyed per (importing
file, target module) -- not a regression, since the parent resolved
neither.

Adds five regression tests in tests/test_extract.py: the issue's own
shape (`from pkg import gate as m_gate`), its try/except-guarded
variant (the issue's literal repro, confirming the drop is
independent of try: nesting), the adjacent `import mathlib as m` and
dotted `import pkg.gate as g_alias` forms, and the relative `from .
import gate as r_gate` form -- plus an assertion that `local_alias`
never survives into the returned edges. All fail on the parent commit
with the exact missing-edge symptom and pass after the fix. Full
suite: 3554 passed vs. 3549 on the unfixed parent, a delta of exactly
these five new tests; ruff clean. #2080's calls-edge-direction
regression tests (test_serve.py) still pass unchanged.
2026-07-22 15:32:08 +01:00
safishamsi 4c759b6dd6 fix(cli): deterministic tie-break for grouped explain tail (follow-up to #2094) 2026-07-22 15:31:56 +01:00
Yyunozor 0ef452c570 fix: group cut connections by file on explain for high-degree nodes
`graphify explain "<node>"` sorts a node's connections by neighbor
degree and shows only the top 20, appending a bare "... and N more"
for the rest. On a high-degree node (a logging/error helper called
from dozens of places is typical) that leaves the exact question
explain is meant to answer - "who calls this, what's the impact?" -
unanswered for 97% of the callers, with nothing pointing at where
they live (#2009).

The top-20 list and its ordering are unchanged (no behavior change
for nodes at or under the cutoff). Past it, the cut connections are
now grouped by (direction, source_file) with counts and printed
under a "Grouped by file:" section, sorted by count descending, so
the caller/callee distribution is visible without falling back to a
repo-wide grep. The aggregation itself is capped at 20 files with
its own "... and N more files" line for the pathological case where
the remainder is spread across more files than that.

Full per-caller detail behind a flag (--callers --all / --group-by=dir
as proposed in the issue) is left for a follow-up: it's a larger,
more opinionated surface (flag naming, pagination semantics) than
the literal complaint needs, and the default output no longer hides
the answer either way.

Four regression tests in tests/test_explain_cli.py: the pre-existing
truncation notice on a 30-connection node is unchanged, the grouped-
by-file output carries real counts (3 files, one at 4 and two at 3)
that sum back to exactly the cut total (no silent loss), a
byte-for-byte no-op check for nodes at/under the cutoff, and a
boundary check pinning the cutoff itself at exactly 20 connections
(no section) vs exactly 21 (one grouped entry) — the earlier tests
sit well clear of the edge and wouldn't catch a future off-by-one.
2026-07-22 15:27:07 +01:00
safishamsi e32c9f431c chore: bump to 0.9.24; changelog for #2080/#2069/#2075/#2085 2026-07-21 21:47:51 +01:00
safishamsi 53d0f88e7b test(serve): guard + direction tests for dangling _src/_tgt (follow-up to #2080) 2026-07-21 21:46:42 +01:00
Yyunozor 4ace95182b fix: preserve calls edge direction in graphify query output
`graphify query` builds an undirected nx.Graph (so BFS/DFS can explore
both callers and callees of the seed node), but its text renderer
assumed the BFS/DFS visit order (u, v) was always the edge's
(source, target). On an undirected graph that assumption only holds
when the seed happens to be the caller: seeding on the callee makes
BFS/DFS visit the callee first, so a `caller --calls--> callee` edge
was rendered backwards as `callee --calls--> caller`. graph.json's
own source/target fields stay correct on disk; only the query
rendering was wrong.

`graphify path` and `graphify explain` don't have this problem
because they force directed=True on load (#849, #853), and the MCP
query_graph tool's _load_graph() does the same. Doing that for CLI
`query` too was tried and reverted: forcing a DiGraph makes
G.neighbors() return successors only, so a query seeded on a
leaf/sink node (no outgoing edges) found zero neighbors instead of
its callers — a recall regression, not just a display fix, and it
would make the CLI and MCP query tools diverge in what they discover
even though they'd render direction identically.

Fix instead mirrors the _src/_tgt pattern graphify/build.py already
uses for the same underlying problem (undirected storage loses
direction): the CLI now stashes each link's true source/target on
its edge data as _src/_tgt before constructing the (still undirected)
graph, and _subgraph_to_text renders EDGE lines from _src/_tgt when
present, falling back to (u, v) otherwise. Traversal itself is
unchanged, so recall is unaffected — verified against the unpatched
CLI, the node counts returned for the same seeds are identical before
and after this fix, only the printed edge direction changes.

Adds two regression tests in tests/test_query_cli.py seeding the same
`calls` edge from both endpoints; the callee-seeded case fails on the
prior code with the exact backwards-edge symptom above.
2026-07-21 21:45:53 +01:00
safishamsi deb2620be9 feat(serve): announce get_neighbors/get_community truncation at the top + tests (follow-up to #2069) 2026-07-21 21:39:32 +01:00
B fef9dbb5e7 feat(serve): honor a token_budget on get_neighbors/get_community
get_neighbors and get_community render every edge/member line unbounded — on a
god node or a large community that floods an MCP client's context window with
100KB+ of text in one tool result. query_graph already solves this with the
~3-chars/token cut in _subgraph_to_text; this applies the same budget rule to
the two line-list tools via a shared helper (_cut_lines_to_budget): cut at a
line boundary, report how many lines were dropped, and point at the narrowing
path (relation_filter / get_node). Default 2000 like query_graph; output under
budget is byte-identical to today.
2026-07-21 21:36:30 +01:00
safishamsi a59abaf99d docs: --code-only is an extract flag, not a skill flag (follow-up to #2075) 2026-07-21 21:34:47 +01:00
HerenderKumar bb8f5bd675 docs(cli): surface --code-only in the extract usage and README (#2071)
The top-level `graphify --help` has listed --code-only since #1734, but the
`graphify extract` usage string and the README never mentioned it. A user
evaluating graphify on a "can this run with no network call" constraint sees
the extract usage / README first and can conclude the flag doesn't exist.

Add --code-only to the extract usage line, name it in the Privacy section and
the command reference, and add a test asserting the usage advertises it.
2026-07-21 21:33:12 +01:00
HerenderKumar abb85ccb03 docs(readme): troubleshoot an older graphifyy shadowing uv run (#1540)
`uv run --with graphifyy python -m graphify` runs the system interpreter, so an
older `graphifyy` in system site-packages loads before the uv-managed one — with
no error. Env overrides like OPENAI_BASE_URL are then ignored and requests 401
against the default endpoint. The existing `skill is from graphify X, package is
Y` warning is the real fingerprint, but users dismiss it as a stale skill.

Add a troubleshooting entry next to the uvx-resolution one: name the symptom,
show how to confirm which module actually loaded, and point at
`uvx --from graphifyy` / uninstalling the stale copy.
2026-07-21 21:32:43 +01:00
safishamsi c83085cfef docs: date 0.9.23 for release 2026-07-21 18:58:17 +01:00
safishamsi 1fbc623271 fix(query): report real call-site lines + stop silent query truncation (benchmark)
Two correctness defects found in a head-to-head benchmark of 0.9.22.

Caller line numbers: explain/affected/get_neighbors/query printed the caller
node's def line for an incoming call, presented as a precise citation, so
click-through landed in the wrong place. The `calls` edge already carries the
true call-site line (engine.py sets it); every caller/relation listing now reads
the traversed edge's source_file:source_location, falling back to the node's own
line only when the edge lacks one.

Silent query truncation: rendered nodes were degree-ordered (a low-degree
definition node ranked last, cut first), the queried symbol wasn't guaranteed to
appear, and the truncation marker sat only at the end so silence read as absence.
Nodes are now ranked by hop distance from the seeds (deterministic), the seed the
question named is rendered first and never truncated, and a prominent TRUNCATED
notice at the top states shown/total counts and how to widen the budget. Also
rewires the seed-first ordering the renderer already supported — a branch merge
had silently dropped the `seeds=` argument, leaving it dead code.
2026-07-21 18:39:05 +01:00
safishamsi 10b710561a fix(extract): harden #2072 src-layout resolution (adversarial-review fixes)
Three issues found reviewing #2072:
- The import-edge repoint loop matched by target id regardless of the edge's
  language, so a non-Python dotted import (C# `using Pkg.Mod;`, Java/Go) whose
  dangling target coincided with a Python alias got repointed onto a Python file,
  fabricating a cross-language import. Gate the rewrite on the edge being
  Python-sourced.
- The resolver ancestor walk probed package dirs too, resolving an absolute
  `from helpers import x` to a sibling in the current package (Python-2 implicit-
  relative semantics) even when `helpers` is external. Only probe sys.path-root
  candidates (ancestors without their own __init__.py).
- Bound the __init__.py package-root chain walk by the path depth so a
  pathological `/__init__.py` can't loop.
Added a cross-language-guard regression test; fixed the tautological (or->and)
ambiguity assertion.
2026-07-21 14:22:50 +01:00
safishamsi afa7c0d9d3 chore: bump to 0.9.23; changelog for #2062/#2074/#2073/#2068/#2072; date 0.9.22 2026-07-21 13:45:49 +01:00
safishamsi bb467634c9 fix(extract): resolve Python imports regardless of scan root (src-layout) (#2072)
Python absolute imports were resolved only against the scan root, and file-node
ids are scan-root-relative, so a src-layout project (code under src/) lost most
of its imports/imports_from edges when scanned from the repo root — the dangling
edges were silently dropped, so the graph looked complete but wasn't. The chosen
scan root thus silently changed the graph.

Two fixes: (1) _resolve_python_module_path probes the scan root first, then walks
up from the importing file toward the root so a nested package root (src/pkg)
resolves (mirrors the Lua upward walk); (2) a Python post-pass detects each
file's package root via its __init__.py chain and repoints absolute-import edge
targets (dotted-module id -> real file-node id), guarded against shadowing an
existing id and against ambiguous aliases claimed by >1 file. Result: byte-
identical import edges whether scanned from the repo root or from src/.
2026-07-21 13:44:49 +01:00
safishamsi cdeba1dcb7 fix(build): ghost-merge keys on full source_file, not bare basename (#2068)
build_from_json's #1145 ghost-duplicate merge keyed on (Path(source_file).name,
label), discarding the directory, so unrelated nodes from different files sharing
a common basename (index.md, README.md, ...) and a generic label were silently
merged onto one survivor with their edges rewired — corrupting multi-corpus doc
graphs. The AST/LLM ghost twins the merge legitimately targets always share the
same source_file, so keying on the full normalized source_file preserves #1145
while making cross-directory false merges impossible. This subsumes the
#1753/#1257 cross-file ambiguity guard (now removed as dead code). Independent of
the #2032 label pass. Updated the #1257 test to the now-correct precise merge.
2026-07-21 13:03:34 +01:00
safishamsi 87c870495f fix(label): --no-label placeholders no longer permanently suppress real labels (#2073)
A `cluster-only --no-label` run wrote "Community N" placeholders into
.graphify_labels.json plus a matching .sig, and the reuse path treated them as
fresh, so real labels were never regenerated on later runs. Two fixes: (a) don't
persist the labels sidecar (or its .sig) on a placeholder-only run, so a later
run generates real labels; (b) treat a stored "Community {cid}" as absent in the
reuse path so an already-polluted sidecar self-heals via the hub labeler while
genuine labels are still reused with no LLM call. The watch/update rebuild had
the same placeholder-perpetuation twin — fixed alongside.
2026-07-21 12:59:10 +01:00
safishamsi b194301c05 fix(path): deterministic route + honest edge relation, not fabricated calls (#2074)
`graphify path` (and the MCP shortest_path tool) ran shortest_path over
G.to_undirected(as_view=True), whose neighbor iteration is a hash-seeded set
union, so among equal-length paths BFS returned a route that varied per process.
Build a sorted, materialized undirected graph so the chosen path is canonical.

The hop label also printed a relation read from an arbitrarily-collapsed parallel
edge, so it could show `calls` on a pair that only carries `references`. Force
multigraph on the cli path reload so parallel links survive, and render the
ACTUAL stored relation(s) via edge_datas, falling back to an honest "related"
when the edge has none. Serve's shared graph is left untouched (its degree feeds
query-seed tie-breaks); the fix is applied locally in both path readers.
2026-07-21 12:54:58 +01:00
safishamsi b96effd3aa fix(install): uninstall must not delete a user's ### graphify H3 section (#2062)
The uninstall strip used an unanchored regex `## graphify`, which matched inside
a user's `### graphify` heading and deleted hand-written content; the
`marker not in content` guard was a substring test that passed on the same
mention. Add a shared `_remove_marker_section` helper that matches the heading
only when a line is exactly the marker (mirroring the install-side #1688
hardening), running each section to the next same-level heading or EOF, and
returning None (leave the file untouched) when no exact heading exists. Replace
all six strip sites: GEMINI.md, copilot-instructions.md, AGENTS.md, CLAUDE.md
(_strip_graphify_md_section), CODEBUDDY.md, and the H1 skill-registration
(_remove_claude_skill_registration, which had the same bug with `# graphify`).
2026-07-21 12:40:49 +01:00
safishamsi abff1b1ca4 docs(readme): surface the graphify.com waitlist above the fold
GitHub is the top organic source of waitlist signups, but the only path to the
site was the logo and a CTA at the very bottom of the README. Add a short,
plain-voice waitlist line right after the value proposition, and change the
Enterprise-section CTA from "Learn more" to an explicit "Join the waitlist".
2026-07-20 17:08:15 +01:00
safishamsi 5b05f0d9ab fix(cli): disambiguate file labels on the --no-cluster extract path too (#2032)
The build_from_json label pass only covered the clustered/update paths; the raw
`extract --no-cluster` path writes the merged node list directly, so colliding
basenames stayed un-disambiguated there. Factor the logic into a shared
_file_label_reassignments core with a list-based variant
(disambiguate_file_labels_in_nodes) and apply it on the raw merged nodes.
Caught by the clean-venv edge-case battery.
2026-07-20 16:35:14 +01:00
safishamsi 8ce9f6b906 docs: changelog for the 0.9.22 data-integrity/correctness batch 2026-07-20 16:25:11 +01:00
safishamsi fecf9aa76b fix(build): disambiguate colliding file-node labels for discovery (#2032)
In directory-per-entrypoint repos (Supabase Edge Functions, Next.js page.tsx,
Rust mod.rs, Python __init__.py) many files share a basename, so basename-only
file-node labels collided and `explain`/free-text discovery couldn't resolve
them — exactly the highest-value files. build_from_json now runs a final pass
that gives colliding-basename file nodes the shortest unique directory-qualified
label (`process-order/index.ts`); unique basenames stay bare, and node ids/edges
are never touched. The pass runs after the alias-competition (which still needs
bare basenames), is idempotent (labels derive from source_file), and the
downstream file-node predicates (analyze god-nodes, tree_html, serve lookup)
recognize the qualified form via a shared _is_file_node_label helper.
2026-07-20 16:25:11 +01:00
safishamsi f1405dd7c1 fix(extract): nested types get a contains edge from the enclosing type (#2040)
In _extract_generic's class branch the `contains` edge was hard-coded to source
from the file node, so a nested class/object/trait attached to the file instead
of its enclosing type across ~19 languages (only C# even flagged the node with
is_nested_type, and still emitted no edge to the parent). The edge now sources
from parent_class_nid when set, else the file node — keeping the containment
tree connected (file -> Outer -> Inner). A `!= class_nid` guard avoids a
self-loop when same-name nesting collides ids (class ids omit the enclosing
name). The C# is_nested_type flag is retained (load-bearing for cross-file
resolution). Methods were already parent-sourced and are unaffected.
2026-07-20 15:40:32 +01:00
safishamsi 1f4e3b2fe1 fix(cli): wire god-nodes subcommand + accept --output alias on extract (#2004)
Part 2: `god_nodes` was an analyzer, an MCP tool, and a README-advertised
capability, but `graphify god_nodes` errored with "unknown command". Add a
read-only `god-nodes`/`god_nodes` subcommand mirroring `affected` (--graph,
--top, --json), routing labels through sanitize_label.

Part 3: `--output DIR` on `extract` was silently dropped (output fell back to
the default dir). It is now an alias of `--out` (both space and =forms), matching
what `graphify tree` already documents. Help/usage text updated.

Part 1 (affected/reverse-dep import-id mismatch) is deferred — a build-time
id-resolution change, tracked separately.
2026-07-20 15:35:40 +01:00
safishamsi db410d0d09 fix(detect): stop silent data loss from env-dir pruning and absolute-path sidecars (#2058, #2059)
#2058: `_is_noise_dir` treated any directory named `env`/`.env`/`*_env` as a
Python virtualenv and pruned it during the walk — before `.graphifyignore`
negation, with zero trace in any returned bucket. Real source dirs with those
names (common in UVM/ASIC verification trees) were silently lost. The venv
heuristic for those names is now gated on actual markers (`pyvenv.cfg`,
`bin`/`Scripts/activate`, `lib/python*`, `conda-meta/`); `venv`/`.venv`/`*_venv`
stay name-only. Pruned-as-noise dirs are recorded in a new `pruned_noise_dirs`
bucket for traceability, and extract.py's walk call sites pass the parent so
genuine venvs are still marker-checked and pruned.

#2059: Office and Google-Workspace sidecars were named with a hash of the
resolved ABSOLUTE source path, so the same tracked file in two clones/worktrees
produced two differently-named byte-identical sidecars — unbounded duplicates
when graphify-out/ is committed, each ingested as a distinct source doc. The
hash is now over the scan-root-relative (NFC-normalized) path, stable across
checkouts while still disambiguating same-stem files; out-of-root sources fall
back to the old absolute form. Also fixes the same bug in google_workspace's
`_sidecar_path` (which additionally never had the #1226 NFC fix).
2026-07-20 15:28:59 +01:00
김재현 67608c21b0 test(serve): pin generic ValueError message against clause-order regression
Per review on #2017 (thanks @HerenderKumar): add a guard asserting a
non-decode ValueError (e.g. a non-.json path) still prints the plain
"must be a .json file" message, not the corrupted-graph hint. Locks in
the except-clause order from the parent fix so a future refactor can't
silently collapse the two branches back together.
2026-07-20 15:02:54 +01:00
김재현 b890ca6590 fix(serve): reorder except clauses so the corrupted-graph message is reachable
json.JSONDecodeError subclasses ValueError, so the broader
`except (ValueError, FileNotFoundError)` clause always matched first,
making the intended "graph.json is corrupted (...). Re-run /graphify
to rebuild." recovery hint dead code — users with a truncated graph.json
got the bare json.JSONDecodeError message instead, contradicting the
behavior SECURITY.md documents for this exact threat.

Move the json.JSONDecodeError clause first so it actually catches.
Audited the rest of serve.py's exception handlers for the same
narrower-after-broader ordering bug; found no other instance.

Fixes #2005.
2026-07-20 15:02:54 +01:00
safishamsi 6bbc9d14c6 chore: bump to 0.9.22; date 0.9.21 changelog
0.9.22 carries the #2051 remote-source eviction follow-up.
2026-07-20 14:00:54 +01:00
safishamsi f6974eae7c fix(watch): don't evict remote-source nodes after URL slash-collapse (#2051 follow-up)
The #2051 disk-absence sweep guarded remote/virtual sources with a literal
`"://"` check. But the write-side path normalization (Path.as_posix) collapses
the double slash, so a stored `gdoc://x` reads back as `gdoc:/x` on the next
update; the literal guard then missed it and the node fell into the disk-absence
branch (`Path('gdoc:/x').exists()` is False), evicting it on the second
`graphify update`. Match the scheme with a regex tolerant of the collapse, with
a 2+ char scheme so a Windows drive letter (C:/) is not misread as remote.

Regression test runs three consecutive updates and asserts the remote node
survives every one.
2026-07-20 13:57:12 +01:00
safishamsi 86fd1e4205 chore: changelog for 0.9.21 data-integrity fixes (#2051/#2056/#2014/#2012/#2015) 2026-07-20 13:30:33 +01:00
safishamsi 9c2e0fcfa2 fix(skillgen): stamp only produced-output files in the update runbook (#2015)
The --update runbook's Step 9 stamped the entire detected corpus into the
manifest, so a semantic file (doc/paper/image) whose chunk failed or was omitted
was recorded as done and never re-queued on the next update — losing its content
permanently. The runbook now builds the manifest the way the library extract
path does: cli._stamped_manifest_files stamps only files that actually produced
nodes/edges/hyperedges, dispatched-but-empty files have their stale hash cleared,
and scan_corpus drops newly-excluded in-root rows.

Applied to the Claude, Aider, and Devin skill bodies and the shared update
reference; all 134 artifacts regenerated. gen.py gains a sanctioned monolith-
diff predicate for the new stamping lines.
2026-07-20 13:30:26 +01:00
safishamsi 6a56763051 fix(build): form-insensitive prune + scan-root marker (#2012)
build_merge now prunes a deleted file's nodes, edges, and hyperedges regardless
of whether their stored source_file is absolute or relative. When the caller
passed no root (the --update runbook), a node that kept an absolute path slipped
past the relative prune set and the deleted file's graph survived silently.
Matching is now form-insensitive (raw, normalized-relative, then an absolute-
identity fallback); a re-extracted file is still never pruned (#1796 preserved).

`graphify extract` also writes the .graphify_root marker after every graph write
so a later build_merge relativizes deleted-file paths correctly even under a
custom --out (its grandparent-of-graph.json fallback pointed at the wrong dir).

Regression tests in tests/test_build_merge_hyperedges_and_prune.py.
2026-07-20 13:29:54 +01:00
safishamsi 94189bac3c fix(watch): correct semantic-node eviction/preservation on update
Three silent-data-loss fixes in the update/reconcile path:

- #2051: a full `graphify update` now evicts semantic nodes whose non-AST
  source (a .txt/.pdf/.png with no code extractor) was deleted from disk.
  The corpus sweep only checked re-extractable files, so deleted docs'/images'
  LLM nodes survived as authoritative forever. Disk absence is now the deletion
  signal; remote/virtual sources (`://`) are left untouched.
- #2056: an incremental rebuild whose change set names a present-but-
  unextractable file no longer treats it as a deletion (which evicted its
  semantic nodes and disabled the shrink guard). The guard now falls through to
  per-source accounting instead of a wholesale bypass on any deletion.
- #2014: code-typed nodes the semantic pass surfaces from within a document now
  count as that doc's semantic layer, so a rebuild doesn't re-scan and drop them.

Regression tests for each in tests/test_watch.py.
2026-07-20 13:29:44 +01:00
safishamsiandClaude Opus 4.8 78a1b80b43 chore: begin 0.9.21 cycle + changelog for #1940/#2027/#2030/#2037/#1983
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 11:42:26 +01:00
safishamsiandClaude Opus 4.8 e7ad693b5b fix(extract): don't guess an ambiguous barrel re-export (follow-up to #2034)
The barrel-chain resolver keyed (source, symbol) -> target as last-write-wins, so
a barrel re-exporting the same local name from two modules collapsed an importer's
edge onto whichever was learned last — a fabricated wrong edge. Learn into a set
per key and refuse to resolve when a name maps to more than one target; the edge
falls to the dangling-canonical fallback (dropped at build) instead. Adds a
regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 11:41:44 +01:00
safishamsiandClaude Opus 4.8 868f75de38 fix(llm): OLLAMA_HOST fallback in detect_backend + default port (follow-up to #2019)
The PR resolved OLLAMA_HOST for the client base_url but not in detect_backend(),
so the headline #1940 case (OLLAMA_HOST set, no --backend) still errored with
"no LLM API key found". detect_backend() now uses _resolve_ollama_base_url (empty
default stays falsy, so ollama remains opt-in and never shadows a paid key). Also
default the port to 11434 when OLLAMA_HOST omits it (a bare host would otherwise
resolve to port 80), and handle bare-port / :port forms.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 11:41:43 +01:00
HerenderKumar fab28ab7bc fix(extract): resolve alias re-exports and imports through barrels to the defining symbol (#1983) 2026-07-20 11:31:58 +01:00
oleksii-tumanov c57d5711ca fix(extract): honor persisted excludes on re-extract 2026-07-20 11:31:36 +01:00
oleksii-tumanov b35898aafc fix(extract): initialize detection for pathless Postgres 2026-07-20 11:31:36 +01:00
김재현 220a675265 fix(llm): fall back to OLLAMA_HOST when OLLAMA_BASE_URL is unset
Ollama's own server has no OLLAMA_BASE_URL concept — it reads
OLLAMA_HOST (https://docs.ollama.com/faq#how-do-i-configure-ollama-server).
graphify only ever read OLLAMA_BASE_URL, so anyone who configured Ollama
the way its own docs describe (OLLAMA_HOST) had graphify silently ignore
it and fall back to the localhost:11434 default.

Add _resolve_ollama_base_url(default): OLLAMA_BASE_URL still wins when
set (unchanged behavior, graphify's existing convention for OpenAI-
compatible base_url overrides across backends). Otherwise falls back to
OLLAMA_HOST, normalized into an OpenAI-compatible URL (adds a scheme if
missing, ensures a trailing /v1). Wired into the BACKENDS dict's ollama
entry and the two ollama_url call sites that read the env var directly.

Fixes #1940.
2026-07-20 11:29:22 +01:00
Endogen c105633b56 fix: drop collapsed import self-loops 2026-07-20 11:29:22 +01:00
safishamsiandClaude Opus 4.8 edec9eabec docs: date 0.9.20 for release
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 22:24:02 +01:00
safishamsiandClaude Opus 4.8 6534a87c28 ci: add PyPI trusted-publishing workflow (publish.yml)
Publishes graphifyy to PyPI via GitHub OIDC on a published Release — no API
token. Builds sdist+wheel with uv, guards that the package version matches the
release tag, twine-checks, then uploads via pypa/gh-action-pypi-publish with
id-token: write and the `pypi` environment. Requires a matching GitHub trusted
publisher configured on PyPI (Owner Graphify-Labs, repo graphify, workflow
publish.yml, environment pypi).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 22:23:13 +01:00
safishamsiandClaude Opus 4.8 4f9752ceb0 chore: point project URLs at the canonical Graphify-Labs/graphify repo
Homepage/Repository/Issues were stale from the org move (safishamsi/graphify).
Aligning them to Graphify-Labs/graphify fixes the PyPI "Issues" link and is a
prerequisite for PyPI to mark the Repository link Verified once releases publish
via a GitHub trusted publisher.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 22:20:10 +01:00
safishamsiandClaude Opus 4.8 a30e933c6a chore: begin 0.9.20 cycle + changelog for #1986/#1987/#1990/#1991/#1983
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 19:13:33 +01:00
shazeb 08166306ba fix(cache): anchor semantic cache writes to cache_root so --out round-trips (#1990, #1991)
With `graphify extract --out <dir>`, the semantic cache write and read
sides disagreed on both location and key anchoring, breaking the cache
round-trip in two ways:

- Checkpoints (#1990): `_checkpoint_chunk` called `save_semantic_cache`
  with only `root=target`, so per-chunk recovery checkpoints were written
  under `<corpus>/graphify-out/` while the reader consulted
  `<out>/graphify-out/` — creating an unwanted graphify-out/ inside the
  analyzed source tree and making every interrupted run re-extract (and
  re-bill) completed chunks.

- Final save (#1991): cli.py passed `root=out_root`, so corpus-relative
  `source_file` paths resolved against the --out directory, failed
  `p.is_file()`, and every result group was silently skipped — the cache
  the reader would consult was never populated at all, with no warning.

Fix, following the split the AST cache already uses (#1774):

- `save_semantic_cache` and `check_semantic_cache` gain a `cache_root`
  parameter mirroring `load_cached`/`save_cached`: `root` stays the
  source-key anchor (content-hash keys, source_file resolution and
  relativization), `cache_root` selects where cache files live. Omitting
  it keeps `root` for both, so existing callers are unchanged.
- `extract_corpus_parallel` plumbs `cache_root` into `_checkpoint_chunk`.
- cli.py extract passes `root=target, cache_root=out_root` at the cache
  read, the checkpoint path, and the final save, and re-anchors the
  prune sweep's live hashes to `target` (keys anchored to out_root would
  mismatch every entry and sweep the fresh cache as orphaned).
- `save_semantic_cache` now warns loudly when every result group is
  dropped because its source_file does not resolve to a real file — the
  silent-0-writes failure mode #1991 asked to surface.

Regression tests cover: checkpoint written under cache_root (not the
corpus, no corpus graphify-out/ created), recovery read finds the
checkpoint via the same root/cache_root split, the final-save call shape
writes entries where the reader looks, the all-groups-dropped warning,
and backward compatibility when cache_root is omitted.

Fixes #1990
Fixes #1991
2026-07-18 19:09:53 +01:00
shazeb 0224bcaea4 fix(install): fire the search nudge on Claude Code's Grep tool, not just Bash (#1986)
ee1df22 narrowed the Claude Code search-guard matcher from "Glob|Grep" to
"Bash" on the premise that dedicated search tools were removed and searches
go through Bash. Current Claude Code routes content search through its
first-class Grep tool (its Bash tool description actively steers away from
shell grep), so the graphify-first nudge never fired on the agent's primary
exploration path and the graph was silently bypassed.

Three-part fix, per the issue's analysis:

- Matcher: "Bash" -> "Bash|Grep" in _claude_pretooluse_hooks. Glob already
  fires the read nudge via "Read|Glob", so Grep was the only orphaned tool.
- Guard body: the hook-guard search branch only inspected tool_input.command,
  which a Grep call doesn't carry (it has pattern/path/glob). A Grep-shaped
  input (pattern present, no command) is now treated as a search — it IS one
  by definition — and nudges whenever a fresh graph exists. The Bash
  token-matching path is unchanged, and a command-carrying input never
  triggers the Grep shape, so non-search Bash calls stay silent.
- Idempotency: "Bash|Grep" added to the four install/uninstall dedup filters
  (claude + codebuddy), so upgrading replaces the stale "Bash" hook in place
  instead of appending a duplicate — verified against a pre-fix settings.json.

Tests: new regression tests feed Grep-shaped tool_input through
hook-guard search and assert the nudge (with graph), silence (without),
valid PreToolUse JSON, and no blocking; plus a guard that a non-search Bash
command with a stray pattern key does not nudge. Existing matcher assertions
updated across test_search_hook/test_install/test_claude_md/test_codebuddy/
test_hook_strict. Hook+install suites: 397 passed. Full suite: 3224 passed;
the 13 failures are pre-existing on clean v8 in this environment.

Fixes #1986
2026-07-18 19:07:16 +01:00
varuntej07 faa0ac2984 fix(install): emit hook exe paths with forward slashes so Git Bash does not strip them
Claude Code runs command-type PreToolUse hooks through Git Bash by default on
Windows. The resolved exe was emitted as a raw backslash path and quoted only
when it contained a space, so a space-free path like C:\Users\me\graphify.EXE
reached settings.json unquoted. Git Bash treats the unquoted backslashes as
escapes and strips them, producing 'C:Usersmegraphify.EXE: command not found',
so every graph guard silently fails. Normalize the path to forward slashes in
_resolve_graphify_exe (a no-op on POSIX), fixing the Claude, Gemini, and Codex
hook emitters at once.
2026-07-18 19:06:51 +01:00
oleksii-tumanov e5a4b51d87 fix(extract): rewrite alias re-export targets 2026-07-18 18:53:28 +01:00
safishamsiandClaude Opus 4.8 9bf14a4931 docs: rebrand the built-on-graphify section to graphify Enterprise + add graphify.com website badge
Rename the "Penpax" section to "graphify Enterprise" (linking graphify.com) and
add a Website badge to the Community and links footer.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 14:59:12 +01:00
safishamsiandClaude Opus 4.8 b77a01ec68 docs: correct #1971 credit (@Mzt00 fix, @JensD-git report; not @mzt006)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 14:34:16 +01:00
safishamsiandClaude Opus 4.8 fb992ce15e docs: cut 0.9.19, document install --strict, fix #1814 credit
Stamp the 0.9.19 release date, add a README note for the strict PreToolUse hook
(graphify install --project --strict), and credit both the #1814 reporter
(@Greg-Moskalenko) and the fix author (@alphanury).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 12:54:59 +01:00
safishamsiandClaude Opus 4.8 5b8480a2c7 docs: changelog entries for the #1989/#1971/#1975/#1978/#1980 fixes
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 12:31:40 +01:00
safishamsiandClaude Opus 4.8 caa6f9edb9 fix(extract): persist --no-gitignore instead of clobbering it (follow-up to #1979)
The PR always wrote gitignore=not no_gitignore into .graphify_build.json, so a
flag-less `graphify extract` after `--no-gitignore` reset it to True and the
git-ignored code silently disappeared again — the exact #1971 complaint. Write
False only when the flag is set (None = leave as-is, mirroring #1886 excludes),
and honor the persisted value for the run when the flag is absent.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 12:09:08 +01:00
mzt006 704e687532 test: update watch ignore loader mock 2026-07-18 12:05:00 +01:00
mzt006 f17e2c5638 fix: add --no-gitignore extraction opt-out 2026-07-18 12:05:00 +01:00
oleksii-tumanov aad595571d fix(detect): keep ignore globs within path segments 2026-07-18 12:04:48 +01:00
Alpha Nury d56b70a451 fix(resolution): repoint cross-extension re-exports without leaking an absolute path (#1814) 2026-07-18 12:04:23 +01:00
Luke J a86666ae94 fix(prs): decode gh/git/claude output as UTF-8, not the Windows cp1252 codec
`graphify prs` reads gh, git, and claude output via subprocess.run(text=True)
with no explicit encoding=, so on Windows stdout is decoded with the cp1252
locale codec. gh emits UTF-8 JSON whose PR titles and logins routinely carry
non-Latin1 bytes (emoji, or the Persian title in PR #1281), and cp1252 has no
mapping for bytes such as 0x81. The capture reader thread raises
UnicodeDecodeError, subprocess.run then returns stdout=None, and the caller dies
one line later on json.loads(None) (TypeError) or None.splitlines()
(AttributeError). Neither is caught by _gh's except clause, so the whole `prs`
command aborts, with a spurious reader-thread traceback on stderr, against any
repo that has non-ASCII PR metadata.

Pass encoding="utf-8", errors="replace" to all five subprocess reads in prs.py
so decoding matches Linux and macOS. This is the decode-side sibling of #1505,
which applied the same change to the llm.py claude-cli subprocess. CI runs Linux
only (a UTF-8 locale), so this path is never exercised there.

Reproduced on Windows 11 / CPython 3.13 with a cp1252 locale:
prs._gh("pr", "view", "1281", ...) crashed with TypeError before and returns the
decoded title after. The added regression tests assert encoding="utf-8" on each
call, mirroring tests/test_charmap_encoding.py, and are red without the fix.
2026-07-18 12:03:47 +01:00
Osamaali313 a0386848be Fix DreamMaker parent-relative #include paths (lstrip charset misuse)
`extract_dm` normalized include paths with `raw.lstrip("./")`. `str.lstrip`
treats its argument as a *set of characters*, not a prefix, so it strips
every leading `.` and `/` — destroying parent-relative includes:

    "../shared/base.dm"  -> "shared/base.dm"
    "../../a.dm"         -> "a.dm"
    ".hidden/x.dm"       -> "hidden/x.dm"

`(path.parent / norm).resolve()` then points at the wrong directory,
`.exists()` returns False, and a correct internal `imports_from` edge to the
real included file becomes a bogus external `imports` edge to a phantom node,
silently losing the cross-file link.

The sibling local-include resolver in `extractors/bash.py` resolves
`(path.parent / raw)` from the raw path without stripping `..`, confirming
the intent. Strip only a literal leading `./` (re is already imported) so
`../` includes resolve correctly; the `./`-prefix and no-prefix cases are
unchanged.
2026-07-18 12:03:47 +01:00
safishamsiandClaude Opus 4.8 995508c328 fix(cache): key file_hash stat-index memo by salt, not absolute path (#1989)
The digest salts content with the path relative to root (portability, #1774),
but the stat-index memo was keyed by absolute path only — so the same file
hashed under two roots (which happens within one `--out` run) served whichever
digest was computed first, making file_hash order-dependent and poisoning the
persisted stat-index across runs. Store one digest per salt under a "hashes"
map; legacy un-salted "hash" entries are never trusted (recompute once). Digest
computation is byte-identical, so existing cache entries still hit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 12:03:34 +01:00
safishamsiandClaude Opus 4.8 689dd6ccfd feat(hook): opt-in strict PreToolUse guard + stop crying wolf (#1840)
Agents routinely ignore the advisory "run graphify query first" nudge and read
raw files anyway. `graphify install --project --strict` (or `graphify claude
install --strict`) now installs a hook that BLOCKS the first raw source read of a
session via permissionDecision:"deny" with a redirect to graphify query, then
downgrades to the soft nudge — it fires at most once per session (atomic
per-session marker) so it can never strand the agent, and a recent
query/explain/path refreshes a stamp that suppresses it. Claude Code only;
Bash-grep and Glob stay nudge-only; Gemini/Codex/OpenCode are unchanged.
GRAPHIFY_HOOK_STRICT=1/0 toggles at runtime without a reinstall; default installs
are byte-identical (soft nudge).

Also fixes #1840 for the default soft nudge: the guard no longer fires for reads
of out-of-project files, and softens to a non-mandatory nudge when the graph is
stale for the target file. Gating is ~3 stat calls (no corpus walk) and fails
open. Begins the 0.9.19 cycle.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 17:10:41 +01:00
safishamsiandClaude Opus 4.8 8cee776cee docs: cut 0.9.18 changelog and document the incomplete-build refusal (--allow-partial)
Stamp the 0.9.18 release date and add a README troubleshooting entry for the
new #1951 behavior: an incomplete extraction refuses to overwrite a larger
existing graph, with --allow-partial as the escape hatch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 14:56:22 +01:00
SinghAman21 be80ee82d5 fix(extract): anchor source_file on the scan root, not the --out dir (#1941)
`graphify extract <root> --out <dir>` reduced every node's `source_file` to a
bare filename, so a graph.json could no longer be resolved back to files on
disk by joining source_file onto the scan root.

--out passes the output dir as cache_root to relocate the cache, but that value
also anchored relativization. Every scanned file then failed relative_to(root),
fell through to the #1899 out-of-root fallback, tripped its `updepth > 3`
walk-up guard -- written for a stray ProjectReference, not a whole corpus -- and
collapsed to a basename. On Windows an --out on another drive hit the
cross-drive branch and basenamed unconditionally, which is what the reporter
saw: 0 of ~120k source_files kept a separator. The directory survived only in
the node id slug, lossily (`.`, `/`, `\`, `-`, spaces all map to `_`), and no
other field carried it -- origin_file is stripped (#1516) and the export has no
file table -- so 0% of nodes resolved.

extract() now takes an explicit `root` anchor for source_file/ids/symbol
resolution, which the CLI pins to the scan root independent of where the cache
lives. This completes the cache/anchor decoupling #1774 started and matches
build(root=target), which already anchored on the scan root -- extract was the
lone component keying off --out.

cache_root keeps its fallback-anchor role, so callers that pass the scan root as
cache_root (watch, the no---out CLI path, tests) are unchanged, as are cache
location and out-of-root portability (#1899).
2026-07-17 11:35:11 +01:00
safishamsiandClaude Opus 4.8 709b208175 test(cache): pin the #1948 x #1950 interaction (truncated doc's hash is cleared)
Follow-up to #1956: a doc stamped complete on a prior run that truncates
(partial) this run must have its stale semantic_hash cleared so it is re-queued.
Partial files are dropped by _stamped_manifest_files and therefore land in
clear_semantic — pin that composed behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 11:33:13 +01:00
Alpha NuryandClaude Fable 5 824cac7086 fix(detect): clear stale semantic_hash for dispatched-but-omitted files (#1948)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 11:30:53 +01:00
safishamsiandClaude Opus 4.8 431dd18169 fix(detect): keep .tfvars out of the graph under the sensitive-dir carve-out (follow-up to #1955)
The #1943 carve-out rescues genuine source under secrets/ / credentials/, but
.tfvars sits in CODE_EXTENSIONS while being Terraform's canonical values store
(routinely real secrets), so it would now be indexed. Add .tfvars to
_SECRET_PRONE_DATA_EXTS so the shared graphable-source predicate drops it in
both Stage 1 and Stage 3; .tf/.hcl stay graphable as genuine infra source.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 11:28:52 +01:00
Alpha NuryandClaude Fable 5 9ee151d826 fix(detect): spare genuine source from the Stage 1 sensitive-dir drop (#1943)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 11:22:08 +01:00
safishamsiandClaude Opus 4.8 dd0f8ec5b6 fix(build): coerce null/malformed edge weight to the 1.0 default (#1960)
An explicit "weight": null in the extraction JSON survived .get("weight", 1.0)
(the key is present, so the default never applied) and reached Louvain/Leiden as
None, crashing modularity with a TypeError (graspologic's Leiden even panics on
NaN). build_from_json now coerces weight and confidence_score to float at the
ingest choke point, falling back to 1.0 for null / non-numeric / NaN / inf /
negative values while preserving valid ones. Repairs (not drops) the key so
graph.json round-trips clean and a cluster-only/--update reload never re-ingests
the null.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 11:21:21 +01:00
Alpha NuryandClaude Fable 5 5163a6243b fix(watch): widen semantic-doc gate to the doc-shaped file_type subset (#1954)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 10:54:59 +01:00
oleksii-tumanov 5a480a83a7 fix(merge-chunks): fail when no chunk validates 2026-07-17 10:54:07 +01:00
oleksii-tumanov dea6ec0c24 fix(extract): remove dangling alias import edges 2026-07-17 10:54:07 +01:00
safishamsiandClaude Opus 4.8 b193607967 docs: record the #1949-#1953 integrity-cluster fixes in the 0.9.18 changelog
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 00:13:40 +01:00
safishamsiandClaude Opus 4.8 8bc477f2e2 fix(llm): move the unverifiable-node flag to a real, consumed field (follow-up to #1949)
The PR flagged unverifiable code nodes as confidence="UNVERIFIED", but node
confidence is read by nothing and UNVERIFIED isn't in the validated (edge-only)
confidence vocabulary {EXTRACTED,INFERRED,AMBIGUOUS} — a dead, colliding field.

- Move the flag to a dedicated verification="unverified" node field, off the
  confidence key. A node the model already hedged (INFERRED/AMBIGUOUS) is left
  untouched, as before.
- Also check the node id's identifiers (not just the label): ids carry the
  verbatim symbol, cutting false flags on prettified labels.
- Skip the (potentially PDF-re-extracting) source read entirely when a result
  has no code-typed node with a source_file.
- Wire a consumer: diagnose_extraction now counts and reports unverified nodes,
  so the persisted flag is actually surfaced.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 00:09:02 +01:00
tpateeq 741876b7f2 fix(llm): downgrade unverifiable code-typed semantic nodes to UNVERIFIED
The semantic (LLM) extraction runs on documents/papers/images; code files are
handled by the deterministic AST engine and never reach the model. A node the
model tags file_type="code" is therefore a symbol it surfaced from within a
document (a name in a fenced code block, an API referenced in a paper), and it
enters graph.json today with no check that the symbol actually appears in the
source the model read. `_out_of_scope` (#1895) only rejects nodes attributed to a
file that was NOT dispatched, so a fabricated symbol on a dispatched file passes.

`extract_files_direct` now verifies every file_type=="code" node whose
source_file was dispatched in the call: if no identifier from its label occurs
(case-insensitive substring) in that file's source bytes, the node's confidence
is downgraded to "UNVERIFIED" (never dropped) and the count is reported to
stderr. Concept/document nodes, nodes without a source_file, nodes attributed to
undispatched files, and labels with no checkable identifier are left untouched.
Best-effort; never aborts extraction; one unreadable file is skipped, not fatal.
2026-07-17 00:02:15 +01:00
safishamsiandClaude Opus 4.8 479f1af455 fix(cache): mark files partial on empty-parse truncation (follow-up to #1950)
The _partial item-marker approach couldn't fire on the most common truncation
shape: a mid-JSON cut parses to zero items, so a sliced document whose second
slice truncated empty was still stamped complete (the PR's own headline case).

- The adaptive-retry give-up sites now record the chunk's own source files in a
  result-level _partial_files list, independent of parsed items; it propagates
  through _merge_two / the recursion merges / _merge_into so it reaches both the
  per-chunk checkpoint and the run-level manifest stamp.
- _partial_source_files unions _partial_files with the item markers.
- save_semantic_cache seeds an empty group for a named partial file with no
  items so its entry is stamped partial, and carries a partial prev entry's flag
  forward so a later clean slice merging over it can't re-promote it to complete.
- the CLI final save now passes partial_source_files (computed before the save)
  so an empty-parse file isn't written back as a complete entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 00:02:15 +01:00
tpateeq 90dcb6a2ef fix(cache): don't promote truncated LLM chunks to the semantic cache as complete
A chunk whose LLM response is truncated (`finish_reason="length"`) and can't be
recovered by splitting, or that hits the adaptive-retry depth cap, returns a
partial node set. Today that set is checkpointed and written to the content-hash
semantic cache + manifest-stamped as complete, so the incomplete nodes are
served forever until the file content changes or `--force`.

Truncated give-up results are now tagged with an internal `_partial` marker.
`save_semantic_cache` stamps the affected file's entry `partial: True` (detected
from the marker or an explicit `partial_source_files` arg), and `load_cached`
treats a partial entry as a cache MISS, so the file re-dispatches and retries.
The file is also left unstamped in the manifest (like a failed chunk, #933) so
detect_incremental re-queues it on the next incremental run — not only on a full
/ `--force` / content-change run. A file sliced across chunks accumulates via a
partial-aware `merge_existing` peek (`load_cached(allow_partial=True)`) so a
truncated slice is never dropped or silently promoted to complete. Self-heals: a
later complete extraction overwrites the same key with a non-partial entry. The
marker is stripped after the final save so it never leaks into graph.json.
2026-07-16 23:48:07 +01:00
safishamsiandClaude Opus 4.8 16fe8f3020 fix(io): route the remaining graph/manifest writers through the atomic helper (follow-up to #1952)
The atomic-write PR left several writers on the old truncate-then-write path.
Route them through write_json_atomic so a crash mid-write can't corrupt them:
- the --no-cluster raw graph.json dump (a core graph.json writer)
- merge-graphs / merge-chunks / merge-semantic output
- .graphify_analysis.json and .graphify_labels.json sidecars
- global_graph.py's global-graph.json and global-manifest.json

write_json_atomic gains an ensure_ascii flag so the raw-UTF-8 writers
(labels, merge outputs) keep byte-for-byte output. Adds tests for the
Windows PermissionError copy fallback and ensure_ascii=False.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 23:48:07 +01:00
tpateeq f38e98012d fix(io): write graph.json and manifest.json atomically
graph.json (the clustered `to_json` write and the `--no-cluster`/merge raw
dumps) and manifest.json were written with a direct `open()`/`write_text`, so a
crash, kill, or disk-full mid-write left a truncated, unparseable file that the
next load or `detect_incremental` then failed on.

Add `write_text_atomic`/`write_json_atomic` in graphify.paths (temp file in the
same directory + `os.replace`; JSON is streamed into the temp, not materialized
as one string) and route the graph.json writers (export.to_json,
cli._prune_graph_json_sources, the merge driver) plus detect.save_manifest
through them. The helper preserves the destination's mode (an atomic replace
never tightens 0644 to mkstemp's 0600), writes through a symlinked destination
(shared-output setups), and falls back to copy-then-delete on a Windows
os.replace lock — matching graphify.cache's existing atomic writer. On failure
the previous file is left intact and the temp removed. Not a power-loss
durability guarantee (no fsync, consistent with the rest of the codebase).
2026-07-16 23:42:47 +01:00
safishamsiandClaude Opus 4.8 7d53a02704 fix(extract): fail closed on malformed existing graph + honor walk_errors (follow-up to #1951)
Two gaps the review found in the incomplete-build shrink guard:
- existing_graph_node_count() returned None ("proceed") on a present-but-
  unparseable graph.json, so the --no-cluster path could clobber a complete
  graph whose file was corrupt/mid-write. It now returns a MALFORMED_GRAPH
  sentinel and the caller fails closed, matching to_json's #479 handling.
- A walk that couldn't fully enumerate the corpus (permission-denied subtree,
  I/O error) is now treated as an incomplete extraction: detect()/
  detect_incremental() already record walk_errors; the extract path consumes
  them so a walk-truncated graph can't force-overwrite a complete one.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 23:42:47 +01:00
tpateeq 0f936850ba fix(extract): extend the incomplete-build shrink guard to the --no-cluster path
The clustered write is guarded by to_json's #479 shrink check, but the
`--no-cluster` raw-dump path writes graph.json directly and had no guard, so an
incomplete `--no-cluster` build could still overwrite a larger complete graph
with a partial one — the residual gap noted in the original change.

Add `existing_graph_node_count` in graphify.export (mirrors to_json's guard and
respects the graph-size cap) and, on the raw path, refuse the write with exit 1
before the manifest when the build was incomplete and the new graph has fewer
nodes than the existing one — unless --allow-partial is passed. Both write paths
now enforce the same guarantee.
2026-07-16 23:38:09 +01:00
tpateeq fcc01dbcdf fix(extract): don't force-write a partial graph over a complete one
A full `graphify extract` writes the final graph with `to_json(..., force=True)`,
which bypasses the #479 shrink guard. That is correct for a clean build that
legitimately shrinks (dedup collapse, deleted code), but when this run's
extraction was incomplete — an AST pass crashed, or some semantic chunks failed —
forcing the write lets a partial graph silently overwrite a good complete one.

The build now tracks incompleteness (AST-pass failure, semantic-pass crash, or
succeeded < total chunks) and falls back to the shrink guard (force=False) on an
incomplete run, so a smaller partial graph is refused rather than written. It
exits non-zero before the manifest is written, so the manifest is never stamped
for a graph we declined to write and the next run re-attempts. `--allow-partial`
restores force=True to override intentionally.

Note: the `--no-cluster` raw-dump path writes graph.json directly and has no
shrink guard; this change covers the normal clustered build path only.
2026-07-16 23:38:09 +01:00
safishamsiandClaude Opus 4.8 3305ef1059 fix(merge-chunks): coerce non-numeric chunk token counts (follow-up to #1953)
An untrusted chunk with a non-numeric input_tokens/output_tokens would abort
the whole merge with a TypeError after other chunks had already merged. Coerce
to 0 so a bad token field can't defeat the per-chunk validation guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 23:38:09 +01:00
tpateeq ee74d80b45 fix(merge-chunks): validate untrusted subagent chunk JSON before merging
`graphify merge-chunks` concatenates agent-written `.graphify_chunk_*.json`
files with only a JSON-decode guard, so an oversized payload or a crafted
node/edge id (e.g. `../../etc/passwd`) flowed straight into the merged graph.

Route each chunk through `load_validated_semantic_fragment`, which stats the
file size BEFORE reading it (a multi-GB chunk can't blow up memory), parses the
JSON, and validates the byte/count caps + the node/edge id charset that blocks
path traversal (#825). An invalid chunk is skipped with a warning (filter
semantics; never abort). Left OUT of build_from_json/load_graph_json on purpose:
those must keep loading valid pre-existing graphs.

Also relax two over-strict checks in the shared validator that would otherwise
silently drop whole legitimate chunks (a relaxation — never a new rejection):
- file_type is no longer gated: build coerces any value via _FILE_TYPE_SYNONYMS
  (unknown -> "concept", #840), so synonyms like "markdown"/"tool" the loader
  maps must not fail validation.
- the id charset now allows Unicode word chars (build's normalize_id preserves
  CJK/Cyrillic/accented-Latin ids); the explicit path-separator/".." check still
  blocks directory escape.
Corrects the stale module docstring (the validator serves the devin skill path
and merge-chunks, not skill-opencode/codex).
2026-07-16 23:36:49 +01:00
safishamsiandClaude Opus 4.8 84638cb69c chore: begin 0.9.18 development cycle
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 16:42:18 +01:00
SinghAman21 0d018b4c6d fix(cache): key semantic cache on the extraction prompt (#1939)
The semantic cache keyed entries on sha256(file content + path) alone, with
no component for the extraction prompt that produced them. After an upgrade
that changed the prompt, every unchanged file was a cache hit and replayed
the older prompt's extraction: the run exited 0, cost.json looked cheap, and
the graph silently carried two prompt generations side by side. The reporter
saw 506 of 512 docs replay an older vintage on a rebuild they expected to be
cold; deleting the whole cache was the only workaround.

output, and invalidating them on every release would re-bill extraction for
unchanged files. Fingerprinting the prompt itself keeps both properties:
entries survive releases that don't touch the prompt, and invalidate only
when it actually changed.

Semantic entries now live under cache/semantic/p{fingerprint}/, mirroring the
AST cache's v{version}/ layout. Both extraction paths pass their prompt: the
Python/CLI path from llm.py's _EXTRACTION_SYSTEM (shared by every backend),
and the skill path via a new prompt_file argument in Step B0/B3 naming the
references/extraction-spec.md the subagents were handed. The fingerprint
normalizes line endings so a CRLF checkout isn't mistaken for a new prompt.

Pre-existing entries predate fingerprinting and have unknowable vintage, so
they are still served rather than re-billing a whole corpus on upgrade — but
check_semantic_cache now warns with the count, turning "no signal at all"
into a visible one. merge_existing refuses to fuse such an entry into a
current-vintage write, which would mix two prompts inside one entry and then
attest the result to a prompt that produced half of it.

Old-fingerprint entries are pruned by liveness only, never swept wholesale
the way stale AST versions are: two hosts with different prompts (verbose vs
compact extraction-spec) can share one graphify-out/, and a wholesale sweep
would have each run delete the other's entries and re-bill on every
alternation. prune/clear/cached_files glob recursively so fingerprinted
entries can't become unprunable orphans (the #1527 failure mode).

The two monolith skills (aider, devin) inline their prompt instead of
shipping a spec sidecar and stay on the unfingerprinted path for now.
2026-07-16 16:38:12 +01:00
sekmurandClaude Fable 5 5840d0b44d fix(pg_introspect): emit FK DDL before function stubs so unparseable routines can't drop references edges (#1854)
A C-language routine's body from information_schema.routines is just the C
symbol name, so its reconstructed stub (CREATE FUNCTION ... AS $gfx$ name
$gfx$ LANGUAGE c) is unparseable by tree-sitter-sql, and the parser's error
recovery consumes the statements that follow. With FK ALTER TABLEs emitted
last, every references edge was silently lost on any DB with a common
extension installed (uuid-ossp, pgcrypto, pg_trgm, fuzzystrmatch, ...).

Emit the FK block before the routine DDL. FK statements only reference
tables, which are emitted first, so the order is always safe. On a real DB
with 35 tables / 41 FKs / 41 extension routines: 41/41 references edges vs
1/41 before.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 16:36:49 +01:00
safishamsiandClaude Opus 4.8 ecf1416a7e docs: cut 0.9.17 changelog and credit @zuwasi for Amp platform support (#948)
Stamp the 0.9.17 release date and add a belated acknowledgement that Amp
(ampcode.com) platform support, which shipped earlier in v8, was contributed
by @zuwasi in #948.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 11:47:08 +01:00
safishamsiandClaude Opus 4.8 cb96bdaa0c fix: preserve semantic layer, stamp hyperedges, PHP namespaces, ignore diagnostic (#1925 #1920 #1923 #1922)
- #1925: a missing manifest.json no longer degrades `extract --code-only`
  into a full scan that discards the committed semantic layer. An existing
  graph.json is a sufficient incremental baseline (detect_incremental treats
  an absent manifest as "all new / none deleted"), so out-of-scope doc/paper/
  image nodes are preserved while genuinely deleted sources still evict.
- #1920: _stamped_manifest_files now counts hyperedge output, so a doc whose
  only chunk output is a hyperedge is stamped instead of re-extracted forever.
- #1923: new namespace/use-aware PHP resolver (mirrors the Java resolver, runs
  before the unique-name rewire) so App\Models\Page and an imported
  Filament\Pages\Page stay distinct — no more false inherits/imports edge.
- #1922: detect() records ignored files/dirs in a new `ignored` diagnostic
  field (the nested-ignore scoping bug itself shipped in 0.9.16 / #1873).

Regression tests added for each; full suite 3325 passed, 3 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 19:51:53 +01:00
safishamsiandClaude Opus 4.8 19c496dd63 fix(build): make _semantic_id_remap idempotent to stop id accretion (#1917)
An id whose canonical stem contains its legacy stem as a prefix (parent
dir name == file stem, e.g. .claude/CLAUDE.md) re-matched the legacy
branch every build and grew another stem segment, defeating the
same_topology/no_change short-circuits and churning graph.json +
clustering on every zero-delta update. Skip an id that already carries
its canonical stem (mirrors graph_has_legacy_ids); genuine legacy
migration still applies. Also records the #1889/#1918 query-scoring perf
work in the changelog.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 15:14:34 +01:00
safishamsiandClaude Opus 4.8 c0875ccae9 test(serve): rebase #1900 test onto #1918 _score_query API; bench newline
PR #1918 replaced _pick_seeds(terms=) with best_seed_by_term= from
_score_query. Update the #1900 German-stopword seed test to the new
single-traversal API and add the missing trailing newline in the
(manual, non-collected) query-scoring benchmark.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 15:09:17 +01:00
Sirhan1 ff999a909a perf(serve): collapse T+1 per-term scoring passes into one traversal
Add _score_query() producing combined ranking + per-term singleton winners
in a single graph traversal. _pick_seeds consumes precomputed winners
instead of rescoring each term via _score_nodes.

Behavior byte-identical to the legacy T+1 path. Supersedes the rescoring
loop from #1596 while preserving its per-term coverage guarantee; folds
in coverage scaling from #1724 and multiplicity penalty from #1832.
Orthogonal to the trigram prefilter from #1431.

Benchmark (full sweep in #1889):
  1k-100k nodes, 1-10 terms: 1.43x-2.43x median speedup
  Single-term: no regression (1.70x-1.89x improvement)
  Traversals: T+1 -> 1 regardless of term count

Tests: 3221 passed, 3 skipped. Ruff clean. Graphify graph updated.

Refs #1889
2026-07-15 15:07:25 +01:00
safishamsiandClaude Opus 4.8 1c280e4576 docs(changelog): record #1894(PR-1) #1916 #1915 #1912 in unreleased 0.9.17
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 14:16:14 +01:00
safishamsiandClaude Opus 4.8 b7ddee3c28 fix(extract): make --mode deep effective over a warm cache; add --force (#1894)
`graphify extract --mode deep` over a warm tree was a silent no-op, for
three stacked reasons:

1. The semantic cache ignored mode: deep runs were served standard-mode
   entries (and vice versa). check_semantic_cache/save_semantic_cache now
   take `mode` (default None, byte-identical when omitted so older
   installed callers keep working) and map it to a namespaced kind —
   cache/semantic/ for None, cache/semantic-{mode}/ otherwise. The
   per-chunk checkpoint in llm.extract_corpus_parallel and the extract /
   cache-check consumers thread the run's mode through (cache-check grows
   --mode/--deep). cached_files, clear_cache, and prune_semantic_cache
   sweep BOTH namespaces; prune uses the same live-hash set for both
   (liveness is content-based, mode-independent) so semantic-deep/ can't
   regrow the #1527 unbounded-orphan problem and inherits the
   files_by_type-derived exclusion gating for free.

2. extract had no --force — the flag was silently swallowed by the
   parser's unknown-arg fallthrough. It is now real (plus GRAPHIFY_FORCE
   env parity with `update`): force disables the incremental gate so
   detection is a full scan and skips the semantic cache READ so every
   semantic file re-dispatches, while the post-run save and manifest
   stamping still happen.

3. The incremental gate dispatched zero files on a warm unchanged tree
   before the cache was ever consulted, so namespacing alone couldn't fix
   the repro. In deep+incremental runs the semantic pass now widens to the
   full live doc/paper/image set from detect_incremental's files_by_type
   (already exclusion-filtered, #1908/#1909) and lets the mode-namespaced
   cache decide hits/misses, with a loud count line so the first deep
   run's full re-dispatch is visible.

Skill-side threading of mode is deliberately deferred to PR-2; mode
defaults keep generated skills byte-compatible.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 14:14:13 +01:00
safishamsiandClaude Opus 4.8 d916c61559 fix(cache): stop persisting dangling edges/hyperedges in the semantic cache (#1916)
save_semantic_cache groups nodes/edges/hyperedges by their own source_file
and the write loop skips a group whose path is a ghost (not .is_file(),
silently) or out-of-scope per the #1757 guard — but an edge or hyperedge in
an ALLOWED group that references a node id from a skipped group was still
written verbatim, so on replay (check_semantic_cache) it dangled forever.
The #1895 filter does not cover this: it cleans the in-memory merged result,
while the checkpoint writes the cache BEFORE it runs and replay bypasses it
entirely.

Fix at the cache layer (the authoritative write path): before the write
loop, compute the node ids belonging to groups that will be skipped —
mirroring BOTH skip branches — minus ids also defined in a group that will
be written (duplicate-attribution nodes must not be over-pruned). Each
written group then drops edges whose source/target is a skipped id and
hyperedges whose member list intersects them (whole-hyperedge drop,
mirroring #1895). Pruning runs on the incoming result only, so with
merge_existing=True (the llm.py checkpoint path) the prior cached entry's
valid edges survive the union untouched. Everything is gated on
allowed_source_files being provided, so unscoped callers stay
byte-identical.

Complementary hardening in build_from_json: hyperedges were copied into
G.graph["hyperedges"] verbatim without member validation, so a dangling
hyperedge reached graph.json even from a live (non-cache) extraction.
Members are now remapped via the same normalization the pairwise-edge loop
uses and pruned when they still don't resolve; a hyperedge with no
surviving member is dropped whole with a stderr warning. (Single-member
hyperedges are legal in this codebase — per-file flows in the #1574 tests —
so the drop threshold is zero survivors, not two.)

Tests: scoped save with an edge to an out-of-scope real file, the same with
a ghost source_file, whole-hyperedge drop, unscoped save preserved
byte-identically (raw cache entry compared), merge_existing keeping the
prior slice's valid edges, and build_from_json pruning a dangling hyperedge
member / dropping an all-dangling hyperedge.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 13:30:25 +01:00
safishamsi 76f5bc98fe fix(watch): stop AST-quick-scanning docs that already have semantic nodes (#1915)
_rebuild_code fed Markdown/doc files (.md/.mdx/.qmd/.skill) into the AST
quick-scan while _reconcile_existing_graph preserved the same docs'
semantic (LLM) nodes, so every semantic-backed doc was represented twice
(heading nodes + concept nodes) and the graph bloated ~4x vs the CLI
`graphify . --update` path.

Semantic now supersedes AST per doc source: before choosing
extract_targets, read the existing graph's source identities that carry
semantic doc nodes (non-_origin=="ast", gated on file_type=="document"
so pre-#1865 marker-less graphs aren't misread) and exclude those docs
from the quick-scan in both the full-rebuild and changed_paths branches.
They stay in code_files, so the #1795 fail-closed corpus check and the
shrink accounting still cover them — a previously-bloated graph
self-heals on the next full rebuild (the AST ownership rule drops the
stale heading nodes) without the shrink guard refusing the smaller
write. On incremental rebuilds the excluded docs never enter
rebuilt/node-evicted identities, mirroring #1865's tier-scoped edge rule
at the node level, so a doc's semantic nodes and edges survive. Docs
with no semantic layer (and brand-new docs) keep the no-LLM quick-scan
structure from #09b33b7.
2026-07-15 13:30:25 +01:00
KookwaterandClaude Opus 4.8 2851f31a07 fix: treat .cjs (explicit CommonJS) as a code extension
.cjs was half-registered: the language maps in build.py and
extract.py already routed it to the JS grammar, but it was missing
from CODE_EXTENSIONS, the extractor _DISPATCH, _LANG_FAMILY, and the
JS resolution/cache suffix sets — so .cjs sources (Electron
main/preload scripts, CommonJS escape hatches in "type": "module"
packages) were silently skipped during a build: classified as
non-code and never handed to the JS extractor.

Add .cjs alongside .mjs in the six lists that gate/route JS files
(detect.py, extract.py _DISPATCH, analyze.py _LANG_FAMILY,
extractors/models.py cache-bypass, extractors/resolution.py resolve
exts, cli.py _HOOK_SOURCE_EXTS), with regression locks mirroring the
.mts/.cts fix (#1607).

Real-world impact: an Electron app whose ~2000-line main.cjs backend
was invisible went from 201 to 294 nodes and 256 to 441 edges on
rebuild.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 13:13:30 +01:00
safishamsiandClaude Opus 4.8 0d783915a6 docs(changelog): record #1908/#1909 and #1910 in unreleased 0.9.17
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 12:18:55 +01:00
safishamsiandClaude Opus 4.8 49df466385 fix(sql): recover CREATE FUNCTION/PROCEDURE from tree-sitter ERROR nodes (#1910)
tree-sitter-sql parses PL/pgSQL CREATE FUNCTION statements (OUT/INOUT
params, tagged dollar quotes, PERFORM/:= body statements) as ERROR
nodes, and the dispatch loop had no branch for them, so the functions
were silently dropped from the graph.

Handle ERROR nodes inside walk() (they can nest inside a merged
create_function during multi-statement error recovery) and dispatch
top-level ERROR statements to it. The branch regex-scans the raw node
text for every CREATE [OR REPLACE] FUNCTION/PROCEDURE, mirroring the
existing fb_proc_or_trigger and has_error fallbacks, with a name class
that keeps schema-qualified names (exposed.important_function) whole.
The PL/pgSQL body is not scanned for FROM/JOIN references to avoid
junk reads_from targets, and node ids match the clean create_function
branch so seen_ids dedups consistently.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 10:58:57 +01:00
safishamsi 75cf56bfbc fix(detect,cli): excluded files are pruned from graph and manifest, not misreported as deleted (#1908 #1909)
Two coupled excluded-vs-deleted fixes:

#1909 — incremental extract's prune set was derived from the manifest
alone (manifest - corpus), so a file that became excluded without ever
being manifest-listed (every pre-#1897 graph) kept its stale nodes in
graph.json forever. The prune set is now also derived from the existing
graph's own node source_files reconciled against the post-exclude detect
corpus (_stale_graph_sources), restricted to in-root paths; out-of-root
--include/symlinked entries and remote (://) sources are never pruned.
Relative source_files are anchored against both the scan root and the
--out root (the #555/#1899 relativized form). The --no-cluster
incremental early exit never runs build_merge, so an exclusion-only
change now prunes the raw graph.json in place instead.

#1908 — save_manifest retained any prior row whose file still existed
on disk, so an excluded-but-alive file survived as a permanent phantom
that detect_incremental reported as deleted on every run. Full-scan
callers (extract's saves, watch._rebuild_code's saves) now pass the RAW
detect corpus via a new scan_corpus parameter and in-root rows outside
it are dropped; the corpus is deliberately not the #933 stamp-filtered
files dict, so failed-chunk/omitted-doc rows and --code-only doc rows
survive. Subset saves (changed_paths hooks, #917) keep the seeding
default. detect_incremental now splits manifest rows that left the scan
into deleted_files (gone from disk) and excluded_files (alive but out of
scan), mirroring the watch-side #1795 distinction, and the extract
summaries report the two separately.

Ordering matters: extract's cleanup of newly-excluded nodes previously
worked only through the #1908 conflation, so the graph-source prune
lands together with the manifest split to avoid regressing #1909.
2026-07-15 10:58:57 +01:00
safishamsiandClaude Opus 4.8 43b2affd56 chore: open 0.9.17 with 8 batch fixes (#1895 #1897 #1902 #1907 #1896 #1900 #1901 #1906)
Bumps to 0.9.17 (unreleased) and records the batch implemented via Fable
subagents in isolated worktrees, integrated onto v8: out-of-scope node
drop, manifest stamping, merge-driver registration, hooksPath configparser
fix, obsidian prune, multilingual query stopwords, .skill classification,
and the postgres package-name hint.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:43:46 +01:00
safishamsiandClaude Opus 4.8 b1e313cc5f fix(cli): stamp freshly-extracted semantic docs in the manifest (#1897)
The #933 manifest filter built its extracted-set from node/edge
source_file values, which are root-relative on a fresh extraction, and
compared them against files_by_type entries, which are absolute (from
detect()). The raw string membership test therefore never matched, so
every freshly-extracted semantic doc was dropped from the manifest and
re-queued as changed on the next run; only code files and cache-replayed
docs got stamped. The filter now lives in _stamped_manifest_files(),
which resolves BOTH sides against the scan root before the membership
test — the same Path/is_absolute/resolve normalization the #1890
reconciliation uses in graphify.llm. Genuinely omitted zero-node docs
still have no source_file entry and stay unstamped, preserving the
intentional #933 re-queue behavior.

Regression tests: a CLI extract with a mocked corpus extractor returning
root-relative source_files lands the doc in manifest.json with a
non-empty semantic_hash while a zero-node doc stays out; a unit test
covers relative (fresh) and absolute (cache-hit) source_file shapes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:41:37 +01:00
safishamsiandClaude Opus 4.8 0cacd708e9 fix(llm): drop out-of-scope nodes from the merged extraction result (#1895)
The #1757 cache guard refuses to write a cache entry for a node whose
source_file resolves to a real corpus file that was not dispatched, but
the node itself still flowed into merged["nodes"] and landed in
graph.json (plus any edges/hyperedges built on it). extract_corpus_
parallel now filters the merged result right before the #1890
dispatched-vs-returned reconciliation: a node is dropped when its
source_file resolves (against root, same normalization as #1890) to an
existing file (.is_file(), mirroring the #1757 condition) outside the
dispatched set. Non-file source_files (concepts, model-invented anchors)
pass through untouched. Edges whose endpoint and hyperedges whose member
is a dropped node id go with it, plus any edge/hyperedge itself
attributed to an undispatched real file. One summary warning names the
offending files and merged["out_of_scope_dropped"] records the count.
Running before the reconciliation keeps covered/uncovered reflecting the
post-filter graph.

Regression tests: a chunk over A.md+C.md returning a stray B.py node
loses the stray (and its edge/hyperedge) while sibling and concept
attributions survive; a clean run records a zero count and no warning.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:41:36 +01:00
safishamsiandClaude Opus 4.8 f2a6139667 Fix spurious hooksPath warning and register graph.json merge driver
Fix #1907: _hooks_dir parsed .git/config with a strict configparser,
which rejects git-legal duplicate keys/sections (VS Code writes such
configs) and printed a spurious "could not read core.hooksPath" warning
on every hook command. Ask git itself (rev-parse --git-path hooks) as
the primary resolution instead; it handles core.hooksPath, includeIf
and linked worktrees, keeps the Windows-path and multiline/NUL guards,
and surfaces git's own stderr when the config is genuinely corrupt.
The .git/hooks final fallback is unchanged.

Fix #1902: hook install never registered the graph.json union merge
driver that README and CHANGELOG 0.7.0 document. install() now sets
merge.graphify.name/driver via git config (pinning sys.executable with
the same shell-safe allowlist the hook scripts use, falling back to the
graphify launcher) and idempotently appends the graph.json
merge=graphify line to .gitattributes without clobbering other entries.
uninstall() mirrors the removal, and status()/install() report the
merge-driver state.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:41:36 +01:00
safishamsiandClaude Opus 4.8 876c043c2f fix(export): prune orphaned Obsidian notes on re-export (#1896)
Re-exporting into an existing vault left notes for nodes that dropped
out of the graph, and rewriting the manifest to only this run's files
disowned those orphans - so a returning node's stale note became
permanently unwritable.

Before rewriting the manifest, delete stale = owned - written - skipped.
This only ever touches files graphify itself wrote (foreign files go to
_skipped, never the manifest), and each path is containment-checked
against the vault dir to defuse a corrupt/hostile manifest with ../
entries. The manifest rewrite then correctly drops the pruned files.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:41:36 +01:00
safishamsiandClaude Opus 4.8 107cea044c fix(serve): drop German and Romance question stopwords from query terms (#1900)
Full-sentence non-English queries picked wrong BFS seeds because
_QUERY_STOPWORDS was English-only: in a mostly-English code corpus,
fillers like wie/die/das/funktioniert are rare, get high IDF weight,
and out-seed the real keyword (~175x score collapse).

Extend the frozenset with a curated German set plus trimmed French/
Spanish/Portuguese/Italian question/filler words, diacritics intact.
English-collision words (war, bald, comment, come, son, sin, con,
pour, des) are deliberately omitted; die/hat are kept since the
all-stopword fallback and unfiltered find_node protect English use.
Filtering stays in _query_terms, so the per-term seed guarantee in
_pick_seeds composes unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:41:36 +01:00
safishamsiandClaude Opus 4.8 ef8771e8c1 fix: correct postgres install hint to graphifyy (#1906); classify .skill files as documents (#1901)
- pg_introspect: the psycopg-missing ImportError suggested pip install
  'graphify[postgres]', but the PyPI package is graphifyy (double-y)
- detect: add .skill (Markdown with YAML frontmatter agent files) to
  DOC_EXTENSIONS so they are no longer dropped as unclassified
- extract: route .skill through extract_markdown for the structural
  quick-scan

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:41:36 +01:00
safishamsiandClaude Opus 4.8 75b7279d92 docs(readme): point star-history at Graphify-Labs org; X handle to @graphify
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 00:00:56 +01:00
safishamsiandClaude Opus 4.8 a0e4a1c6bd docs(changelog): date 0.9.16 for release
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 23:57:12 +01:00
safishamsiandClaude Opus 4.8 a4ab6ed3f6 fix(llm): reconcile dispatched vs returned files in semantic extract (#1890)
A semantic chunk can return a clean, non-empty response that omits some
of the documents it was given. Those docs vanished from the graph with
no node, no warning, and no cache/manifest stamp, so they were silently
re-dispatched (and typically re-omitted) on every run. extract_corpus_
parallel now diffs the dispatched file set against the source_files that
returned, records the gap in merged["uncovered_files"], and prints a loud
warning naming the omitted files. Smallest visibility guard; routing docs
through the deterministic extractor for a guaranteed file node is a
separate, larger change.

Adds a regression test: a chunk that omits odd-numbered docs is caught
and warned, not silently dropped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 23:45:46 +01:00
safishamsiandClaude Opus 4.8 b3dc15b839 fix(extract): close residual absolute-path/username leaks (#1899)
Completes #1789. Two residual leaks into committed graph.json:

(a) Out-of-root reference targets (a .csproj ProjectReference, .sln
    project, or bash `source` pointing outside the scan root) kept an
    absolute source_file and an absolute-derived id, because the
    relativization post-passes only handled paths under root and silently
    left out-of-root ones absolute. They now get a portable walk-up
    relative source_file and an `ext_`-namespaced id (basename fallback
    for far-outside or cross-drive targets), with edge endpoints remapped.

(b) A symbol whose name normalizes to nothing (minified `$`, a JSONC
    `"//"` key) collapsed _make_id(stem, name) to the bare absolute file
    stem, leaking the path and colliding with the file node. Guard at the
    three mint sites (json_config keys, engine function names) to skip
    these no-signal symbols.

Adds regression tests: an out-of-root ProjectReference stays portable
(no scan-path in any id/source_file/edge), and a minified `$` is dropped
while the real function survives.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 23:42:06 +01:00
safishamsiandClaude Opus 4.8 e1b8a17dc8 docs(changelog): record #1881, #1876, #1893 in the unreleased 0.9.16 section
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 23:32:28 +01:00
kebwlmbhee 5c0a04c991 fix(extract): filter Kotlin builtin/stdlib types from references graph
_kotlin_collect_type_refs had no equivalent of _JAVA_BUILTIN_TYPES /
_PYTHON_ANNOTATION_NOISE / _GO_PREDECLARED_TYPES, so every Boolean/String/
Int/List/... type annotation in a .kt file became a real graph node/edge.
Unrelated files sharing only these language-level types were getting
merged into the same community by cluster-only.

Add _KOTLIN_BUILTIN_TYPES (kotlin.* scalars, collections, throwables -
deliberately not Android/JVM framework types like Context/View/Bundle,
matching how _JAVA_BUILTIN_TYPES doesn't filter framework types either)
and check it plus _JAVA_BUILTIN_TYPES (Kotlin freely references
java.util.Date/UUID/etc) at the three call sites that previously appended
unconditionally.

Deliberately excludes "Result" from the filter list even though
kotlin.Result exists - it collides with the very common user-defined
sealed-class name (confirmed against this repo's own sample.kt fixture,
which defines its own Result<T>).

Verified on a ~400-file Android/Kotlin project: 3693->3239 nodes (-12%),
6481->5221 edges (-19%), with a previously merged 5-file grab-bag
community cleanly splitting out an unrelated screen-dimension utility.
2026-07-14 23:32:03 +01:00
xkam7ar 8361a81f73 fix(extract): recognize uppercase TypeScript 2026-07-14 23:32:02 +01:00
mzt006 4f6106a2f1 fix(cli): send missing-skill warning to stderr 2026-07-14 23:31:59 +01:00
safishamsiandClaude Opus 4.8 f80e4fac35 test(watch): pin update discovers newly-added files/dirs (#1837)
#1837 (update silently fails to discover new files) was the same
nested-gitignore scoping bug (#1873/#1880), already fixed. The existing
test only does a single build; add the build -> add new file+dir ->
update -> discovered sequence the report describes, with a nested `*`
scratch dir as a scoping guard. No production change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 23:20:36 +01:00
safishamsiandClaude Opus 4.8 060dd6317f fix(extract): resolve Python module-qualified calls to calls edges (#1883)
`module.function()` where `module` is imported produced no calls edge,
while bare-name calls did. The member call was captured, but the shared
cross-file pass skips all member calls and _resolve_python_member_calls
only handled capitalized class receivers, so a lowercase module receiver
fell through. Add a module arm: a lowercase receiver naming a module
imported into the caller's file resolves to the single callable that
module contains. Keyed on stable node ids (imports edge source is the
caller file node; contains maps file -> children), not source_file
strings, so it holds under the cache_root id-remap relativization. Also
drop the no-classes early return that skipped the whole resolver when a
corpus had functions but no class methods.

Guards: only modules imported into the caller's own file match (so
self/obj/local instances never match), and a single-definition god-node
guard on the callable. Adds a positive test and a false-edge negative.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 23:19:06 +01:00
safishamsiandClaude Opus 4.8 2795a18bda fix(exclude): persist --exclude so rebuilds re-apply it (#1886)
--exclude was honored only by the initial extract scan; update/watch/hook
rebuilds re-ran detect() without it and silently re-indexed excluded
paths. extract now writes the patterns to a graphify-out/.graphify_build
.json sidecar, and _rebuild_code reads and re-applies them on every
rebuild (layered after the ignore files, so they still win). Pre-existing
graphs without the sidecar behave as before. Adds a regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 14:03:20 +01:00
safishamsiandClaude Opus 4.8 fd54f0ef0b fix(dedup): deterministic collision survivor + bare-file definer (#1851 followup)
Two tweaks on top of @bchan84x's #1852:

1. The definer heuristic decided the survivor pairwise, so when several
   same-file nodes co-defined one ID the surviving label still depended on
   arrival order (the exact 3-node case #1851 reports). Choose the survivor
   by a total order (definer first, then shorter/canonical label, then
   lexically) via a min over _collision_rank, so it is order-independent.
   Direction preserves #1504 (lexically-first source path wins).

2. _defines_id now also recognizes a bare file-level node whose id is
   exactly the slugified path (nid == prefix), not only <path>_<entity>.

Adds an order-independence test over all 6 permutations of definer +
same-file relabel + cross-file reference, and a bare-file-node test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 13:51:42 +01:00
bchan84 70bc9ca7b2 fix(dedup): let the defining file win an ID collision, and warn only about real loss
Node IDs are <source-path>_<entity>, so a doc that merely references an entity
mints the entity's own ID and collides with the entity's node by construction.
The pre-dedup pass kept whichever arrived first, so chunk order decided whether
an entity kept its own attributes or a passing cross-reference's, and the
warning that fired (#1504) told the user a same-name-different-directory clash
had lost their data — while the one drop that really is lossy, two labels for
one ID from the same file, was silent because the warning was gated on
source_file differing.

The survivor is now the node whose source_file is the file its ID encodes (any
trailing slice of the path, so absolute, repo-relative, and pre-#1504
bare-stem IDs all resolve), falling back to first-seen. Reporting follows what
the drop actually costs: a cross-reference folding into the node it references
loses nothing (edges are keyed by ID and rewire to the survivor) and is silent;
a same-file relabel notes the discarded label; two files that both encode the
ID are distinct entities and still WARNING, now stating the ID-scheme cause
rather than a filename clash.

Refs #1851
2026-07-14 13:38:57 +01:00
safishamsiandClaude Opus 4.8 2210d69bc4 docs(changelog): record #1865 and #1858 in the unreleased 0.9.16 section
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 13:21:29 +01:00
xor_xe 4ac5f07e88 fix(watch): preserve semantic edges of re-extracted sources (#1865)
A full graphify update evicted every edge whose source_file was a
re-extracted source, including LLM semantic edges (e.g.
semantically_similar_to) from Markdown docs that also have an AST
extractor. The AST pass cannot regenerate those edges, so they were
silently lost while their concept nodes survived — node eviction is
provenance-aware via _origin (#1116), edge eviction was not.

Tag AST-extracted edges with the same _origin=ast marker nodes already
carry, and scope rebuild-driven edge eviction to that tier: re-extraction
replaces a source's AST edges, while its semantic edges survive until a
semantic re-extraction supersedes them. Deletion-driven eviction stays
provenance-blind, so edges of deleted or excluded sources are still
purged regardless of tier.

Edges from graphs built before this change lack the marker; a stale
AST edge from a file changed exactly once between the old and new
version can linger until its source is deleted — the same migration
trade-off the #1116 node marker made.
2026-07-14 13:20:40 +01:00
thejesh 1aca158ada fix(cargo): honor package = "..." rename when resolving internal deps (#1858) 2026-07-14 13:19:16 +01:00
safishamsiandClaude Opus 4.8 40eae3cea2 test(watch): pin update-with-nested-gitignore (#1880); changelog for #1873/#1880
#1880 is the update-layer symptom of the #1873/#1887 nested-ignore
subtree-scoping regression (fixed in fb4d452, @Alwyn93): a nested broad
`.gitignore` zeroed update's re-scan, so it built 0 nodes and the
shrink-guard refused to overwrite. Adds a _rebuild_code regression test
asserting update sees the real files (and still scopes the nested ignore
correctly) so this can't recur at the update layer. Records both
regressions in the unreleased 0.9.16 changelog.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 13:18:28 +01:00
Alwyn93andClaude Fable 5 fb4d45226e fix(detect): scope nested ignore patterns to their own subtree (#1873)
Non-anchored patterns from a nested .gitignore/.graphifyignore were
matched against root-relative paths first, so a nested ignore file's
patterns leaked outside its directory. In the wild, .hypothesis/.gitignore
(a bare "*" auto-written by the hypothesis library) ignored the entire
repository and detect() returned 0 files.

Per gitignore semantics, patterns from A/.gitignore apply only to paths
under A. Match every pattern against the path relative to its own anchor
(the anchor dir itself exempt — an ignore file governs its directory's
contents, not the directory), and skip patterns whose anchor does not
contain the target.

Regression introduced with nested-ignore support in 8a5287a (#1206).
tests/test_detect.py: 143 passed, including the existing nested-ignore
and nested-negation tests plus two new regressions.

Fixes #1873

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 13:14:24 +01:00
safishamsiandClaude Opus 4.8 368407874f docs(changelog): record #1862 and #1860 in the unreleased 0.9.16 section
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 00:26:13 +01:00
thejesh e32be08c2a fix(detect): legacy-manifest branch must !=-compare mtime to catch reverse jumps (#1859) 2026-07-14 00:25:36 +01:00
thejesh 20405a84bf fix(dedup): report fuzzy count in summary when exact_merges is 0 (#1857) 2026-07-14 00:25:35 +01:00
safishamsiandClaude Opus 4.8 cfc7cf2c93 fix(cache): resolve FileSlice via unit_path in checkpoint allowlist (#1870)
The #1757 batch-scoping followup built the per-chunk allowlist by reading
FileSlice.rel, which does not exist (a FileSlice carries its parent file
in .path). So every chunk containing a sliced oversized document leaked
the FileSlice object into the allowlist, save_semantic_cache raised
TypeError on Path(FileSlice), and the best-effort except swallowed it:
extraction finished but those chunks were never checkpointed, so a
re-run or a crash/rate-limit resume re-billed them.

Resolve each unit through the canonical unit_path() helper so a slice
maps to its parent file. Adds a regression test that slices a real
oversized .md and asserts the checkpoint writes without swallowing a
TypeError.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 00:25:34 +01:00
safishamsiandClaude Opus 4.8 961b78e57a test(watch): assert update writes community_name (#1855 followup); changelog
Adds the regression test the #1855 fix was missing: _rebuild_code must
produce graph.json whose clustered nodes carry community_name, guarding
against the label-stripping regression recurring. Also records #1847 and
#1855 in the 0.9.15 changelog.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:49:25 +01:00
Farda Karimov 6eb5923404 fix(watch): forward community_labels to to_json in _rebuild_code
`graphify update` (and the git hooks that share its code path) wrote
graph.json with numeric-only community IDs instead of readable hub
names, because `_rebuild_code` called `to_json()` without the
`community_labels` parameter that `cluster-only` already passes.
Running `cluster-only` right after `update` "fixed" the names again,
which was the visible symptom.

- watch.py: forward the already-computed `labels` dict into `to_json`,
  matching the `cluster-only` code path (cli.py:1203).
- watch.py: `_canonical_topology_for_compare` now also strips the new
  `community_name` field before diffing topology. Without this, the
  topology-unchanged cache (used to skip a full re-cluster) would
  never match again once graph.json started carrying names, forcing
  a full re-cluster on every subsequent `update` even with no code
  changes.

Fixes #1808
2026-07-13 18:35:20 +01:00
safishamsiandClaude Opus 4.8 7ca43ab314 test(detect): harden nested-ignore tests (#1847 followup)
Tighten the brittle negation test to use .py files so classification
lands in the deterministic `code` bucket (was checking a fuzzy
document+unclassified union), and add a composition test asserting a
nested `.gitignore` `!` re-include outranks both a root `.gitignore` and
`.git/info/exclude` (#1810) — locking the precedence across all three
ignore sources.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:35:09 +01:00
Mohak AgrawalandClaude Sonnet 5 8a5287a979 fix(detect): honor nested .gitignore/.graphifyignore files below the scan root (#1206)
detect() only read .gitignore/.graphifyignore in the scan root and its
ancestor directories (up to the nearest VCS root), loaded once before the
walk began. A .gitignore sitting in a descendant directory — e.g.
vendor/sub/.gitignore — was never read, so files/dirs it excluded leaked
into the graph. Real git (and every other gitignore-aware tool) honors
.gitignore at every directory level, not just the ancestor chain.

Extracts the per-directory read+parse logic into a shared
_load_dir_own_ignore() helper (used by both the existing ancestor-chain
loader and the new call site) and invokes it live inside detect()'s
os.walk loop for every directory visited, before that directory's
children are pruned — so a nested ignore file governs its own subtree
with the same closer-file-wins precedence git uses.

Adds three regression tests: nested file exclude, nested directory prune
(the walk never descends into it), and nested negation overriding a
broader root-level rule.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-13 18:29:32 +01:00
98c7ec039a fix(export): close stored XSS + broken neighbor links in graph.html (#1838)
The HTML report's neighbor "focus" links dropped an unescaped
JSON.stringify(nid) into a double-quoted inline onclick. The stringified
value carries its own quotes, so the attribute was truncated on every
node (links never worked), and a node id/label containing a double-quote
broke out of the attribute and injected live event handlers. AST ids are
[a-z0-9_]-safe, but ids/labels from documents or titles scraped via
`graphify add <url>` are not, so a hostile source could plant an
executable handler into a locally-opened report.

Carry the id in an HTML-escaped data-nid attribute and dispatch via one
delegated listener bound to document (survives the innerHTML rebuild that
recreates #neighbors-list). Closes the injection and repairs the links.

Reported by @edgestack-ai.

Co-Authored-By: edgestack-ai <edgestack-ai@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 17:48:26 +01:00
safishamsiandClaude Opus 4.8 94d3099540 fix(cache): stat-index must follow the cache location, not the key anchor
Completes #1774. The prior fix redirected the AST cache dir to CWD but
file_hash still called _ensure_stat_index(root) without the cache
location, so the hash fastpath's stat-index.json kept anchoring on the
key-root (the analyzed corpus) — leaving a stray graphify-out/cache/
stat-index.json inside a writable foreign corpus even though the AST
cache itself had moved to CWD.

Thread cache_root through file_hash -> _ensure_stat_index (which already
accepts it, #1747). Surfaced by an out-of-CWD parallel-extract edge case:
the leak was masked in the in-process test suite because _stat_index_root
is a set-once module global that an earlier test had already pinned. The
regression test resets that global to simulate a fresh process and
asserts the corpus stays clean while the stat index lands under CWD.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 10:29:26 +01:00
c3a42a35eb fix(extract): write AST cache to CWD, decoupled from the key anchor (#1774)
With no explicit cache_root, extract() wrote graphify-out/cache/ under the
inferred common parent of the inputs — the analyzed source tree — so
scanning a read-only/foreign corpus silently polluted it.

The naive fix (point the root at CWD) breaks two other things that shared
the same parameter: file_hash keys become absolute/non-portable for an
out-of-CWD corpus, and the XAML/C# project-scan boundary would scan CWD
instead of the corpus. So split cache LOCATION from key/id ANCHOR:
load_cached/save_cached gain a cache_root arg for where the dir lives,
while `root` (inferred common parent) still anchors file_hash keys,
source_file relativization, node ids, and the XAML boundary. extract()
now locates the cache at CWD (or cache_root) but anchors on `root`; the
parallel worker tuple carries both. Existing callers passing cache_root
(CLI, watcher) are unchanged.

Adopts @SimiSips's #1802 (the CWD default + the two location tests) and
adds the decoupling plus a regression test that keys stay relative for a
corpus outside CWD — the property the one-line version would have lost.

Co-Authored-By: SimiSips <SimiSips@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 01:34:35 +01:00
6ca8604142 fix(query): dedup seeds by label to stop generic-symbol flooding (#1766)
Many nodes sharing one generic label (framework route handlers all
labelled GET/POST, a repeated handler) consumed every BFS seed slot, so
query traversal explored near-identical neighborhoods and buried the
actual target. Seed selection now dedups by normalized label (GET/Get/get
collapse together), keeping one representative per label, and the per-term
guarantee loop honors the same cap so it can't reintroduce a dupe.

Adopts @devcool20's seed-dedup from #1832 but drops that PR's second
mechanism — a per-label multiplicity penalty applied inside the shared
_score_nodes. That scorer also resolves shortest_path/explain endpoints,
so dividing scores there silently reweighted path/explain (out of scope
for #1766 and able to flip endpoint selection); the dedup alone bounds
the flood. Also normalizes the dedup key (the PR keyed on the raw label).
Adds the tests the PR was missing: dedup of homonymous labels,
case/diacritic normalization, per-term-guarantee cap, and a guard that
identical-label nodes still score equally in _score_nodes.

Co-Authored-By: devcool20 <devcool20@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 01:03:02 +01:00
safishamsiandClaude Opus 4.8 da9616d99e fix(cache): scope the incremental checkpoint write too (#1757 followup)
The #1835 fix scoped save_semantic_cache's final CLI write to an
allowed_source_files allowlist, but the per-chunk incremental checkpoint
in llm.py `_checkpoint_chunk` — the write that actually runs on every
`graphify extract`/`update` via extract_corpus_parallel — still called
save_semantic_cache with no allowlist. A chunk whose model result
mis-attributes a node's source_file to another corpus file would merge
that stray fragment into the victim's cache entry (merge_existing=True).

Scope the checkpoint write to the chunk's own dispatched files (FileSlice
-> .rel, bare Path -> the relative source_file). Also hoist the
`import warnings` in cache.py to module level.

Adds an extract_corpus_parallel integration test: a chunk dispatching
only A.py that returns a node attributed to already-cached B.py must
leave B.py's cache entry untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 00:47:10 +01:00
tpateeq 579ba1da3c fix(cache): scope semantic cache writes to extracted files (#1757) 2026-07-13 00:35:32 +01:00
a46eee49ef fix(export): coerce non-scalar attrs in graphml; harden pipe-close flush
#1831 — `graphify export graphml` crashed on any dict/list-valued
attribute (per-node metadata dict, graph-level hyperedges list) because
nx.write_graphml only accepts scalars; a real ~2,300-node graph failed
every export and left a 0-byte .graphml behind. to_graphml now coerces
None->"" and JSON-serializes non-scalars across graph/node/edge scopes
(int/float/bool/str pass through), and writes atomically via a temp file
so a failed export can't leave a partial file. Closes #1830.

#1807 followup — adopt @varuntej07's explicit in-guard sys.stdout.flush()
from #1811: piped stdout is block-buffered, so a small fully-buffered
output would only flush at interpreter shutdown (outside the guard),
where a closed-pipe reader escapes as a noisy shutdown error and nonzero
exit. Flushing inside the try closes that gap. Closes #1811.

Reported by @hofmockel (#1831) and @varuntej07 (#1807/#1811).

Co-Authored-By: hofmockel <hofmockel@users.noreply.github.com>
Co-Authored-By: varuntej07 <varuntej07@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 23:57:16 +01:00
5f57c46b92 fix(detect,hooks): honor .git/info/exclude; guard worktrees (#1810, #1809)
#1810 — detection read only .gitignore/.graphifyignore, never
.git/info/exclude, which is where git records local-only excludes and
where `git worktree add` writes nested worktree paths. graphify walked
into those worktree copies and the graph exploded (one 5-worktree repo:
9.4k nodes/10MB -> 210k nodes/311MB, ~77% duplicate). detect now loads
info/exclude at lowest precedence (below every per-dir .gitignore, per
git, so a nearer `!` still wins) and resolves the linked-worktree /
submodule case where `.git` is a file to the shared common git dir.

#1809 — two git-hook gaps: (a) post-checkout never honored
GRAPHIFY_SKIP_HOOK, so the var stopped commit rebuilds but not
branch-switch ones; now checked in both. (b) with core.hooksPath shared
across worktrees, a commit in any linked worktree fired post-commit,
which wrote a rogue delta-only graph.json into it and raced deploy/CI
`git clean` against the detached rebuild. Both hooks now short-circuit
in a linked worktree (git-dir != git-common-dir), comparing ABSOLUTE
paths so the primary checkout (where --git-common-dir is the relative
".git") is never false-positived and skipped.

Adds regression tests: info/exclude honored + negation precedence;
both hooks honor the skip env and carry the worktree guard; and an
end-to-end guard check against a real `git worktree`.

Reported by @cdahl86-cyber (#1810, #1809); the worktree guard was
co-developed with @Claude-Madera's PR #1806.

Co-Authored-By: cdahl86-cyber <cdahl86-cyber@users.noreply.github.com>
Co-Authored-By: Claude-Madera <Claude-Madera@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 16:15:24 +01:00
90b545c609 fix(cli): survive early pipe close (#1807); skip .nox venvs (#1804)
#1807 — piping graphify into a reader that stops early (head,
Select-Object -First N, sed q) disconnected stdout mid-write, raising an
unhandled BrokenPipeError (OSError(EINVAL) on Windows) and exiting 255,
so CI wrappers and agent harnesses read a successful query as a failure.
The console entry point now wraps the CLI body: a closed-pipe reader is
treated as success — stdout is redirected to devnull so shutdown flush
can't raise again, and the process exits 0. Adds a subprocess regression
test.

#1804 — .nox/ (nox virtualenvs, tox's successor, same .nox/ tree shape)
was missing from _SKIP_DIRS while .tox was present, so nox site-packages
got fully indexed (one repo came out 91% venv noise). Added next to .tox
with a regression test.

Reported by @varuntej07 (#1807) and @igorregoir-lgtm (#1804).

Co-Authored-By: varuntej07 <varuntej07@users.noreply.github.com>
Co-Authored-By: igorregoir-lgtm <igorregoir-lgtm@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:24:42 +01:00
373bc8efd8 fix(sln): keep Visual Studio solution-folder node ids relative (#1789)
A solution folder is a virtual grouping, not a file: VS writes its name
as both the display name and the "path" (name == path, no real file).
extract_sln resolved it to an absolute filesystem path anyway and keyed
the node id off that. The CLI id-relativization pass only remaps ids of
real files in the scan set, so a virtual folder never matched and its
absolute id (with the local username) survived into a committed
graph.json.

Detect solution folders (name == path) and key their id/source_file off
the folder name only; real project files still resolve as before. Adds a
regression test asserting the folder node id is relative.

The earlier fix (0.9.13) covered .csproj/.sln file nodes but missed the
virtual folders, so #1789 was closed prematurely; this completes it.

Reported and diagnosed by @fremat79.

Co-Authored-By: fremat79 <fremat79@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 14:31:50 +01:00
safishamsiandClaude Opus 4.8 eec7a01838 docs(changelog): finalize 0.9.13 notes and 0.9.12 section
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 11:12:18 +01:00
adam-pond-agentandClaude Opus 4.8 da71f8264f fix(querylog): make the query log opt-in, off by default (#1797)
querylog wrote every query/path/explain question + corpus path (and full
responses under GRAPHIFY_QUERY_LOG_RESPONSES) to a default-on, unbounded,
fail-silent plaintext file at ~/.cache/graphify-queries.log — outside any repo's
.gitignore/retention, and undocumented. A default-on plaintext record of
proprietary queries contradicts graphify's on-device / no-telemetry posture.

Flip to opt-in: _log_path() returns None unless GRAPHIFY_QUERY_LOG_ENABLE=1
(default path) or GRAPHIFY_QUERY_LOG=<path> is set; GRAPHIFY_QUERY_LOG_DISABLE=1
still forces it off (back-compat, wins). Document all four env vars in the
README (the old entries implied default-on). Regression tests cover
default-off, both enable paths, disable-wins, and that log_query writes nothing
without opt-in.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 10:36:00 +01:00
jerp86andClaude Opus 4.8 71d7ab9d71 fix(build): merge markdown quick-scan doc node into its semantic _doc twin (#1799)
The semantic pass mints a document node <slug>_doc; the markdown quick-scan
(extract_markdown) mints the bare <slug>. After a semantic build, a `graphify
update` (AST path) re-runs the quick-scan and the graph ends up with BOTH — one
document as two disconnected nodes, the file's edges split between them (semantic
`references`/hyperedges on the _doc twin, quick-scan cross-links on the bare
one). path/query traversals dead-end on the wrong twin; degree and communities
split.

build_from_json now reconciles the pair: when <slug> and <slug>_doc both exist
with the same source_file and both are file_type=document, remap the bare node
into the semantic _doc node (canonical, richer edges) and repoint its edges and
hyperedges. Remap-induced self-loops are dropped; pre-existing ones are left
alone. Gated to document twins for the same file, so a code symbol `foo` and an
unrelated `foo_doc` never merge. Regression tests for both.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 10:23:36 +01:00
CJNAandClaude Opus 4.8 591da764a1 fix(watch): require deletion evidence before evicting a missing source (#1795)
_reconcile_existing_graph treated "source identity absent from the collected
corpus" as deletion and evicted its nodes/edges/hyperedges. But corpus absence
is ambiguous: it's also what you see when a file still exists and merely stopped
being collected (ignore rules or filters changed). Upgrading into the merged-
.gitignore scan semantics (#1363) mass-evicted 655 nodes from a deliberately-
built, .gitignore'd docs dir whose files were present the whole time — reported
as a successful rebuild.

Fail-closed: before evicting a corpus-absent identity, require Path(identity)
.exists() is False (identity is an absolute path). Alive-but-excluded sources
are preserved (nodes, edges, hyperedges) and a loud line reports how many were
kept and why. True deletions and renames still evict (old path gone from disk);
a full extract --force still purges deliberate exclusions via the AST ownership
rule. Existence is memoized (one stat per file that left the corpus).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 00:37:09 +01:00
safishamsiandClaude Opus 4.8 0efb2a443c docs: point all website links at graphify.com
Switch every website URL from graphifylabs.ai to graphify.com — the hero logo,
the Penpax section, and the waitlist link — across the main README and the
translated READMEs. The contact email stays on graphifylabs.ai (mail is hosted
there); no mailto links were changed. graphify.com is the official graphify
product site; graphifylabs.ai remains the company site (org profile + email).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 18:07:57 +01:00
erichkusukiandClaude Opus 4.8 091f6095b4 fix(build): never prune a re-extracted source in build_merge (#1796)
build_merge already drops a re-extracted file's stale base nodes before merging
(replace-per-source), so on current code an EDITED file passed only in
new_chunks is handled correctly. But the prune step still removed every node
whose source_file was in prune_sources, with no guard for re-extracted files —
so a caller following the old edit-workflow (pass the changed file in BOTH
new_chunks and prune_sources) had its freshly-built nodes deleted after the
merge, silently losing a concept whose label survived the edit.

Exclude new_sources (files present in new_chunks) from prune_set: a re-extracted
file is being replaced, never deleted, so "replace" wins over a contradictory
"delete" of the same source. Genuine deletions (in prune_sources but not
new_chunks) still prune. Regression tests for both.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 17:22:25 +01:00
safishamsiandClaude Opus 4.8 0d0e5780c8 test(cli): graph.json node ids are portable across checkout paths (#1789)
The absolute-path-in-node-ids leak reported on 0.8.19 is already fixed on v8:
detect() returns paths relative to the scan root, so the CLI-produced graph.json
uses relative structural node ids (portable, no username/home leak). Lock it with
a regression test that extracts the same corpus from two different absolute
checkout dirs and asserts identical, leak-free node ids.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 16:31:10 +01:00
CJNAandClaude Opus 4.8 b688a26f71 fix(path): prefer full-token label matches when resolving path endpoints (#1785)
`graphify path` committed each endpoint to _score_nodes()[0]. The full-query
bonus tier only fires when the query equals/prefixes a label, so a query that is
a token subset of the intended label ("Reject-everything judge" vs "Degenerate
Reject-Everything Judge") got no bonus and a node prefix-matching one rare token
("Rejection Summary") could out-score it on IDF alone — anchoring the path on an
unrelated, often disconnected node and returning a false "No path found".

_pick_scored_endpoint() scans the score-ordered list and takes the first
candidate whose label contains EVERY query token, falling back to scored[0] when
none does — so when the head already full-matches (the common case) resolution
is unchanged. Wired into both the `path` CLI and the MCP _tool_shortest_path.
The close-runner-up ambiguity warning now fires only when the picked endpoint is
the raw score head (a full-token override was chosen on coverage, not score, so
the head's margin is irrelevant).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 11:56:38 +01:00
balloon72andClaude Opus 4.8 15a86536c4 fix(analyze): exclude rationale nodes from suggested-question gap count (#1768)
suggest_questions()'s "isolated/weakly-connected nodes" filter was missing the
`file_type != "rationale"` exclusion that report.py's Knowledge Gaps section
already applies, so the same GRAPH_REPORT.md reported two different counts for
the same concept (757 vs 245 on a real graph) — an internal inconsistency that
made a healthy graph look like a documentation problem. Add the same filter so
both computations agree.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 11:52:12 +01:00
balloon72andClaude Opus 4.8 a646d66a67 fix(bash): link executed scripts across files (#1756)
extract_bash only created a cross-file edge for `source x.sh` / `. x.sh`. The
two most common ways one script runs another — `bash x.sh` and `./x.sh` —
produced no edge, so in any repo where scripts invoke each other by execution
the call topology was missing (each script left an isolated file+entry pair).

Emit a `calls` edge (context `script_invocation`) from the caller's entry (or
enclosing function) to the invoked script's entry node, for script-runner
commands (bash/sh/zsh/ksh/dash <path>) and bare `./x.sh`, but only when the
target resolves to a real .sh file on disk — so no phantom edges to missing or
function-shadowed names. Verified end-to-end: the edges land on real target
nodes (no dangling drop at build).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 11:48:10 +01:00
krishnateja7andClaude Opus 4.8 5777fec8c1 fix(extract): route .rake files to the Ruby extractor + resolution (#1784)
.rake files are plain Ruby (Rake's task DSL is ordinary method calls), but the
extension was gated out everywhere, so rake tasks were classified as
unsupported, skipped, and their calls invisible. Add `.rake` to all seven `.rb`
gates the reporter mapped:
  - detect.CODE_EXTENSIONS (classification)
  - extract._DISPATCH (extractor dispatch)
  - extract._LANG_FAMILY_BY_EXT-adjacent language-name map (.rake -> ruby)
  - the ruby_member_calls LanguageResolver suffix set
  - both `.rb`-suffix filters in ruby_resolution.py (raw-call gather + class-def index)
  - analyze language-stats map
  - build repo-tag map

The extractor already parsed the content; this is purely extension routing.
Regression test: a `.rake` task's `Widget.tally` resolves cross-file to the
`.rb` definition.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 11:31:47 +01:00
safishamsiandClaude Opus 4.8 df74ab4481 test(csharp): chained call off new X(...) resolves (#1770)
The reported bug — a method chained directly onto a `new X(...)` expression
(no intermediate variable) producing no calls edge — is already fixed on v8:
`new Merger(ctx).Combine(...)` emits calls -> Merger.Combine. Add a regression
test so the fluent new-expression receiver stays covered.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 21:57:16 +01:00
EmilNygandClaude Opus 4.8 3c3b6554e7 fix(extract): rewire cross-module function references to their definition (#1781)
_rewire_unique_stub_nodes gated merge targets through _is_type_like_definition,
which rejects any label ending in `)`. So a function referenced from another
module (passed by name, e.g. FastAPI's Depends(get_db)) left its reference edge
dangling on a sourceless name-only stub while the real def had zero incoming
edges — "who references this function" returned nothing. Class/type symbols were
fine; only functions/methods suffered.

Top-level function defs (label `name()`, not `.name()` methods or `Class.m()`
qualifiers) are now eligible rewire targets, but only when:
  - the label key matches exactly one such function corpus-wide (existing
    unique-candidate guard — two same-named functions stay unresolved), AND
  - the candidate shares a language family with the stub's referrers, so a
    Python `get_db` reference can't bind to a unique Go `get_db()` (#1718/#1749
    interop guard), AND
  - the stub is not used as a supertype (inherits/implements/extends) — you
    don't inherit from a function.

Types are unchanged. Regression tests: cross-module function ref binds to def;
cross-language, ambiguous, and supertype cases all correctly left unresolved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 21:44:31 +01:00
safishamsiandClaude Opus 4.8 ce5af6fbc5 test: guard to_html/sanitize_label against null source_file/label (#1775)
The TypeError reported on 0.1.14 is already fixed on v8: sanitize_label coerces
None ('if text is None: return ""') and the source_file call site guards with
str(data.get("source_file") or ""). Add regression tests (unit + to_html
integration with null label/source_file) so it can't silently regress.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 20:24:25 +01:00
safishamsiandClaude Opus 4.8 4c075f90ab docs(readme): unlink YC S26 badge until the public company page is live
The badge's href pointed at www.ycombinator.com/companies/graphify, which 404s
— the public S26 company page isn't published yet. Show the badge without a
link rather than ship a dead click; re-add the href once YC publishes the page.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 11:52:56 +01:00
rithyKabirandClaude Opus 4.8 35665a76ba fix(pg_introspect): read FKs from pg_constraint so read-only roles get references edges (#1746)
The live-introspection FK query joined information_schema.referential_
constraints, which Postgres only exposes for constraints where the current user
has WRITE access to the referencing table. A read-only introspection role
therefore got zero FK rows — while tables/views/routines still appeared (SELECT
is enough for those views) — so the graph silently lost every `references`
edge, contradicting the documented FK-mapping behavior.

Switch to pg_catalog.pg_constraint (world-readable, not privilege-filtered),
keyed by constraint oid rather than name — which also fixes a latent bug where
same-named constraints on sibling tables could cross-match in the old
name-based key_column_usage joins. Composite-FK column order is preserved with
UNNEST(conkey/confkey) WITH ORDINALITY. Mock test asserts the query targets
pg_constraint and not the privilege-filtered view, plus composite-FK ordering.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 11:12:28 +01:00
oleksii-tumanovandClaude Opus 4.8 d68bf2819c fix(extract): create json_config reference target nodes (#1764)
extract_json emitted `imports` edges for package.json dependencies and
`extends`/`$ref` edges for tsconfig.json to target ids (`_make_id("ref", ...)`
/ `_make_id(key)`) that it never created as nodes. build_from_json drops edges
to unknown node ids silently (that case is filtered out of real_errors), so
dependency and extends structure vanished from the graph on two of the most
common files in any JS/TS repo, surfaced only by diagnose_extraction after the
fact.

The extractor now adds the referenced target as a `concept` node (external ref,
not a corpus file) before emitting each edge, so the edges survive build.
Regression test asserts no dangling endpoints, the concept nodes exist, and the
import/extends edges land on real targets with no self-loops.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 10:53:58 +01:00
oleksii-tumanovandClaude Opus 4.8 51b15a9ff1 fix(update): preserve surviving hyperedges on AST-only rebuild (#1755)
`graphify update` (the watch._rebuild_code / _reconcile_existing_graph path)
evicted every hyperedge whose source_file is in the corpus, because on a full
update every corpus file counts as "rebuilt" and hyperedge eviction reused the
node/edge eviction set. But the AST pass never emits hyperedges, so nothing
replaced them — doc-sourced hyperedges (what semantic extraction produces) were
permanently lost on the first update after a full build, even on a no-op run.

Split out a hyperedge_evicted_source_identities set scoped to genuinely deleted
(and symlink-target-outside) sources only, not merely-rebuilt ones. Replacement-
by-id (new_hyperedge_ids) and dangling-member cleanup are unchanged, so a real
semantic re-extraction still replaces its own hyperedges and orphaned ones are
still dropped. Parametrized regression test (full + incremental doc update).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 10:48:57 +01:00
oleksii-tumanovandClaude Opus 4.8 dae602ccd1 fix(extract): resolve Java member calls by receiver type (#1696)
Java member calls (`gw.charge()`) resolved by bare method name, so a call bound
to any same-named method in the corpus — e.g. `PaymentGateway.charge` and
`AuditLog.charge` were indistinguishable, producing phantom cross-class edges
and a false god node.

The extractor now preserves the receiver and its static type, and
_resolve_java_member_calls binds the call against the receiver's declared type:
explicit-type receivers and `this` are exact; current-class fields, method
parameters, and explicitly-typed locals resolve via a method-scoped type table;
a missing/ambiguous/inherited/chained receiver is skipped rather than falling
back to a bare name match (same single-owner god-node guard as the C#/Swift/Ruby
resolvers). Fully-qualified and nested-type receivers are deferred since they
need package- and nesting-aware type identity.

Verified: `gw.ping()/gw.charge()` (gw: PaymentGateway) bind to PaymentGateway,
the three charge() calls dedup to one edge, and no edge targets the same-named
AuditLog methods. Applies cleanly to the post-#1737 layout (extract.py +
extractors/engine.py). 13 new tests; full suite 3135 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 02:11:36 +01:00
bbqboogiedwonsenandClaude Opus 4.8 c5db9ffb06 fix(cli): keep outputs/cache with --out / --graph, not the corpus or CWD (#1747)
Case 1 — `extract <corpus> --out <dir>`: the graph went to <dir> (cache_root is
already passed to the AST extractor), but detect()'s word-count/stat-index cache
uses the scan root, so a stray graphify-out/cache/ was created inside the corpus
(and left behind even when the run aborted at the no-LLM-key gate). Thread an
optional cache_root through detect() -> cached_word_count() -> _ensure_stat_index()
and pass out_root from the extract CLI, so the stat index lives under --out. Entry
keys are absolute paths, so relocating the index file is safe.

Case 2 — `cluster-only --graph <elsewhere>/graphify-out/graph.json`: outputs
(GRAPH_REPORT.md, re-clustered graph.json, labels, analysis, html) were written to
the CWD's graphify-out/, ignoring where --graph lives. They now write beside the
input graph when it sits in a graphify-out/ dir (another project/tenant's output),
while still falling back to the CWD for an arbitrary archived backup/graph.json —
the restore-into-place workflow #934 pins.

Regression tests for both cases; #934 still passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 02:06:26 +01:00
philberndtandClaude Opus 4.8 bdc6e531a6 fix(build): don't bind imports/references across a language boundary (#1749)
The extraction spec forbids cross-language `calls` edges, and build already
dropped cross-language INFERRED `calls`. But `imports`/`references` had no such
guard: an unresolved Python `import time` resolved by bare stem (the #1504
old-stem alias) onto a `src/time.ts` file node, welding a polyglot repo's two
language halves together. In the reporter's repo three such edges were the only
bridge between 2409 Python and 1403 TS nodes, so every backend<->frontend
shortest path routed through time.ts, inflating its betweenness ~90x and making
it the #1 reported god node.

Hoist the interop-family map to a module constant and extend the edge-loop
guard to `imports`/`imports_from`/`references`. For these relations the edge is
dropped only when BOTH endpoints are known code languages of different families,
so a config/manifest -> code reference (unknown ext) is never mistaken for a
phantom. `calls` behavior is unchanged (still INFERRED-only, still drops when
either family differs). Regression tests: py->ts import dropped, ts->ts import
kept, config->code reference kept.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 00:20:55 +01:00
rithyKabirandClaude Opus 4.8 8b7ffc5b15 fix(extract): warn when files skip extraction for a missing optional dep (#1745)
When the [sql] extra is absent, .sql files are counted as code and scanned but
extract_sql returns an error result and zero nodes — and the graph builds
"successfully" with the entire SQL corpus missing. Neither existing warning
catches it: #1666's zero-node warning skips results carrying an "error", and
#1689 only covers files with NO extractor at all (.sql HAS a dispatch entry).

extract() now scans per-file results for a "not installed" error, groups the
affected files by extension, and prints a warning naming the extra that
restores the language (pip install "graphifyy[sql]"), via a small
_EXTRA_FOR_EXTENSION map (sql, terraform, dm). The map is only consulted after
an extractor actually reports the dependency missing, so it can't mislabel a
language that has a working fallback.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 23:43:47 +01:00
erasmust-dotcomandClaude Opus 4.8 29a6954f91 fix(build): make ghost-node merge deterministic across process runs (#1753)
build_from_json's ghost-node merge iterated set(G.nodes()), so when two nodes
shared a (basename, label) key the "canonical" survivor was chosen by CPython's
per-process string-hash order — rebuilding the same extraction JSON in a fresh
process could pick a different survivor, silently changing which node id
represents a concept. That breaks any workflow persisting ids across a rebuild;
concretely it broke the cluster->relabel step (community membership referenced
an id that the second build merged away -> KeyError in report generation).

Two changes:
- Pass 1 and Pass 2 now iterate sorted(node_set), not set(node_set), the same
  deterministic-order fix the edge loop below already uses on purpose.
- The #1257 ambiguity guard is extended to the case it did not cover: two
  NON-AST nodes sharing a key but from DIFFERENT source files are distinct
  concepts, not an AST ghost/canonical twin, so the key is marked ambiguous and
  both survive rather than one arbitrarily merging away (data loss). A genuine
  same-file duplicate (identical source_file) is not flagged and still
  collapses to one node.

Reported with a precise root-cause, minimal repro, and real-world impact by
@erasmust-dotcom.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 23:32:54 +01:00
CekaruandClaude Opus 4.8 9c27a52448 test(extractors): guard facade + registry identity for the per-language split (#1721)
The extract_terraform move #1721 proposed already landed on v8 via the #1737
decomposition (extractors/terraform.py exists, extract.py re-exports it, and
extractors/LANGUAGE_EXTRACTORS registers it), so the code move is a no-op now.
But the regression test @Cekaru added with it had no equivalent on v8. Salvage
and generalize it: sweep every LANGUAGE_EXTRACTORS entry and assert graphify.
extract re-exports the SAME object (facade identity) and the registry maps to
it (registry identity), plus the concrete terraform anchor from the PR. This
institutionalizes the re-export-identity guarantee the split relies on, so a
future move that forgets a facade re-export fails loudly.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 13:22:36 +01:00
safishamsiandClaude Opus 4.8 ee1ff3d691 fix(extract): resolve Java cross-module type references by import (#1744)
Two classes with the same simple name in different Maven modules
(FinancialEntryValidator in payment/ and core/) already survive as distinct
path-scoped nodes on v8 -- the "node silently disappears" report from 0.9.9 is
fixed. But a cross-module field/type `references` edge was still left dangling
on a sourceless phantom stub: _resolve_java_type_references (#1318) re-pointed
implements/inherits/extends/imports edges to the real definition using the
importing file's `import` statement, but its REPOINT_RELATIONS omitted
`references`, so bare-name resolution's shadow stub survived for field types.
A query about the referenced class could then miss it.

Add `references` to the Java resolver's REPOINT_RELATIONS. The C# sibling
already covers references; this brings Java to parity. The reference now
resolves to the imported package's class (falling back to same-package), and
the orphaned phantom is dropped. Regression test covers the ambiguous
two-module case: both reals present, no phantom, reference lands on the
imported class.

Reported with a precise root-cause and repro by @aviciot.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 10:44:50 +01:00
safishamsiandClaude Opus 4.8 d2d1f68ff9 fix: surface silently-skipped dirs in enumeration + dedup Pascal edges
Two correctness fixes found while analysing the reported 'graphify update
occasionally writes a partial graph.json' bug.

Enumeration (P0): detect()'s os.walk had no onerror handler, so any os.scandir
failure -- a transient PermissionError, or a directory created/deleted mid-walk
by concurrent writes (e.g. benchmarking racing the scan) -- was silently
swallowed and that entire subtree dropped out of the file list with no log, no
error. Downstream that becomes a silently partial graph.json. The walk now
records each skipped directory (surfaced as walk_errors in detect()'s result)
and warns to stderr, while still enumerating the rest of the tree. This stays
visible even when a --force/GRAPHIFY_FORCE rebuild bypasses the shrink guards.
Relatedly, to_json's #479 anti-shrink guard was fail-OPEN: a non-empty but
unreadable existing graph.json (corrupt or mid-write) proceeded with the
overwrite. It now fails SAFE -- refuse and point at force=True -- while an
empty/whitespace existing file (no nodes to lose) still proceeds. The size-cap
check keeps running before any read, so an oversized existing file is not
loaded into memory.

Pascal edges (P1): a class method declared in the interface section and defined
in the implementation section each emitted a "method" edge to the same node id,
and the edge helpers (unlike the node helpers) did not dedup, so ~half of a
Pascal/Delphi graph's method edges were doubled -- inflating degree/centrality
and tripping the #1739 cross-file resolver's single-owner god-node guard. Both
extractors now dedup edges on (source, target, relation).

Adds regression tests for all three behaviours.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:06:02 +01:00
richtextandClaude Opus 4.8 d89efbf9ef fix(extract): scope Pascal/Delphi call resolution + resolve inherited calls across files (#1739)
Both Pascal extractors resolved every call via a single file-wide
{method_name: node_id} dict, so two unrelated classes declaring a same-named
method (property accessors, generated COM/TLB wrapper classes) collapsed onto
whichever declaration was inserted last, producing wrong cross-class `calls`
edges. Resolution is now scoped: own class -> ancestor chain (inherits) ->
file-level free function -> unambiguous file-wide match; ambiguous at every
level emits no edge rather than guessing (same god-node guard as the Ruby
resolver).

Adds graphify/pascal_resolution.py, a corpus-wide post-extraction resolver
(registered via resolver_registry) that walks the inherits chain across file
boundaries, so a call from a manual descendant to a method it inherits from a
base class in a separate unit (the generated-base/manual-descendant split)
resolves. Also stops both extractors from emitting a duplicate base-class stub
carrying the referencing file's source_file, which collided with the real node
under cross-file id disambiguation. cache.py gives the new raw_calls bucket the
same portable-path treatment as nodes/edges so it round-trips.

Re-applied to the post-#1737 module layout (extractor hunks land in
graphify/extractors/pascal.py; registration stays in extract.py). Added one
adaptation the original PR predated: the cross-file resolver's god-node guard
now counts DISTINCT method nids, because the tree-sitter extractor emits a
method edge for both the interface declaration and the implementation, so the
same method_nid arrives twice -- without deduping, every inherited call looked
ambiguous and resolved to nothing.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 00:32:21 +01:00
fkhawajaghandClaude Opus 4.8 2f9deae8d5 fix(serve): scale per-term exact/prefix score tiers by squared term coverage (#1602)
In a multi-term query, a lone generic term that exactly equals a short leaf
label (`home` vs a `home()` action, `list` vs a `list()` function) received
the full exact-tier bonus and outscored nodes matching several of the query's
terms by ~10x, so `_pick_seeds`' gap cutoff discarded the genuinely relevant
candidates and `path`-style consumers of `scored[0]` had no backstop.

`_score_nodes` now scales the per-term exact/prefix tier contributions by the
squared fraction of query terms the node's label matches
(`tiered * (matched / n_terms) ** 2`). Squared because the exact tier is 10x
the prefix tier; label hits only (source-path hits score but don't count as
coverage, so a colliding leaf in the target's own directory can't win its
exact tier back via path fragments); query tokens deduped order-preserving so
a repeated word can't quadratically restore the collision. Single-term and
full-coverage queries are unchanged (coverage == 1), keeping identifier
exact-match dominance. Guarded against zero-term division.

Dropped the unrelated README badge changes from the PR; kept the scoring fix
and its two regression tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 23:56:28 +01:00
safishamsiandClaude Opus 4.8 e2d47535c3 Changelog: fold #1700 (Kotlin enums) and #1735 (uv probe) into 0.9.11
Both fixes landed after the initial 0.9.11 section was written but before
0.9.11 was published, so they belong in that release's notes rather than a
new version.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 23:41:01 +01:00
mohammedMsgmandClaude Opus 4.8 ea8b804b7f Fix uv interpreter detection falling back to graphify-less python (#1735)
Step 1's POSIX interpreter probe ran `uv tool run graphifyy python -c ...`,
but the graphifyy package exposes its executable as `graphify`, so uv treated
`python` as a missing `graphifyy` command. The probe failed, and `2>/dev/null`
swallowed uv's "use --from" hint, leaving PYTHON on a system interpreter that
does not have graphify installed. The probe now runs
`uv tool run --from graphifyy python -c ...`.

Applied to the skillgen source fragments (shell/posix.md and the aider/devin
monoliths) and regenerated all skill*.md; added a sanctioned monolith-diff
predicate and re-blessed the expected/ snapshots. The PowerShell path was
already correct (it probes the venv python.exe directly).

Reported and originally patched by @mohammedMsgm in #1736.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 23:08:05 +01:00
ivanzhilovichandClaude Opus 4.8 00dd978d17 fix(extract): emit Kotlin enum entries as nodes with case_of edges (#1700 Kotlin half, #1738)
Kotlin enum entries weren't extracted: the walker never descended into the enum
body (`enum_class_body` wasn't in _KOTLIN_CONFIG.body_fallback_child_types, so
_find_body returned None). Add `enum_class_body` to the fallback body types and a
`_kotlin_extra_walk` (dispatched for tree_sitter_kotlin, mirroring the Java/Swift
handling) that emits each enum_entry as a node with a `case_of` edge to the enum.

Re-applied from PR #1738 (@ivanzhl) onto the post-#1737 module layout: the walk
engine now lives in graphify/extractors/engine.py while _KOTLIN_CONFIG stays in
extract.py. Closes the Kotlin half of #1700 (Java was #1719).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 22:49:01 +01:00
safishamsiandClaude Opus 4.8 87b330c44f Release 0.9.11
Decompose extract.py / __main__.py / export.py into focused modules (#1737,
verbatim, no behavior change). Plus fixes since 0.9.10: merge-graphs distinct
repo tags (#1729), uninstall cleans Claude .local files (#1731), and
extract --code-only for keyless code-only indexing of a mixed repo (#1734).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 22:21:41 +01:00
tpateeqandClaude Opus 4.8 247b2ae603 refactor(main): move the command dispatch into graphify/cli.py
main() was a 2,760-line function that was almost entirely a 2,538-line
if/elif chain dispatching every non-install subcommand (query, path, explain,
diagnose, affected, reflect, save-result, extract, update, cluster-only, label,
build, global, merge-graphs, merge-driver, watch, tree, export, benchmark,
clone, prs, provider, hook*, check-update, and the `graphify <path>` redirect).

Move that chain, plus its 5 chain-only helpers (_StageTimer, _clone_repo,
_default_graph_path, _enforce_graph_size_cap_or_exit, _run_hook_guard) and 4
chain-only constants (_SEARCH_NUDGE, _READ_NUDGE, _HOOK_SOURCE_EXTS,
_GEMINI_NUDGE_TEXT), into graphify/cli.py as dispatch_command(cmd). main() now
does its setup (encoding, stale-skill check, version/help) then
`if dispatch_install_cli(cmd): return` else `dispatch_command(cmd)`.

The chain ends in its own unknown-command exit, so it's called as a statement —
no return-value plumbing. The one cli->__main__ coupling, the path-redirect's
recursive main() call, is handled by a lazy import (_reenter_main), so import
direction stays __main__ -> cli with no cycle. __main__ re-exports every moved
symbol, so importers/tests are unchanged.

__main__.py 3,388 -> 662 LOC (5,368 at branch start, -88%). Verified end-to-end:
version/help/unknown-command, the `graphify <path>` redirect (rebuilds a graph),
and query/path/explain. Full suite unchanged: 3036 passed, 29 skipped; skillgen OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 02:13:04 +05:30
tpateeqandClaude Opus 4.8 563bb599fa refactor(extract): migrate pascal, objc, and julia extractors to extractors/
Now that the resolution passes and the tree-sitter engine live in their own
modules, these three bespoke extractors are self-contained and move cleanly
(verbatim), pulling only the specific engine/resolution/base helpers they need:

- extractors/pascal.py: extract_pascal + regex helpers + _PAS_* constants
- extractors/objc.py: extract_objc + Objective-C member-call resolution
- extractors/julia.py: extract_julia

Re-exported from extract.py and registered in extractors/__init__.py (27 langs).
The remaining in-file extractors (js/ts config family + vue/svelte/astro/xaml)
stay because they share _JS_CONFIG/_TS_CONFIG and the xaml dispatch caches with
extract_js/extract_csharp and the dispatcher.

extract.py 5,947 -> 4,740 LOC (17,054 at branch start, -72%). Full suite
unchanged: 3036 passed, 29 skipped; skillgen --check OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 02:03:52 +05:30
tpateeqandClaude Opus 4.8 5015212fc1 refactor(extract): extract the _extract_generic tree-sitter engine into extractors/engine.py
Moves the config-driven extraction engine — _extract_generic (~2.2k LOC) and its
67-function closure of per-language tree-sitter walkers/type-collectors
(_js_*, _ts_*, _python_*, _java_*, _csharp_*, _cpp_*, _swift_*, _kotlin_*,
_php_*, _ruby_*, _scala_*) plus 10 engine-private constants (language builtin/type
tables) — into graphify/extractors/engine.py, verbatim.

AST analysis proved the engine closure references neither `extract` nor
`_DISPATCH`, so the dispatcher facade (extract, _DISPATCH, _get_extractor,
collect_files, the thin config-driven extractor wrappers) stays in extract.py and
imports the engine. Import direction: extract.py -> engine -> {resolution, models,
base}; no shared constant crosses the boundary (verified), and engine pulls a
single name (_resolve_js_import_target) from resolution, so there is no cycle.

extract.py re-exports every moved symbol, so importers and tests reaching into
engine internals are unchanged.

extract.py 10,270 -> 5,947 LOC (17,054 at branch start, -65%). Full suite
unchanged: 3036 passed, 29 skipped; skillgen --check OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 02:01:27 +05:30
tpateeqandClaude Opus 4.8 9b4ffdad4c build: package the new graphify.exporters subpackage
setuptools uses an explicit package list, so the new graphify/exporters/ package
(base, html, graphdb — split out of export.py) was absent from the built wheel,
which would break `import graphify.exporters.*` for installed users. Add it
alongside graphify and graphify.extractors. No version change.

Verified: fresh-venv install of the rebuilt wheel imports every new module,
resolves all backward-compat re-exports, builds a multi-language graph, and runs
query/path/explain and install/uninstall.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:46:02 +05:30
tpateeqandClaude Opus 4.8 97a289c531 refactor(main): move install/platform CLI dispatch into install.dispatch_install_cli
main() carried a 256-line if/elif chain routing every install-family command
(install, uninstall, and the 22 per-platform targets: claude, codebuddy, gemini,
cursor, vscode, copilot, kilo, kiro, devin, pi, amp, agents/skills,
aider/codex/opencode/claw/droid/trae/trae-cn/hermes, antigravity). That block
only ever reads sys.argv and calls functions that already live in install.py, so
move it there verbatim as a guarded dispatch_install_cli(cmd) -> bool; main() now
does `if dispatch_install_cli(cmd): return`.

The command set is derived from the block's own conditions (so none is missed),
and the branch's early `return` becomes `return True` so the help path still
short-circuits. Verified end-to-end: `graphify claude install/uninstall`, unknown
command, and the install test suite all behave identically.

__main__.py 3,641 -> 3,388 LOC (5,368 at branch start, -37%). Full suite
unchanged: 3036 passed, 29 skipped; skillgen --check OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:42:12 +05:30
tpateeqandClaude Opus 4.8 4561da2088 refactor(extract): extract symbol-resolution subsystem into extractors/
Moves the cross-file symbol-resolution / import-resolution / decl-def-merge
passes — the largest remaining self-contained subsystem in extract.py — into
two new modules, verbatim:

- extractors/models.py: the shared data types (LanguageConfig, the
  _Symbol*Fact / _SymbolResolutionFacts dataclasses) and two shared caches
  (_WORKSPACE_PACKAGE_CACHE, _JS_CACHE_BYPASS_SUFFIXES). Homed here so both
  extract.py and resolution.py import them without a cycle; the mutable
  workspace cache keeps a single shared object identity (only ever .clear()'d
  in place), verified in the smoke test.
- extractors/resolution.py: 60 resolution functions (_resolve_*, _collect_*,
  _apply_symbol_resolution_facts, _disambiguate_colliding_node_ids,
  _merge_decl_def_classes, the JS/TS/Python import walkers, tsconfig/workspace
  resolution) and their 12 private constants.

extract.py re-exports every moved name, so importers (__main__, watch, tests
that reach into _JS_RESOLVE_EXTS / _resolve_cross_file_imports / the fact
dataclasses) are unchanged. Import direction is strictly extract.py ->
resolution -> {models, base}; AST analysis confirmed no moved non-entry symbol
is referenced from outside its new module.

extract.py 12,632 -> 10,270 LOC (17,054 at the start of this branch, -40%).
Full suite unchanged: 3036 passed, 29 skipped; skillgen --check OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:36:20 +05:30
tpateeqandClaude Opus 4.8 e8a22893c9 refactor(extract): migrate verilog and markdown extractors to extractors/
Continues the extract.py -> extractors/ split. Both are self-contained bespoke
extractors (verified: closure-private, byte-identical verbatim move, facade
identity + _DISPATCH resolution intact):

- extractors/verilog.py: extract_verilog + SystemVerilog helpers (_sv_*,
  _augment_systemverilog_semantics) and _SV_* constants.
- extractors/markdown.py: extract_markdown + _resolve_markdown_link and _MD_* regexes.

extract.py 13,121 -> 12,632 LOC. Full suite unchanged: 3036 passed, 29 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:31:17 +05:30
tpateeqandClaude Opus 4.8 4859f9883c refactor(export): split HTML and graph-DB exporters into graphify/exporters/
export.py mixed nine independent export targets in one 1,671-LOC module. Move
the two largest self-contained ones into a new graphify/exporters/ package,
verbatim, re-exported from export.py so every importer (from graphify.export
import to_html / push_to_neo4j) is unchanged:

- exporters/html.py: to_html + its private helpers (_html_script, _html_styles,
  _hyperedge_script, _viz_node_limit) and MAX_NODES_FOR_VIZ.
- exporters/graphdb.py: push_to_neo4j, push_to_falkordb.
- exporters/base.py: COMMUNITY_COLORS (shared by the HTML/SVG/Obsidian
  exporters), homed here so per-format modules and export.py both import it
  without a cycle.

Verified: AST closure-privacy analysis, facade object identity, ruff clean.
export.py drops 1,671 -> 962 LOC. Full suite unchanged: 3036 passed, 29 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:20:49 +05:30
tpateeqandClaude Opus 4.8 9fc30e680d refactor(extract): migrate 18 bespoke language extractors to extractors/ package
Continues the graphify/extract.py -> graphify/extractors/ split (MIGRATION.md,
upstream #1212), which already moved blade/zig/elixir/razor. Moves the
independent bespoke extractors whose closures are fully private (no shared
_extract_generic core, no shared mutable caches), verbatim, following the
documented invariants:

  dart, rust, go, powershell (+psd1 manifest), fortran, sql,
  dm (dm/dmm/dmi/dmf), bash, apex, terraform, sln,
  pascal_forms (delphi .dfm + lazarus .lfm), json_config

Each language's private helper funcs and constants move with it; only the
`extract_<lang>` entry points (plus fortran's _cpp_preprocess, which has a
direct unit test) are re-exported from extract.py's facade block, so every
existing importer (__main__.py, watch.py, tests) is unchanged and object
identity is preserved. Registry (extractors/__init__.py) grows 4 -> 22 langs.

Verified: AST closure-privacy analysis (no symbol referenced from outside its
moved set except via the facade); byte-identity of every moved span;
extract._DISPATCH still resolves every extension; ruff clean; skillgen --check
OK. extract.py drops 17,054 -> 13,121 LOC. Full suite unchanged: 3036 passed,
29 skipped (excluding env-only openai tests).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:11:37 +05:30
tpateeqandClaude Opus 4.8 cc2d3c13a6 refactor(main): extract install/uninstall subsystem into graphify/install.py
__main__.py was 5,368 LOC, more than half of it per-platform install/uninstall
machinery interleaved with the CLI dispatcher. Move that subsystem — 68
functions (all *_install/*_uninstall, _copy_skill_file, _platform_skill_destination,
_always_on, etc.) plus 21 module constants (_PLATFORM_CONFIG and the platform
skill/hook payload constants) — into a new graphify/install.py, extracted verbatim.

Behavior-preserving:
- install.py lives in the same package dir as __main__ so packaged-asset lookups
  via Path(__file__).parent ("always_on"/"skills") resolve unchanged.
- __main__ re-exports all 89 moved names, so `from graphify.__main__ import
  claude_install` (and every other import, incl. private helpers used by tests)
  keeps working, with object identity preserved.
- The install cluster was verified (AST) to have zero back-references into
  __main__, so no circular import; __main__ imports _PLATFORM_CONFIG et al. one-way.

__main__.py drops 5,368 -> 3,642 LOC. Full suite unchanged: 3036 passed, 29
skipped (excluding the env-only openai tests). ruff check clean; skillgen --check OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 00:20:48 +05:30
safishamsiandClaude Opus 4.8 20bfdf60ac feat(extract): add --code-only to index code without an LLM key on a mixed repo (#1734)
`graphify extract` on a repo containing docs/papers/images hard-failed when no
LLM backend was configured — even for a user who only wants the code graph. The
only workaround was hand-building a .graphifyignore of everything non-code, which
is onerous (the "not code" set is far larger than the code set).

`--code-only` skips the semantic (doc/paper/image) pass entirely: it indexes the
code via pure local AST (no key required) and reports what it skipped ("skipping
N non-code file(s) ...") rather than silently dropping it. The no-key error on a
mixed repo now also points users at the flag. Code-only was always keyless; this
just makes a *mixed* repo usable without a key instead of failing outright.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:07:31 +01:00
tpateeqandClaude Opus 4.8 0d206cbe11 fix(uninstall): remove graphify hook/section from Claude local-only files (#1731)
`graphify uninstall` (and `graphify claude uninstall`) only looked at
`.claude/settings.json` and root `CLAUDE.md`. A user who relocates the
PreToolUse hook into `.claude/settings.local.json` and the `## graphify`
instructions into `CLAUDE.local.md` / `.claude/CLAUDE.local.md` - so they
are not committed to a shared repo - was left with both behind after
uninstall, which reported "nothing to do".

- `_uninstall_claude_hook` now strips the hook from both `settings.json`
  and `settings.local.json` (factored into `_strip_graphify_hook`).
- `claude_uninstall` now strips the `## graphify` section from `CLAUDE.md`,
  root `CLAUDE.local.md`, and `.claude/CLAUDE.local.md` (factored into
  `_strip_graphify_md_section`), cleaning every present file rather than the
  first, and always runs the hook cleanup.
- `_strip_graphify_md_section` reads the two newly-covered files defensively
  so a non-UTF-8 or otherwise unreadable file can't abort uninstall.

Unrelated local-only files (no graphify content) are left byte-for-byte
untouched. The `--local` install flag suggested in the issue is left out of
scope; this change makes uninstall symmetric with wherever the config lives.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:38:35 +01:00
safishamsiandClaude Opus 4.8 4be0f7b3bf fix(merge-graphs): give each input a distinct repo tag so same-stem nodes don't collapse (#1729)
merge-graphs prefixed each graph's node ids with `<repo>::` where repo was
`gp.parent.parent.name` — the graphify-out parent dir name. That tag is not
unique across inputs: `src/graphify-out` and `frontend/src/graphify-out` both
yield `src`, so a bare `app` node from a backend `src/app.js` and a frontend
`App.jsx` both became `src::app` and nx.compose silently merged them into one
node (one graph's label/source_file, both graphs' edges) — inventing false
cross-runtime `path` results with no warning.

New `distinct_repo_tags` guarantees a unique prefix per graph: colliding tags
are widened with their own parent dir (`frontend_src`), then an index suffix
backstops any residual duplicate. The handler prints a note when it disambiguates.
Verified end to end: the two `app` nodes now survive as `..._src::app` and
`frontend_src::app` instead of collapsing. Regression tests cover the merge case
and the tag uniquifier (pass-through, widening, and triple-collision fallback).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 12:45:08 +01:00
safishamsiandClaude Opus 4.8 5c6f7272cd test(extract): cover builtin static-call shape (Date.now()) for #1726
Adds a regression test for the Date.now()/static-call shape (credit PR #1727 /
@2loch-ness6, who independently found the same fix): a capitalized builtin
receiver must not bind cross-file to a same-spelled user const/class. The same
guard added in 67f4f83 already covers it (verified); this locks the static-call
shape in, while allowing the legitimate same-file const reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 12:09:40 +01:00
safishamsiandClaude Opus 4.8 781d1cd8ec Release 0.9.10
Correctness batch since 0.9.9: TS/JS builtin-typed receiver no longer collapses
onto a same-named user symbol (#1726); no cross-language calls edges (#1718);
build_merge ambiguous-alias no longer merges unrelated files (#1713); base-class
stubs tagged with origin_file (#1707); Java enum constants as nodes (#1719);
rebuild recovers from a deleted hook cwd (#1703); per-chunk semantic-cache
checkpoint (#1715); SECURITY.md http-transport doc + GRAPHIFY_MAX_GRAPH_BYTES
tests (#1714, #1722). Nine merged PRs plus #1726.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 11:39:39 +01:00
safishamsiandClaude Opus 4.8 67f4f835f7 fix(extract): skip builtin-global receiver types in TS/JS member-call resolution (#1726)
`_resolve_typescript_member_calls` resolves a member call's receiver to a type
definition by casefolded label. For a builtin-typed receiver (`x: Date;
x.getTime()`), `_key("Date")` == "date" matched a same-named user `class DATE` /
`const DATE` in another file, binding the caller to it as a phantom
`references[call]` edge. In a real 3,368-file repo one module-local `const DATE`
accumulated 469 false cross-file edges (degree 472, betweenness 0.435) — a false
god node distorting path/god-node results.

Skip the resolution when the receiver type is an ECMAScript/Python builtin
global (Date, Promise, Map, ...), mirroring the guard the cross-file CALL
resolver already applies (#726). The guard is a strict no-op for genuine user
types, so legitimate constructor-injection member-call resolution (#1316) is
unaffected. Verified across new Date().method(), return-type, and var-decl-type
shapes: zero phantom edges, user DATE degree back to 1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 11:25:28 +01:00
mallyskies 96db75c8c2 fix(build): recognize a salted file node as its own alias claimant
Follow-up to the previous commit on this branch. That fix's ambiguity check
missed a case: it detects "is this node the file itself" by checking
whether the node's id starts with the file's plain new_stem, but a
same-directory .h/.cpp pair that collides on their shared pre-extension id
gets salted apart by _disambiguate_colliding_node_ids into ids like
"tools_aolserver_utility_h_tools_aolserver_utility" -- no longer a clean
new_stem prefix.

That salted header silently failed to compute an empty suffix, so it never
entered the bare "utility" alias race at all, leaving an unrelated
wwwapi.masque.com/pages/utility.php as the lone (wrong) "unambiguous"
winner -- reproduced exactly against the real depot's
Tools/aolserver/utility.h and .cpp.

Detect "this node IS the file" by label instead: every file node's label is
its own basename regardless of what its id looks like after salting. That
keeps a salted file node in the alias competition, so the real collision
between the C header and the PHP file is correctly caught as ambiguous.
2026-07-08 01:24:25 +01:00
mallyskies 3b2ca2e55f fix(build): don't let an ambiguous legacy-stem alias silently merge files
build_from_json's "pre-migration alias index" (#1504) registers each real
file's OLD-style bare-stem id (extension dropped) as an alias so a stale
cached fragment referencing that old form still resolves after an id-scheme
migration. It never checked for collisions: two unrelated real files easily
compute the same bare alias (e.g. "ping.h" and "ping.php" in different
directories both alias to "ping"), and dict.setdefault let whichever file
happened to iterate first in a Python set win, arbitrarily.

A dangling edge with a bare, deliberately-unscoped fallback target (e.g. the
C/C++ extractor's last-resort id for an #include it couldn't resolve to a
real path) would ride that alias onto whatever unrelated file won the
collision -- silently wiring, say, a C++ server file to an unrelated PHP
script, purely because both files happen to share a common basename
somewhere in the corpus.

Now every candidate for an alias is collected before any of them are
committed to norm_to_id, and the alias is only trusted when exactly one real
file claims it. Ambiguous aliases are dropped entirely, so the dangling edge
correctly stays dangling (and gets discarded) instead of merging two
unrelated files -- same "don't guess through ambiguity" principle already
applied to stub-node disambiguation and cross-file call resolution
elsewhere in this codebase.

Found via graphify-practice round 2: a `path` query between two unrelated
symbols routed through exactly this kind of bogus edge, traced back to
Dev/Poker/TDServer/server.cpp's unresolved `#include "ping.h"` /
`#include "utility.h"` landing on unrelated www.masque.com PHP scripts of
the same bare name.
2026-07-08 01:24:25 +01:00
mallyskies 9557bf6733 fix(extract): tag inline base-class stubs with origin_file
ensure_named_node() tags the sourceless stub it creates for an
unresolved reference with origin_file, so _disambiguate_colliding_node_ids
can tell one file's unresolved reference apart from another's instead of
merging every file's same-named reference onto one shared bare id
(which can then collide with an unrelated same-named real definition
anywhere else in the corpus, since ids are case-normalized and global).

Five call sites duplicated that stub-creation logic inline instead of
calling ensure_named_node() -- Ruby's `Class.new(Super)` and
`class Foo < Base` inheritance, Python inheritance, Kotlin delegation
-specifier inheritance/conformance, and C++ base_class_clause
inheritance -- and none of them were updated when origin_file was added,
so all five still produce the un-disambiguated bare-id stub the fix was
meant to eliminate.

Four of the five sit directly inside _extract_generic, where
ensure_named_node() is already in scope as a closure, so they're
switched to call it directly. The fifth (Ruby's `Class.new(Super)`) is
handled by a separate helper, _ruby_extra_walk(), which doesn't have
that closure in scope; that one gets the same origin_file tag added
directly to its own inline stub dict, matching what ensure_named_node()
already does, without changing the helper's signature.

(A sixth occurrence of the same inline pattern exists in extract_apex(),
a fully separate regex-based extractor with no ensure_named_node()
equivalent of its own -- left out of this fix, which is scoped to the
shared _extract_generic path and its one directly-affiliated helper.)

Added a regression test: two different C++ files each inheriting from
the same undefined base class must produce two distinct stub nodes, not
one shared one. Fails on main (one shared 'base' id for both files),
passes with this fix.
2026-07-08 01:21:55 +01:00
edinaldoof bf7fa50f38 fix(extract): never bind a cross-file call to a definition in another language family
The cross-file call resolver matches raw-call callees against a repo-wide
label index with no language check. In a repo that mixes a web app with a
native Android app, a TSX callback passed by name (register(refreshHeading))
resolved to a same-named Kotlin method and shipped as an INFERRED
indirect_call edge — a phantom the extraction spec itself forbids ('calls
edges MUST stay within one language'). Direct calls from non-JS/TS callers
had the same hole with no gate at all: a bare Python call bound to the lone
same-named Kotlin fun. Found on a production Next.js + Android codebase,
where the phantom edge also inflated the Kotlin node's betweenness enough
to surface it as a top suggested question in GRAPH_REPORT.md.

Resolution candidates are now filtered by language interop family before
the single-candidate/import-evidence logic runs. Families are grouped by
REAL interop so legitimate cross-language resolution keeps working:
Kotlin/Java/Scala/Groovy share the JVM, C/C++/Objective-C/CUDA share
headers (Swift bridges to ObjC), and JS/TS variants plus Vue/Svelte/Astro
SFCs compile into one module graph. Candidates whose family is unknown
(no source_file, non-code nodes) are never filtered, preserving the
previous permissive behavior, and callers with an unmapped extension skip
the guard entirely.
2026-07-08 01:16:58 +01:00
safishamsiandClaude Opus 4.8 27b523e769 test(cache): cover save_semantic_cache merge_existing union + default overwrite (#1715)
The per-chunk checkpoint feature added merge_existing without test coverage.
Add tests asserting merge_existing=True unions a file's slices across chunks and
the default still overwrites (the authoritative final write in extract).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 01:14:12 +01:00
A.Levin 2ea37734c0 Checkpoint semantic cache per chunk so interrupted runs resume
Semantic extraction only wrote to the cache once, at the very end of the
run (save_semantic_cache in __main__ after extract_corpus_parallel returns).
A run interrupted partway — a crash, a kill, or a claude-cli/API run that
exits when it hits a rate limit — therefore lost every completed chunk and
restarted from scratch. On a large corpus with a slow local backend this can
throw away many hours of work.

Persist each chunk's results to the semantic cache as soon as it completes,
in both the serial and threaded paths of extract_corpus_parallel. Add a
merge_existing option to save_semantic_cache so a file split into slices
across several chunks accumulates its slices instead of the later chunk
overwriting the earlier one. The checkpoint is best-effort (a cache write
error never aborts extraction) and can be disabled with
GRAPHIFY_NO_INCREMENTAL_CACHE. Default behaviour of save_semantic_cache is
unchanged (merge_existing defaults to False).
2026-07-08 01:10:44 +01:00
Francisco Javier Serna Barragan e5044c3253 Fix rebuilds from deleted hook cwd
What changed
- Stabilize relative rebuild execution before graphify-out queue/lock setup.
- Recover from deleted transient hook CWDs when GRAPHIFY_REPO_ROOT points at the repository root.
- Fail cleanly when the current working directory is gone and no repo root fallback is available.
- Add regression coverage for both fallback and clean-failure paths.

Why
- Detached post-commit/post-checkout rebuilds can inherit a transient CWD that is deleted before the background process starts.
- _rebuild_code previously used relative graphify-out paths before Path.cwd()/watch_path resolution could be handled, causing FileNotFoundError: [Errno 2] No such file or directory.

Validation
- .venv/bin/pytest tests/test_watch.py -q: 54 passed, 2 skipped.
- .venv/bin/ruff check graphify/watch.py tests/test_watch.py: passed.
- .venv/bin/python -m py_compile graphify/watch.py tests/test_watch.py: passed.
- env -u PYTHONPATH -u PYTHONHOME PYTHONHASHSEED=0 .venv/bin/pytest -q: 2904 passed, 30 skipped.

Notes
- Full suite without PYTHONHASHSEED=0 exposed an unrelated ordering-sensitive labeling test; with the deterministic hash seed used by graphify hooks, the suite passes.
2026-07-08 01:08:02 +01:00
kaanrumin 6c33e3aad7 test(security): cover GRAPHIFY_MAX_GRAPH_BYTES parsing; clarify unit docstring
_max_graph_file_bytes() resolves the graph-load memory-bomb cap and parses the
GRAPHIFY_MAX_GRAPH_BYTES env var (plain bytes, MB/GB suffix, fallbacks), but had
no behavioral tests — only the default constant was asserted.

- Add tests for: unset/blank -> default, plain integer, MB/GB suffix (binary),
  case-insensitive and space-tolerant suffixes, unparseable -> default, and
  non-positive -> default.
- Fix the docstring, which described the suffix as "decimal multipliers of 1024"
  (self-contradictory). MB/GB are treated as binary (MiB/GiB); the tests lock
  that behavior in.

No behavior change.
2026-07-08 01:03:28 +01:00
Thizeidler 0ce8ea00e7 docs(security): clarify stdio-only claim now that HTTP transport exists
SECURITY.md said graphify never runs a network listener and only
communicates over stdio. README.md documents an opt-in --transport http
mode (with --host/--api-key flags) for sharing one server across a team,
which does open a network listener. Update the claim to describe the
default (stdio, no listener) and the documented opt-in exception.
2026-07-08 00:56:33 +01:00
ivanzhilovich cf36d10292 fix(extract): emit Java enum constants as nodes with case_of edges 2026-07-08 00:42:56 +01:00
safishamsiandClaude Opus 4.8 53efaf89b6 Release 0.9.9
Fixes since 0.9.8: explain punctuated-label matching (#1704); surface code files
with no AST extractor instead of dropping them silently (#1689); consistent
AST-extraction progress denominator (#1693); no dangling Obsidian wikilinks in
GRAPH_REPORT.md by default (#1712); MATLAB .m no longer force-parsed by the
Objective-C grammar (#1702); corrected the /graphify usage comment in the skill
files (#1681); surface unclassified files (Dockerfile/Makefile/...) instead of
vanishing (#1692).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 12:36:16 +01:00
safishamsiandClaude Opus 4.8 733ad08852 fix(extract): don't force-parse MATLAB .m through the Objective-C grammar (#1702)
`.m` is shared by Objective-C implementation files and MATLAB, but the extractor
dispatch routed every `.m` to extract_objc unconditionally. Feeding real MATLAB
to the Objective-C tree-sitter grammar yields root.has_error and garbage
nodes/edges — worse than skipping, because it pollutes the graph with wrong data.

_get_extractor now content-sniffs `.m` the same way `.h` already is: a genuine
Objective-C `.m` carries an ObjC directive (@implementation/@interface/@import/
#import) and still routes to extract_objc; a `.m` without one (MATLAB, Octave)
gets no extractor, so it is surfaced by the no-AST-extractor warning (#1689)
instead of mis-parsed. `.mm` is unambiguously Objective-C++ and is left untouched.

This stops the wrong-by-omission garbage; wiring a real tree-sitter-matlab
extractor (the issue's primary ask) remains a follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 11:46:51 +01:00
safishamsiandClaude Opus 4.8 ac6bb274a1 docs(skill): fix stale /graphify usage comment that claimed an Obsidian vault by default (#1681)
The Usage block's bare `/graphify` comment read "full pipeline on current
directory -> Obsidian vault", contradicting Step 6 (HTML viz always; Obsidian
vault only when --obsidian is explicitly given). The comment predated the
opt-in change and told agents a bare /graphify produces a vault. It now reads
"full pipeline on current directory (HTML viz; add --obsidian for a vault)".

Fixed at the skillgen source (fragments/core/core.md + the aider monolith
override), added a sanctioned-diff predicate so the monolith round-trip guard
allows the change, and re-blessed the expected/ snapshots. Every generated
skill-*.md now carries the corrected comment; the only content change across
all rendered files is this one line.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 11:34:54 +01:00
safishamsiandClaude Opus 4.8 23457d11ff feat(detect): surface unclassified files instead of dropping them silently (#1692)
When classify_file() returned None — an extensionless, non-shebang file
(Dockerfile, Gemfile, Makefile, Rakefile, LICENSE, ...) or an unsupported
extension — the file left no trace at all: not counted, not listed, nothing.
A user had no way to tell from graphify's output that those files were even
considered.

detect() now collects these into an "unclassified" list in its result, and
`graphify extract` prints a one-line summary after the scan counts:
"N file(s) not classified (no supported extension or shebang), skipped:
Dockerfile, Makefile, ...". Real code/docs are unaffected. This is the
visibility half of the issue; wiring up extractors/manifest handling for
Dockerfile/Makefile-style files remains a separate feature.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 11:19:18 +01:00
safishamsiandClaude Opus 4.8 f84a0af1bf fix(report): don't emit dangling [[_COMMUNITY_*]] wikilinks by default (#1712)
GRAPH_REPORT.md rendered the Community Hubs section as Obsidian wikilinks, but
the `_COMMUNITY_*.md` notes they target are only created by the opt-in
`--obsidian` export — and the report is written at build time, before any export
runs. So on a default run every link dangled: inside an Obsidian vault they
spawned phantom `_COMMUNITY_*` nodes in the graph view, and outside Obsidian they
rendered as literal brackets that navigate nowhere.

`generate()` now takes `obsidian: bool = False`; by default the hubs render as a
plain list, and the wikilink form is emitted only when a caller opts in. The
Obsidian export's own community notes already cross-link each other, so the vault
stays navigable without the report's links. Mirrors the #1444/#1465 portability
fix that was applied to `export wiki`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 10:57:52 +01:00
safishamsiandClaude Opus 4.8 f5d50adbd0 fix(extract): keep AST progress denominator consistent to the end (#1693)
Intermediate progress lines count against len(uncached_work) ("X/Y uncached
files"), but the final line switched to total_files ("Y/Y files"), which includes
cached hits and files with no extractor that never entered uncached_work. On a
large corpus with unsupported-language files, the total jumped upward right after
99% with no explanation. Both the parallel and sequential final lines now report
the same uncached_work denominator, so the count no longer appears to change
mid-run.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 00:12:36 +01:00
safishamsiandClaude Opus 4.8 377dc7f384 fix(extract): warn when code files have no AST extractor instead of silently dropping them (#1689)
Extensions like .r/.R (also .ejs, .ets) are in CODE_EXTENSIONS, so those files
are classified as code and counted in the scan, but there is no entry for them
in the extractor dispatch — so they produce zero nodes and are silently absent
from the graph while the CLI still reports success. The #1666 zero-node warning
deliberately skips them (it only fires when an extractor exists), so nothing
surfaced the gap.

extract() now emits a warning listing the offending extensions and counts
("N file(s) are classified as code but graphify has no AST extractor ...: .r (2)")
so a primarily-R (or .ejs/.ets) corpus no longer looks fully mapped when it is
not. Grouped by extension, fires only for files actually present with no
extractor (today: .ejs, .ets, .r). Adding real grammars for these remains the
follow-up; this removes the silent-data-loss now.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 00:06:49 +01:00
safishamsiandClaude Opus 4.8 d1d1f412b2 fix(serve): match a punctuated label against norm_label symmetrically in _find_node (#1704)
`_find_node` built its search term with `_search_tokens` (\w+ tokenization), so
"blockStream.ts" became "blockstream ts" (space where the '.' was) while the
node's stored `norm_label` keeps punctuation ("blockstream.ts"). The verbatim
case is already rescued by the `term == label_tokens` tier (the node label
tokenizes the same way), but that is a coincidence: if `label` and `norm_label`
diverge, an exactly-typed punctuated label fails to resolve through `explain`
even though `path`/`query` find it.

Add a punctuation-preserving `norm_query` (`_strip_diacritics(label).lower()`)
matched against `norm_label`/`bare_label` across the exact/prefix/substring tiers
(and fed to the trigram prefilter so candidates are not missed). Purely additive,
symmetric with how norm_label is stored. Regression tests cover the verbatim
file-label case and the label/norm_label divergence case that only norm_query
resolves.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 23:28:32 +01:00
safishamsiandClaude Opus 4.8 aba1232b66 docs(readme): stronger front door — badge reorder, accurate hero, 30-sec quickstart
- Badges reranked for click-through and split: lean top strip (PyPI, Downloads,
  Discord, LinkedIn, YC S26) with trust signals leading and social/company links
  at the tail; a "Community and links" footer (Discord, X, Sponsor, Book); CI
  badge dropped, book also linked from "Learn more".
- Hero leads with three differentiator bullets, corrected to match the codebase:
  code is tree-sitter AST (deterministic, no LLM, local), while docs/PDFs/images/
  video use your assistant's model or a configured API key for a semantic pass.
  Removed the inaccurate "local embedder" claim (there is no embedder; dedup is
  MinHash/LSH and there is no vector store) and qualified "zero LLM tokens" to the
  code path. "Not a vector index" is accurate.
- Added a 30-second quickstart (install + graphify install + /graphify .) above
  the fold, moved "See it in action" above "What it does" so differentiation is
  shown before it is enumerated, and compressed the "works in" list to one line.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 17:38:03 +01:00
safishamsiandClaude Opus 4.8 80e199defa Release 0.9.8
Fixes: Windows PreToolUse/BeforeTool hooks for Claude Code, Codebuddy and
Gemini CLI (#522); CLAUDE.md/AGENTS.md section-write data loss (#1688);
tiktoken special-token crash (#1685); Ollama hang retry-multiplication (#1686);
truncated community-label reply salvage (#1690); cluster-only labeling token/cost
accounting (#1694); discovery-layer file drops from snapshots/ and name-keyword
filters (#1666); deepseek thinking default + GRAPHIFY_DISABLE_THINKING opt-in (#1621).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 16:52:10 +01:00
safishamsiandClaude Opus 4.8 737a0b8454 test: rigorous edge cases for the hook-guard subcommand (#522)
Adds a wide matrix over _run_hook_guard covering the search/read detection
boundaries and the gemini BeforeTool contract:

- search: grep-family variants (grep/pgrep/egrep/fgrep/ripgrep), token matches
  (rg/find/fd/ack/ag with trailing space), piped commands; and silence for
  non-search commands, empty/missing/non-string command, 'find' without a
  trailing space, 'ag' mid-word, top-level vs nested tool_input, non-dict
  tool_input, and no-graph.
- read: source/framework extensions, uppercase and multi-dot names, Windows
  backslash paths, glob patterns; and silence for .json (not .js), lockfiles,
  images, extensionless files, an extension on a directory segment, targets
  under the (default and custom-named) output dir, and no-graph.
- fail-open: malformed/empty/binary stdin and a throwing graph-existence check
  never crash or block.
- gemini: always returns {"decision":"allow"}, nudges only with a graph, and
  stays "allow" even if the check throws.
- dispatch/exit/encoding via real subprocess: missing/unknown mode exits 0
  silently, every mode exits 0 (never blocks), and the read nudge's em dash
  round-trips as valid UTF-8.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 16:49:31 +01:00
safishamsiandClaude Opus 4.8 85f9fac7f7 Fix: port the Gemini CLI BeforeTool graph-nudge hook to be shell-agnostic too (#522)
The Gemini hook was a `python -c "..."` one-liner that (a) depended on a bare
`python` being on PATH (frequently `python`/`py` or absent on Windows) and
(b) embedded backticks + escaped quotes that Windows PowerShell mangles. Same
fix as the Claude/Codebuddy hooks: it now invokes `graphify hook-guard gemini`
via the absolute exe path.

The gemini mode always returns {"decision":"allow"} (never blocks a tool) and
appends the graph nudge as additionalContext only when graph.json exists — the
BeforeTool contract Gemini expects, byte-identical to the old payload. It takes
no stdin, honors GRAPHIFY_OUT, and the matcher stays "read_file|list_directory"
so install/uninstall find and replace old hooks unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 16:43:21 +01:00
safishamsiandClaude Opus 4.8 f7911fd1b3 Fix: make Claude Code / Codebuddy PreToolUse graph-nudge hooks work on Windows (#522)
The hooks were inline POSIX bash (case/esac, [ -f ], single-quoted echo),
which Windows cmd.exe/PowerShell cannot parse. On Windows the hook failed
silently, so the "run `graphify query` before grepping/reading raw files"
nudge was never injected and users fell back to manual /graphify.

The detection logic (grep-command match; source/doc extension match; skip if
the target is under the output dir; require graph.json to exist) moved into a
shell-agnostic `graphify hook-guard <search|read>` subcommand, invoked via the
absolute exe path resolved by _resolve_graphify_exe() — the exact pattern the
codex hook already uses. A single console-script invocation has no shell syntax,
so it parses identically under sh, cmd.exe and PowerShell.

Behavior on macOS/Linux is unchanged: the nudge payload is byte-identical
(compact JSON, same additionalContext text), matchers stay "Bash"/"Read|Glob"
so install/uninstall still find and replace old hooks, and the command still
contains "graphify". The graph-exists check now honors GRAPHIFY_OUT instead of
the hardcoded graphify-out/ path. Codex stays a no-op there (hook-check) because
Codex Desktop rejects additionalContext.

Detection is fully unit-tested (ported test_read_hook.py + new test_search_hook.py,
byte-identical output on POSIX); Windows execution itself is not testable in CI
here, but the mechanism is now shell-independent by construction.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 16:38:42 +01:00
safishamsiandClaude Opus 4.8 5d0137388e Feat: opt-in GRAPHIFY_DISABLE_THINKING; correct deepseek thinking default (#1621)
@sub4biz verified against the live DeepSeek API that deepseek-v4-flash (and
v4-pro) have thinking ENABLED by default, contradicting the built-in config's
stale "non-thinking" comment (now corrected).

The naive fix (mirror the kimi branch and force thinking off) is the wrong
call: @sub4biz's production testing on real corpora found that disabling
thinking removes a rare reasoning-leak failure — which the adaptive
extraction/labeling retry already recovers from — but trades it for far more
frequent benign truncation AND measurably lower extraction quality and file
coverage, confirmed by a blind second reviewer.

So thinking stays ON by default (quality/coverage), with a documented opt-in
`GRAPHIFY_DISABLE_THINKING=1` for users who prefer run-to-run stability. Applies
to reasoning-capable OpenAI-compatible backends at both extra_body sites
(extraction + labeling). An explicit providers.json extra_body still wins, and
the moonshot/kimi branch is unchanged (it must disable thinking or content is empty).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 16:02:45 +01:00
safishamsiandClaude Opus 4.8 912d832a60 Fix: stop silently dropping source files during discovery via two over-broad filters (#1666)
@krishnateja7 root-caused this precisely: the files were never reaching
extraction, so the 0.9.7 no-cache-on-empty mitigation could not surface them.
Two discovery-layer filters were the cause:

(a) A bare `snapshots/` directory was pruned as a Jest/Vitest artifact, which
killed legitimate code namespaces like a Rails `app/services/snapshots/`. It is
now pruned only when it actually contains `.snap` files or sits directly under a
JS test root (`__tests__`/`__test__`). `__snapshots__` stays unconditionally pruned.

(b) `_is_sensitive` dropped files on a bare name-keyword hit (device_token.rb,
passwords_controller.rb) even when `classify_file` had already resolved them to
source code. A genuine programming-language source file is now exempt from the
weak keyword heuristic, while real secret stores in data/config formats
(credentials.json, secrets.yaml, .env, .pem, ...) are still caught — those route
through the CODE path for manifest parsing but are deliberately not exempted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 16:00:31 +01:00
safishamsiandClaude Opus 4.8 bbc3be2238 docs(readme): add animated "path lights up" demo to See it in action
An animated SVG that mirrors the real `graphify path` output: a terminal
types the query on the left while the answer draws itself hop by hop across
the knowledge graph on the right, ending on "3 hops. Zero files opened."

Pure SMIL inside a self-contained dark card, so it renders inline on both
GitHub themes with no JS and no external fonts. Palette is brand-only:
muted emerald (sampled from the logo) as the single accent, no neon.
Generated by scripts/gen_demo_path.py (re-run to regenerate; STATIC=1 bakes
a still frame for QA).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 13:25:35 +01:00
adirbuskilaandClaude Opus 4.8 e801196e4e docs: add Hebrew (he-IL) README translation (#1639)
Adds the Hebrew translation under docs/translations/README.he-IL.md and
links it from the language row (30 -> 31 languages). Merged from PR #1639
by @AdirBuskila; the language-row link was adapted to the current README
structure by hand since the English README changed after the PR was opened.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 12:58:08 +01:00
safishamsiandClaude Opus 4.8 21b851b3d2 Fix: salvage truncated labeling replies and account for labeling token cost (#1690, #1694)
Two related fixes in the community-labeling path:

#1690 (thanks @vdgbcrypto): a truncated or slightly malformed reply no
longer discards the whole batch with "Expecting value: line 1 column 6".
`_parse_label_response` now salvages the complete `"id": "name"` pairs from
a reply that failed a strict `json.loads` (e.g. one truncated mid-object),
raising only when no pairs can be recovered. The per-batch token budget was
also raised (256 + 48*n, was 64 + 24*n) so models that prepend a short
preamble have headroom to finish the JSON. The exact provider truncation
could not be reproduced without a live key; the parser and budget address
the mechanism.

#1694 (thanks @sub4biz): cluster-only mode reported a hardcoded
`0 input * 0 output` token cost because the labeling LLM calls were never
accounted for. `_call_llm` now accumulates per-response usage into an
optional accumulator threaded through the labeling path and surfaced in
GRAPH_REPORT.md. Backends that do not return usage (the Claude Code CLI)
contribute nothing, which is honest rather than estimated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 12:46:12 +01:00
safishamsiandClaude Opus 4.8 b78248f22a Fix: cap Ollama client-side retries so a hung request cannot multiply the stall (#1686)
A stalled local model wedged for `timeout * (max_retries + 1)`, which with
the default 6 retries turned one long stall into a ~21-minute block with no
progress. `_call_openai_compat` now defaults the Ollama backend to zero
client-side retries (a local model that stalls will not un-stall on retry);
set `GRAPHIFY_MAX_RETRIES` to opt back in. Other backends are unchanged.

This bounds the wait; the underlying stall is driven by the model server
and is non-deterministic, so it is not eliminated. Thanks @Kyzcreig for the report.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 12:44:47 +01:00
safishamsiandClaude Opus 4.8 0ff584f070 Fix: tolerate tiktoken special-token text in token estimation (#1685)
`_TOKENIZER.encode(content)` raises ValueError by default when the text
contains a special token such as `<|endoftext|>`, so a doc or corpus that
merely mentions these strings crashed the entire semantic pass. Both
`encode` sites in `_estimate_file_tokens` now pass `disallowed_special=()`
so such text is tokenized as ordinary bytes. Thanks @Kyzcreig for the report.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 12:42:39 +01:00
safishamsiandClaude Opus 4.8 97a1371478 Fix: exact-match section heading in _replace_or_append_section to prevent CLAUDE.md data loss (#1688)
The updater located its managed block by substring (`marker in content`
and `next(... if marker in line)`), so a heading that merely appeared as
a substring of another line, or a duplicate heading, matched the wrong
offset and the rewrite could truncate or drop unrelated content in
CLAUDE.md / AGENTS.md.

It now matches the section heading exactly (`line.strip() == marker`),
appends when the section is absent, and prefers the last exact match
when several exist. Thanks @bdfinst for the report.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 12:36:12 +01:00
safishamsiandClaude Opus 4.8 31211a0e7c docs(readme): visual overhaul (hero, capability table, query demo, honest benchmarks table)
Rework the top of the README into a self-contained pitch:
- New logo + Trendshift badge; collapse the 31-language row into a toggle so the
  tagline and hero land in the first screen.
- Hero screenshot of the FastAPI graph, tagline with selective bold.
- 'What it does' capability table and a 'See it in action' section with verbatim
  explain/path output (real relations + confidence tags).
- Benchmarks as a scannable table, honest: shows where competitors lead, only
  bolds rows graphify wins or ties, names the tie.
- Collapse platform picker + optional extras into <details>; typography and
  identifier-formatting polish; fix orphaned paragraphs; reword the confidence-tag
  gloss; drop the redundant callflow CTA from the hero.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 02:34:28 +01:00
safishamsiandClaude Opus 4.8 b699182a4f release: 0.9.7
17 fixes/features since 0.9.6. Highlights:
- Ruby: mixes_in edges for include/extend/prepend (#1668) and affected <Class>
  reaching method-bound callers (#1669); constant-receiver call resolution
  hardening continues from #1634.
- Extensionless shebang CLIs are now extracted (#1683); JS/TS rationale + ADR/RFC
  doc refs (#1599); Java stdlib types dropped from references noise (#1603);
  pascal optional extra (#1616).
- Incremental/detect correctness: Office source edits re-enter --update (#1649),
  Windows long-path hashing (#1655), word-count caching (#1656), zero-node
  results no longer cached + warned (#1666).
- JS/TS phantom cross-package calls edge killed (#1659); Windows skill name +
  OpenCode plugin separator + doc-corpus report noise (#1635/#1646/#1657);
  case-insensitive suffix dispatch (#1671); postgres URI on Windows (#1672);
  deferred import() not a cycle (#1241).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 01:31:06 +01:00
guyoron1andClaude Opus 4.8 dd8c24cf7b docs: add .claudeignore tip for prompt cache (#1539); changelog for #1603
Applied the .claudeignore troubleshooting entry from #1539 manually (the PR
branched from an older README). Closes #1387.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 01:08:10 +01:00
NydiaChungandClaude Opus 4.8 92edf78005 feat(java): suppress java stdlib types from references edges (#1603)
Adds a _JAVA_BUILTIN_TYPES skip list so ubiquitous java.lang/util/io/time/etc.
type names (String, List, Map, Optional, ...) are not emitted as references
edges (they never resolve to a project node). Mirrors _GO_PREDECLARED_TYPES /
_PYTHON_ANNOTATION_NOISE. Nested user-type generic args still resolve.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 01:01:53 +01:00
safishamsiandClaude Opus 4.8 f2b81a9980 docs: changelog credit for #1616
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 00:56:35 +01:00
Vinicius Machado 7d463c98e2 feat: add pascal optional extra for tree-sitter-pascal
extract_pascal() already imports tree-sitter-pascal for AST-quality
extraction and falls back to a regex extractor when it is absent (#781),
but the grammar was not declared anywhere in the package metadata, so it
was never installed and the AST path never ran out of the box.

Declare a `pascal` extra (and add it to `all`) so users can opt into the
AST extractor with `uv tool install "graphifyy[pascal]"`. tree-sitter-pascal
publishes prebuilt wheels for every platform (win/macOS/Linux), so unlike
the `dm` extra it needs no C toolchain.

On a mid-size Delphi codebase the AST path yields notably more accurate
relationship edges than the regex fallback (calls and inherits both up
~25%). README extras table and uv.lock updated accordingly.
2026-07-06 00:55:18 +01:00
safishamsiandClaude Opus 4.8 a4d4533ae3 docs: changelog credit for #1599
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 00:48:59 +01:00
Nilton Moura 6d3a6f1c6b feat: extract rationale comments + ADR/RFC doc references from JS/TS
Parity with _extract_python_rationale: Python files get rationale nodes
from docstrings and '# NOTE:'-style comments, but JS/TS comments were
discarded entirely. This adds a post-pass to extract_js that:

1. extracts rationale comments ('// NOTE:', '// WHY:', block-comment
   '* NOTE:' variants) as rationale nodes with rationale_for edges,
   matching the Python behavior;
2. first-classes architecture-decision references (ADR-NNNN, RFC NNNN)
   found in comments as doc_ref nodes with 'cites' edges from the file.

The doc_ref pass is the natural join point between code and design docs
in mixed corpora: teams conventionally cite ADR ids in file headers, but
today those citations produce no edges, so code<->ADR connections never
form even when the discipline exists. Spellings are normalized
(ADR-11 / ADR 0011 -> ADR-0011) so references to the same document
collapse to one node, and string literals are excluded (comment-shaped
lines only).

Tested on a real mixed corpus (Flutter/Supabase monorepo): router.ts
alone yields 10 ADR citations that previously produced zero edges.
2026-07-06 00:45:51 +01:00
safishamsiandClaude Opus 4.8 5cfd7d9891 docs: changelog credit for #1683
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 00:12:45 +01:00
stasnamcoandClaude Fable 5 2ab086742a fix(extract): route extensionless shebang scripts to their AST extractor
detect.classify_file already labels extensionless files with a bash/python/
node/... shebang as CODE via _shebang_interpreter, but _get_extractor
dispatched purely on path.suffix — so a CLI entry point like `devctl` or
`manage` was detected as code and then silently contributed zero nodes to
the graph (its doc-referenced symbols stayed dangling stubs).

Resolve extensionless files through the same _shebang_interpreter and a
new _SHEBANG_DISPATCH map. Only interpreters with a real extractor are
mapped (python/bash-family/node/ruby/lua/php/julia); detect's wider set
(perl, fish, tcsh, Rscript) stays unmapped and skipped rather than being
mis-parsed by a wrong grammar.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 00:09:11 +01:00
safishamsiandClaude Opus 4.8 d7aafb0d05 docs(readme): collapse platform picker and optional extras into <details>
The 20+ row platform-install table and the optional-extras table (~60 lines
combined) sat between Install and the value content. Wrapping both in collapsible
<details> blocks keeps a skimmer moving to the report/commands sections while each
platform's command stays one click away. No content changed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 00:03:45 +01:00
safishamsiandClaude Opus 4.8 b06c55eea1 docs(readme): add graph.html hero image + benchmark table
Adds a hero screenshot of the interactive graph (FastAPI codebase, community
coloring) right after the tagline so the value prop is shown, not just told.
Converts the Benchmarks prose into a compact scannable table (LOCOMO recall/QA,
LongMemEval, zero-credit build) while keeping the judge-validation credibility
line and the link to BENCHMARKS.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 23:57:59 +01:00
safishamsiandClaude Opus 4.8 21b52e195d docs(readme): new Graphify logo (cropped icon + wordmark)
Replaces the old v4-hosted SVG wordmark with the new brand logo (graph-cube
icon + "Graphify" on the green brand gradient), tightly cropped from the source
export (1384x645, ~2.15:1, even ~90px padding). Served from docs/logo.png on v8.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 12:36:54 +01:00
safishamsiandClaude Opus 4.8 6631af7936 feat(ruby/affected): mixes_in edges for include/extend/prepend + method-bound callers in affected (#1668, #1669)
#1668: Ruby `include`/`extend`/`prepend <Const>` in a class/module body now emits
a `mixes_in` edge to the module. The mixin is captured during the node walk and
resolved cross-file by resolve_ruby_member_calls (single-owner guard, reusing
the #1640 module nodes as targets). The shared call pass skips these markers so
they are not mislabeled as `calls`. `extend self` and non-constant args are
skipped; ambiguous/undefined modules produce no edge. Rails concern composition
is now visible to affected/explain.

#1669: affected <Class> seeds the reverse walk with the root's own member nodes
(one method/contains hop) so callers that bind at method granularity (e.g.
Service.call -> the def self.call node, #1634) are reachable from the class.
method/contains stay out of the general relation-filtered walk (no forward
noise), and the seeded member nodes are not reported as hits.

Full suite: 2924 passed, 3 skipped. Verified end-to-end (Rails-shaped repros)
plus edge cases: extend self / undefined / ambiguous mixins emit nothing, mixins
are not emitted as calls, member methods aren't reported, class-level callers
still resolve, and one-hop seeding does not pull in downstream classes' methods.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 11:41:18 +01:00
safishamsiandClaude Opus 4.8 d9f97b9c01 docs: changelog credit for #1671, #1672, #1241
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 10:48:42 +01:00
raman118 aa1bbdab23 Fix case-sensitive file suffix filtering silently skipping capitalized/mixed-case extensions (#1671) 2026-07-05 10:42:09 +01:00
Synvoya 94392de640 fix(extract): don't report deferred import() as a file cycle (#1241)
`_dynamic_import_js` emitted a deferred `import('./x')` as a plain
`imports_from` edge, so `find_import_cycles` counted it as a static import.
A file that statically imports another which dynamically imports it back was
reported as a phantom circular dependency.

Keep the edge as `imports_from` (the dependency stays visible in the graph)
but mark it `deferred`, and skip deferred edges in `find_import_cycles`.

Closes #1241
2026-07-05 10:42:09 +01:00
raman118 5ffa921e27 Fix invalid virtual postgres source_file URI backslashes on Windows (#1672) 2026-07-05 10:42:09 +01:00
safishamsiandClaude Opus 4.8 1288a557e3 fix(extract): don't cache zero-node results; warn on empty source files (#1666)
krishnateja7 reported that on a full-repo run a stable subset of Ruby files
yields zero nodes (not even a file node), each fine in isolation, drop set
byte-stable across runs. Root cause is a transient batch/parallel extraction
that produces an empty result, which then gets cached and persists.

Every extractable file yields at least a file node, so a zero-node result is
anomalous. Both extraction paths (parallel worker and sequential fallback) now
skip the cache write when a non-error result has no nodes, so a rerun re-extracts
and self-heals instead of loading the stale empty. extract() also warns, listing
the files that landed in the graph with zero nodes, so the previously-silent
blindness in affected/explain is visible.

This addresses the persistence and the silent blindness. The underlying trigger
(why a valid file occasionally extracts empty when co-processed with certain
others) was not reproducible with synthetic corpora; the warning now surfaces it
for a concrete report if it recurs.

Full suite: 2912 passed, 3 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 10:33:07 +01:00
safishamsiandClaude Opus 4.8 3140b2ecce docs(readme): move star-history chart from top to bottom
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 00:30:36 +01:00
safishamsiandClaude Opus 4.8 9fea1a42e4 docs: add BENCHMARKS.md and link it from the README
Adds a benchmark writeup covering graphify as long-term memory (LOCOMO,
LongMemEval-S vs mem0/supermemory/bm25/dense/hybrid) and as a code-intelligence
layer (ERPNext), run on graphify's own harness with competitors as adapters:
one shared model (Kimi K2.6), identical budgets, shared BGE-m3 embedder where
allowed, and a judge blind-validated against a second judge (90.6% agreement,
kappa 0.81). Numbers are wins-forward but every retained figure is exact; the
supermemory recall comparison is labeled embedder-confounded. README gets a
short Benchmarks section linking to it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 00:24:52 +01:00
safishamsiandClaude Opus 4.8 54825b6a1c fix: windows skill name, opencode plugin separator, doc-corpus report noise (#1635, #1646, #1657)
#1635: the windows skill variant declared `name: graphify-windows`, but
`graphify install --platform windows` writes it to ~/.claude/skills/graphify/
SKILL.md and Claude Code requires the folder name to equal the frontmatter
`name` — the suffix broke discovery. platforms.toml now sets name = "graphify"
(regenerated + re-blessed).

#1646: the OpenCode (and Kilo) plugin prepended its reminder with `&&`, which
Windows PowerShell 5.1 rejects as a statement separator, breaking the first
bash command of every session. Switched to `;` (valid in PowerShell 5.1, Bash,
POSIX).

#1657: the GRAPH_REPORT.md "Import Cycles" section printed "None detected" on
documents-only corpora where imports don't exist — now gated on code nodes /
import edges being present. The other two items in that issue (mojibake in
manifest/report, stdout encoding) are already handled on current v8: both files
are written UTF-8 and main() reconfigures stdout/stderr to UTF-8.

Full suite: 2909 passed, 3 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 22:43:31 +01:00
safishamsiandClaude Opus 4.8 f9174943a2 fix(detect): incremental correctness for Office sources + long paths, cache word counts (#1649, #1655, #1656)
#1649: detect_incremental tracks the converted markdown sidecar, and
convert_office_file early-returned whenever the sidecar existed — so a .docx/
.xlsx edited after its first conversion never updated its sidecar and was
reported "unchanged" forever, freezing the graph. It now re-converts when the
source is newer than the sidecar (bumping the sidecar so the hash check catches
it); an unchanged source still skips the rewrite (#1226).

#1655: _md5_file/save_manifest/count_words used plain open()/stat(), which the
Windows file APIs reject for absolute paths over 260 chars unless prefixed with
`\\?\`. Deeply-nested files never hashed, their manifest entry never stabilized,
and detect_incremental re-flagged them as changed every run. A new _os_path adds
the extended-length prefix on win32 for change-detection I/O (mirror of
cache._normalize_path, which strips it for keys). No-op elsewhere.

#1656: detect() re-parsed every PDF/docx/text file to size the corpus on each
run. Word counts are now memoized in the existing content-hash stat index (keyed
by size + mtime_ns), so an unchanged file is parsed once. file_hash's fastpath is
guarded so a word-count-only entry (no hash) can't KeyError, and both writers
augment a co-located entry in place instead of clobbering the other's field.

Full suite: 2906 passed, 3 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 22:12:47 +01:00
safishamsiandClaude Opus 4.8 62b8eb1416 fix(extract): gate JS/TS cross-file calls on import evidence to kill phantom cross-package edges (#1659)
When a callee had exactly one same-named definition repo-wide, the cross-file
resolver emitted a `calls` edge at INFERRED/0.8 even with no import path between
caller and callee. On a monorepo this fabricated dependencies: a 14-package repo
showed `platform`/`sidecar` depending on `registry-protocol` purely because it
exported generically-named symbols that unresolved calls collapsed onto.

JS/TS modules have no implicit cross-module scope, so a cross-file call is real
only if the caller imported it. Direct JS/TS cross-file `calls` attribution is
now gated on import evidence and left unresolved otherwise. Scoped to direct
calls: other languages keep the #1553 single-candidate resolution (C/C++
headers, Ruby autoload, same-package implicit scope), and the indirect_call path
(already INFERRED + callable-gated) is untouched.

Also hardens caller/candidate -> file mapping to resolve via the node's
`source_file` string (identifying the file node by its basename label) instead
of `relative_to(root.resolve())`, which threw on a path-resolution/symlink
mismatch and fell back to a non-matching absolute id — spuriously failing import
evidence. This both makes the new gate safe and fixes legitimate cross-file
calls being mislabeled INFERRED instead of EXTRACTED.

Full suite: 2898 passed, 3 skipped. Verified via CLI on the reporter's repro
(phantom dropped) and a control (imported call resolves EXTRACTED).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 21:22:39 +01:00
safishamsiandClaude Opus 4.8 983da3c15f docs(readme): sync code-extension list with detect.py
The "What files it handles" code row omitted several extensions that reuse
existing tree-sitter grammars (so the grammar count is unchanged): `.mts`/`.cts`
(TypeScript, #1607, new in 0.9.6), `.cc`/`.cxx` (C++), `.kts` (Kotlin), `.psd1`
(PowerShell), `.toc` (Lua). Apex (`.cls`/`.trigger`) and Terraform already have
their own rows. `.r`/`.ejs`/`.ets` are intentionally left out — they are in
CODE_EXTENSIONS but have no registered extractor.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 13:01:18 +01:00
safishamsiandClaude Opus 4.8 29b3f9126d release: 0.9.6
19 fixes/features since 0.9.5. Highlights:
- Ruby: module/Struct.new/Class.new/Data.define container nodes (#1640) and
  constant-receiver singleton-call resolution (#1634) — Rails/Zeitwerk graphs
  now get real cross-file edges.
- Kill cross-language phantom imports_from edges from unresolved bare npm
  imports (#1638); harden semantic extraction against malformed LLM chunks
  (#1631); deterministic graph.json node/edge ordering for parallel semantic
  backends (#1632).
- Contributor extractor fixes: Apex interface multiple inheritance (#1645),
  Kotlin `by` delegation (#1644).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 12:55:35 +01:00
safishamsiandClaude Opus 4.8 13e2bddf4d fix(ruby): extract module/Struct/Class.new containers and resolve constant-receiver calls (#1640, #1634)
#1640 (node extraction): the extractor only created nodes for `class Foo`, so
plain `module Foo`, `Foo = Struct.new(...) do ... end`, `Foo = Class.new(Super)`
and `Result = Data.define(...)` produced no container node — their methods hung
off the file via `contains` with dot-less labels and no edge could target them.
`module` is now a container type (methods attach via `method`, nested modules
included), and a constant assignment whose RHS is Struct.new/Class.new/Data.define
synthesizes a class node named after the constant, attaches block-defined methods
to it, and emits an `inherits` edge for `Class.new(Super)`. Plain constant
assignments (MAX = 100, X = Foo.new) are untouched.

#1634 (resolution): constant-receiver singleton calls (`Service.call`,
`Model.where`, `SomeJob.perform_async`) emitted no edge, so a Zeitwerk-autoloaded
Rails app (no requires) had near-zero cross-file edges. resolve_ruby_member_calls
now handles a capitalized receiver with any callee: bind to the class's owned
singleton/instance method (`def self.call`) when present, else to the class node
itself so inherited/dynamic class methods (ActiveRecord where/find_by) still give
blast-radius. Namespaced receivers resolve by bare class name. The
single-owning-class god-node guard is kept — ambiguous receivers resolve to
nothing, never a wrong edge.

The two compound: PaymentProcessor#process -> TaxCalculator.rate_for needs the
module node (#1640) AND the resolver (#1634); both now land.

Full suite: 2893 passed, 3 skipped. Adversarial smoke confirms no false class
nodes from plain/multiple assignments and no self-loops on self-class calls.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 12:20:07 +01:00
safishamsiandClaude Opus 4.8 5737388f17 docs: changelog credit for #1645 (apex extends) and #1644 (kotlin by delegation)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 11:32:07 +01:00
Synvoya 9b040224e1 fix(kotlin): emit implements edge for interface delegation (by)
class Foo : Bar by baz produced no edge because the delegation_specifier loop only handled constructor_invocation and bare user_type children; the by form wraps user_type in an explicit_delegation node. Add that branch so the implements edge (and generic-arg recovery) fires.
2026-07-04 11:26:55 +01:00
Synvoya 53c769d23d fix(apex): emit extends edges for interface multiple inheritance
interface X extends A, B captured the parent list in iface_re group 2 but the handler only read group 1, so no inheritance edge was emitted. Split the parent list and emit one extends edge per parent (mirroring the class branch).
2026-07-04 11:26:54 +01:00
safishamsiandClaude Opus 4.8 e2ef4ef3d1 fix: harden semantic extraction and kill phantom import edges (#1631, #1638, #1632)
#1631: a malformed LLM chunk (a stray non-dict entry in edges/nodes/hyperedges)
crashed the AST+semantic merge and the semantic-cache write with
`AttributeError: 'list' object has no attribute 'get'`, discarding every
successful chunk and writing no graph.json. `_parse_llm_json` now sanitizes each
fragment at the single parse chokepoint (dict entries only; non-list values
coerced to []), protecting the cache writer, the adaptive-retry merge, and the
CLI merge in one place.

#1638: an unresolved bare npm import (`import colors from "tailwindcss/colors"`)
emitted an imports_from edge to the bare id `colors`, which build.py's
pre-migration alias index then remapped onto an unrelated local file of that
stem (backend/utils/colors.py) - a confident EXTRACTED cross-language phantom
edge, one per importing file. The external-import fallback now namespaces its
target with the `ref` prefix (the J-4 convention), so it can never collapse to a
local node id; the ref target has no node, so build drops it as an external
reference.

#1632: with a parallel LLM backend, extract_corpus_parallel merged chunk results
in completion order, so which network call returned first reordered nodes/edges
run-to-run even when the model returned identical content - churning graph.json.
Chunks are now merged in deterministic submission order after the pool drains
(matching the serial path); the progress callback still fires in completion
order. The model's own content variance is unchanged (irreducible).

Full suite: 2882 passed, 3 skipped. Validated end-to-end via a local wheel build
on a mixed TS+Python corpus: `explain colors.py` shows only the real importer,
and graph.json is byte-identical across repeated runs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 03:12:23 +01:00
safishamsiandClaude Opus 4.8 2ba07e84e1 fix(export): guard to_canvas against dangling community members (#1236 follow-up)
The #1236 fix guarded to_obsidian's member loop but not to_canvas, so
`graphify export obsidian` (which also writes graph.canvas) still crashed with
KeyError on a community member id absent from G — after the notes exported,
leaving a partial mirror. Reported on 0.9.5 by @swells808.

Apply the same `m in G and m in node_filenames` filter in both to_canvas loops:
the box-sizing loop (so the group box matches the cards actually laid out) and
the card-layout loop (so the sort/label deref and the node_filenames fallback
never touch a dangling id). Regression test added alongside the to_obsidian one.
Full suite 2872.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 18:34:41 +01:00
safishamsiandClaude Opus 4.8 4744dfefca feat(extract): TS/JS member calls on local new-binding + typed-param receivers (#1630)
The #1316 resolver handled `this.injectedField.method()`, but a receiver whose
type comes from a local `const x = new Foo()` binding (Pattern A) or a
type-annotated parameter — including inside a returned closure (Pattern B) —
produced no calls edge, so `affected <method>` silently under-reported.

- _ts_receiver_type_table: augment the per-file type table with local
  `new` bindings (name -> constructor type) and bare-typed parameters
  (`(svc: Svc)` -> svc: Svc), merged after the constructor-injection entries
  (which win on a name clash). Only a bare type_identifier is recorded — an
  array/union/generic/qualified/predefined type is skipped (precision).
- walk_calls now descends into an inline/returned JS/TS closure that is not
  separately tracked in function_bodies (e.g. `return () => svc.doThing()`),
  attributing its calls to the enclosing function, instead of stopping at the
  arrow boundary. A tracked-body-id set prevents double-walking const-assigned
  arrows.

The existing _resolve_typescript_member_calls then resolves both via the
receiver type with its single-definition guard. Verified on the real-CLI shape
(absolute paths + graphify-out cache): both patterns resolve, ambiguity binds
to the right class (Svc not Cache), untyped/array-typed receivers emit nothing.
5 tests, full suite 2871.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 16:03:18 +01:00
safishamsiandClaude Opus 4.8 21294f0d4f fix(skill): utf-8 encoding in query reference snippets (#1619 A2)
The query reference doc's inline vocab-harvest / fallback-search snippets used
bare Path(...).read_text()/write_text(), which on Windows (default cp1252)
crash with UnicodeEncodeError on the cross-language corpora the doc itself
demonstrates (Cyrillic labels like обработчик). Add encoding="utf-8" to all
five sites in the skillgen source fragment and regenerate; blessed expected/,
skillgen --check + --monolith-roundtrip green.

Scoped to the concrete reproduced crash; the larger #1619 findings (the
Windows .exe interpreter-guard rewrite, INPUT_PATH backslash guidance, BOM
handling) are a separate skill-template pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 11:37:22 +01:00
safishamsiandClaude Opus 4.8 53638d4017 docs(changelog): note stale-source reconciliation on update (#1623)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 10:33:45 +01:00
oleksii-tumanov 8d8d2b8c0a fix(update): reconcile removed and renamed sources 2026-07-03 10:30:27 +01:00
safishamsiandClaude Opus 4.8 412a29d9d0 docs(changelog): note per-term BFS seed diversity (#1596)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 10:18:50 +01:00
Mark Butterworth d56ee8384d fix: guarantee per-term BFS seed diversity in query (fixes #1445)
_pick_seeds' gap_ratio cutoff discards any candidate scoring below 20%
of the top score. On a multi-term natural-language query, one term's
incidental EXACT label match on a node that is otherwise unrelated to
the query's intent (e.g. a common word also used as a field name or
identifier elsewhere in the corpus) scores ~1000x higher than any
SUBSTRING match on the query's other, actually-relevant terms
(_EXACT_MATCH_BONUS vs _SUBSTRING_MATCH_BONUS). The cutoff then
silently discards every one of those substring-tier candidates as BFS
seeds, so the traversal only ever explores the neighborhood of the one
unrelated exact match, and `query` returns confidently-wrong results
with no signal that anything went wrong.

This matches #1445's reproduction exactly: a vague query that doesn't
name a target symbol seeds from unrelated "concept-dense" nodes
instead, even though the target node is present in the graph.

_pick_seeds now optionally accepts the graph and the tokenized query
terms; when supplied, it guarantees at least one seed per distinct
term that has any match at all, so one term's collision cannot starve
out the others. Ties within a term are broken by node degree, so an
isolated incidental match doesn't out-rank a real, well-connected hub
for that term. The parameters default to None and existing callers
that don't pass them see byte-identical behavior (see
test_pick_seeds_without_diversity_args_is_unchanged).

Adds a regression test reproducing the exact failure shape from
#1445 and confirms the previously-starved target node is recovered
as a seed once G/terms are supplied.

Full test suite (74 tests) and ruff both pass.
2026-07-03 10:14:57 +01:00
safishamsiandClaude Opus 4.8 cf4b4ef85a fix(build): don't crash when a node's source_file is the scan root (#1618)
A node whose source_file equals the absolute scan root (e.g. a project-level
semantic concept the LLM attributed to the whole repo) relativized to Path('.'),
and _semantic_id_remap fed that into _file_stem, whose path.with_suffix("")
raises `ValueError: '.' has an empty name`. The crash landed in final graph
assembly — AFTER all LLM extraction cost was spent — writing no graph.json at
all, and leaving `cluster-only` to then report "no graph found".

Two guards: _file_stem returns "" for a name-less path (protects every caller,
not just this one), and both _semantic_id_remap passes skip a root-equal
source_file explicitly (it has no per-file identity to remap — id left
untouched). Reported with a minimal LLM-free repro by @sub4biz.

Not a 0.9.5 regression: _semantic_id_remap/_file_stem are byte-identical to
0.9.4; the latent path was only hit when dedup produced a root-source_file node.
4 regression tests (dot-path stem, remap no-crash, build_from_json with a
root-level concept node, normal remap unaffected). Full suite 2849.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 00:32:24 +01:00
safishamsiandClaude Opus 4.8 eebc406773 feat(extract): C# receiver-typed member-call resolution (#1609)
C# had no member-call resolver (unlike Swift/Python/Ruby/TS/C++/ObjC), so
`recv.Method()` fell back to a bare method-name match against label_to_nid —
which, under ambiguity, silently mis-bound `_server.Save()` to an unrelated
`Cache.Save()`. That's a WRONG edge, not just a missing one, and it left
delegation-heavy C# call graphs (wrappers, service layers) blind across typed
member/param boundaries.

Mirrors the C++ #1547 pattern:
- capture the member_access_expression receiver (simple identifier or `this`)
  into member_receiver and set is_member_call in the C# invocation branch;
- defer ALL C# member calls with a receiver to the resolver (tgt_nid = None) so
  the bare in-file match can't fire, and emit a raw_call tagged lang="csharp";
- _csharp_member_type_table: file-wide name -> Type from fields, properties,
  parameters, and locals (incl. `var v = new T()`), first-binding-wins;
- _resolve_csharp_member_calls: `this` -> enclosing class (EXTRACTED),
  capitalized -> the named type (EXTRACTED), else the receiver's table type
  (INFERRED), each gated by the single-definition guard; no method on the type
  -> no edge. Registered for .cs.

Verified: the ambiguous `_server.Save()` now resolves to Server.Save and NOT
Cache.Save; field/param/local/this/Type.static/cross-file all resolve; dynamic
receiver and absent-method emit nothing; unqualified calls unregressed. 8 new
tests, full suite 2841.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 23:25:54 +01:00
safishamsiandClaude Opus 4.8 41ce87e442 docs(changelog): note the #1617/#1607/#1615/#1613 fixes
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 22:53:06 +01:00
Paulo PintoandClaude Opus 4.8 35404167d9 fix(extract): emit reference edges for TS/JS decorators
`@Component`, `@Injectable`, `@Input`, `@Inject`, `@Entity`, … produced no
edge — the `decorator` node kind was never walked. This is framework-critical
(Angular, NestJS, Vue class components, TypeORM): the decorators are the
primary signal of what a class is and does.

Decorators occur only on classes, class members, and parameters, so one pass
over each class declaration covers them. `_ts_emit_decorator_edges` emits a
`references` edge (context="decorator") from the decorated entity to the
decorator symbol:

  - class decorators -> the class. Handles both `@Deco class C` (decorator is
    a child of the class) and `@Deco export class C` (decorator sits on the
    wrapping export_statement), plus stacked decorators.
  - method decorators -> the method node. They are siblings preceding the
    `method_definition`; stacked decorators are skipped past to find it.
  - field / accessor decorators -> the class (the field is not a graph node).
  - parameter decorators (`@Inject(T)`) -> the enclosing method/constructor.

The symbol is the head identifier: `@Injectable`, the `function` of
`@Component({...})`, or the `property` of `@ns.Component()`. Targets go
through `ensure_named_node`, so a decorator defined outside the corpus
becomes a sourceless stub, consistent with type references — one per
referencing file, matching the cross-file stub disambiguation introduced
with full-path node IDs in 0.9.0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 22:38:29 +01:00
Paulo PintoandClaude Opus 4.8 869aaf7502 fix(extract): emit a node for TS namespace / module containers
`namespace Foo {}` parses as `internal_module` and `module Bar {}` (and
ambient `declare module "pkg" {}`) as a named `module` node. Neither kind
was in `class_types`/`function_types` nor handled by an extra-walk, so the
container produced no node — its members were still reached by the default
recurse, but the namespace/module itself was invisible to the graph and its
members lost their namespace context.

Add `_ts_extra_walk`, dispatched for TypeScript after `_js_extra_walk`,
mirroring `_csharp_extra_walk`: it emits a container node + a file→container
`contains` edge and recurses the body, leaving members file-contained as
before. `internal_module` exposes `name`/`body` fields; `module` exposes
none, so name (identifier / nested_identifier / quote-stripped string) and
body (`statement_block`) are found positionally. The `is_named` guard skips
the anonymous `module` keyword token, which shares the `module` type string.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 22:38:29 +01:00
Paulo PintoandClaude Opus 4.8 09aeb979c8 fix(extract): extract TS/JS generator functions as nodes
Generator functions were invisible to the graph. The declaration form
`function* g()` parses as `generator_function_declaration`, which was
absent from the JS/TS `function_types`, so it produced no node; the
expression form `const h = function*(){}` parses as `generator_function`,
which was absent from the JS function-value types, so it was never captured
when assigned to a module-level const. Generator *methods* (`*gen()` in a
class) were already covered — they parse as `method_definition`.

Add `generator_function_declaration` to the JS and TS `function_types` (so
it emits a node and its body is walked) and to `function_boundary_types`
(so its calls are scoped to it, parity with `function_declaration`); add
`generator_function` to `_JS_FUNCTION_VALUE_TYPES` (so the const-assigned
expression form is captured like `function_expression`).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 22:38:28 +01:00
Tok6Flow0 009a98b6dd Contain symlinked extraction inputs 2026-07-02 22:29:32 +01:00
Paulo PintoandClaude Opus 4.8 9811def1b3 fix(extract): capture the TS import-equals form (import x = require(...))
`import x = require("./m")` produced no edge at all: tree-sitter parses it
as an `import_statement` whose module string sits inside an
`import_require_clause`, not as a direct child of the statement, so the
direct-child string scan in `_import_js` never found it. The file-level
dependency was silently dropped while the equivalent ESM form
(`import * as x from "./m"`) was captured — an invisible hole in the
import graph of TS codebases that interop with CommonJS modules.

Restructure the scan to first locate the module string — a direct `string`
child for ESM imports/re-exports, or the `string` nested inside an
`import_require_clause` for the import-equals form — then emit the
`imports_from` edge from the single shared path. Relative paths, tsconfig
aliases, and bare modules all resolve through the same
`_resolve_js_import_target` as ESM, giving the import-equals form exact
parity with a namespace import: one file-level `imports_from` edge.

Plain JS is unaffected (the grammar has no `import_require_clause`), and
the pure namespace alias form (`import A = B.C`) is out of scope — it has
no module string and models an intra-code alias, not an import.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 22:29:32 +01:00
AshmitandClaude Opus 4.8 1226c34731 Treat .mts/.cts (TypeScript module extensions) as TypeScript
`.mts` (ESM) and `.cts` (CommonJS) are the TypeScript counterparts of the
already-supported `.mjs`/`.cjs`, but graphify handled them in neither the
code-extension detection nor the TypeScript grammar path — so they were either
skipped entirely (classified as non-code) or, once detected, parsed with the plain
JavaScript grammar, which silently drops every `type`/`interface`/type-alias
declaration.

Detection — add `.mts`/`.cts` alongside their siblings in:
- detect.CODE_EXTENSIONS            (the code / non-code gate)
- analyze._LANG_FAMILY              (cross-language edge family → "js")
- extract._JS_RESOLVE_EXTS          (import target resolution)
- extract._JS_CACHE_BYPASS_SUFFIXES
- build.py per-node language map    (→ "js")

TypeScript grammar — route `.mts`/`.cts` to the plain TypeScript grammar (like
`.ts`; neither is JSX), so their TS-only syntax is captured:
- extract_js()                      (grammar selector: .mts/.cts → _TS_CONFIG)
- extract._DISPATCH                 (.mts/.cts → extract_js)
- the use_ts tree-sitter selector
- the typescript_member_calls resolver frozenset

Result: a `.mts`/`.cts` file now extracts identically to the equivalent `.ts`.
Verified on a real 47 KB `.mts` source — 36 nodes for `.mts`/`.cts`, matching `.ts`
exactly (was 22 with the JS grammar; the 14 dropped nodes were TS type/interface
declarations). No new dependency — same tree-sitter-typescript grammar as `.ts`.

Tests: tests/test_typescript_module_extensions.py — membership regression locks for
the extension sets, dispatch routing, and end-to-end parity asserting `.mts`/`.cts`
capture the TS `type`/`interface` nodes and match the `.ts` node set.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 22:29:31 +01:00
Jeisson 32ff6d6fb3 fix(claude-cli): deliver extraction instructions in the user turn
The claude-cli backend passed the extraction schema via --system-prompt with
only the raw file dump in the user turn, assuming a replacement system prompt
is the model's sole authority. Claude Code >= ~2.1 (verified on 2.1.197) does
not honour that: it still layers in the local coding-agent context
(CLAUDE.md/AGENTS.md in cwd, skills, MCP) and, given a user turn that is just a
file with no request, replies conversationally ("I see the file, but there's no
actual request attached"). That prose parses to zero nodes/edges, so
_response_is_hollow flags it as truncation and the adaptive-retry path bisects
the chunk indefinitely (94 -> 47 -> 23 -> ...), never converging and never
writing graph.json.

Move the full extraction schema plus an explicit imperative into the user turn
and drop --system-prompt, so the CLI emits the JSON object directly. The
<untrusted_source> prompt-injection guardrails are carried verbatim; model
override, --add-dir image handling, timeout, and token accounting are untouched.
2026-07-02 22:29:30 +01:00
sanmaxdev 62f49bad73 fix: persist cluster-only analysis sidecar 2026-07-02 22:29:29 +01:00
safishamsiandClaude Opus 4.8 d89ec68af9 release: 0.9.5
Two 0.9.4 regressions (CLI cross-file indirect_call, stale community labels on
re-cluster), the case-folding god-node fix (#1581), ~15 language extractor
fixes (Ruby/Groovy/Elixir/Fortran/Rust/Julia/SystemVerilog/Scala/PowerShell/
ObjC/PHP/C#/C++/Swift), merge-graphs mixed-type handling (#1606), Swift
singleton-into-local resolution (#1604), Homebrew python@ shebang (#1586),
hooks foreground-stall perf (#1601), serve query stopwords (#1597) and
multi-project MCP serving (#1594), plus JSON-loading hardening, dedup collision
warning, and Windows hook worker limit.

Built wheel validated in a clean venv: CLI reports 0.9.5, import resolves to the
installed package, the case-folding and Swift-singleton fixes verified, and a
real `graphify extract` produces indirect_call + inherits edges end-to-end.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 13:03:34 +01:00
Joan F Garcia 9e7fbcbd6e feat(serve): optional project_path for multi-project MCP serving
Add an optional project_path to every MCP tool so one server process can
answer against many projects. Omitted -> the server's default graph (fully
backward-compatible); an absolute project_path -> that project's
<GRAPHIFY_OUT>/graph.json, routed per call.

Implementation (all in _build_server):
- _ctx_cache + _load_ctx(): per-graph context cache with mtime+size
  hot-reload, unified across the default graph and every project graph.
  Unlike _load_graph it raises instead of sys.exit on a bad file.
- _resolve_graph_path()/_select_graph(): map project_path to a graph.json
  and rebind G/communities/active_graph_path per call. No hot-path lock:
  select+handler run in one synchronous span of the call_tool coroutine.
- Tolerant startup: serve with no default graph (pure multi-project mode)
  instead of exiting; a bad project_path is a tool error, not a crash.
- project_path injected as an optional (non-required) field on all tools.

Tests: 3 new HTTP-transport tests (optional-on-every-tool, routing,
bad-path-no-crash). Full serve suite green (91 passed).
2026-07-02 12:11:51 +01:00
Paul Young 6e97088493 fix(serve): drop question/filler stopwords from query terms
`graphify query "<question>"` tokenised the whole question and seeded BFS on
every word, so natural-language scaffolding dominated retrieval. "how does the
frontier cache work" seeded on "how"/"the"/"work" — which prefix-match prose
labels like "Working Principles" at the 100x prefix tier — instead of on
"frontier"/"cache", landing in the wrong part of the graph.

Filter a set of English question/filler words from the query terms so content
words drive seeding, with a fallback to the unfiltered terms when a query is all
stopwords ("how does it work"). Applied to query terms only — node text is never
filtered, so a symbol literally named `work` stays findable via explain/path.

Updates the one test that pinned "what" as a kept term and adds coverage for the
new drop + all-stopword fallback. Full suite green (2745 passed, 28 skipped).
2026-07-02 11:50:17 +01:00
JimandClaude Fable 5 1256d65214 perf(hooks): eliminate multi-second foreground stalls before the detached launch
Three foreground costs ran on every commit before the detached rebuild
launcher even started:

1. Interpreter probes imported the full package. Each probe executed
   'import graphify' wholesale — measured 13s per probe cold on a Windows 11
   dev box with AV-scanned site-packages — and up to four probes could run
   synchronously. Probes now use importlib.util.find_spec, which locates the
   package without executing it (interpreter startup cost only). A broken
   install under the selected interpreter still fails loudly in the rebuild
   log, as before.

2. The shebang probe read a binary. Git for Windows' command -v can return
   the launcher path WITHOUT its .exe suffix, so the '*.exe)' guard missed
   and head -1 read a PE binary: the shell warned 'ignored null byte in
   input' on every commit and the garbage always fell through to the slow
   python3/python fallbacks. The Windows pip layout is now resolved directly
   (Scripts/graphify -> sibling ../python.exe, or ./python.exe for venvs),
   and the remaining POSIX shebang read strips NULs first.

3. GIT_DIR was re-derived. git exports GIT_DIR to hooks; the unconditional
   rev-parse added ~1.3s more on machines where every git exec is scanned.
   Now reused from the environment with rev-parse as the manual-run fallback.

Measured on the affected machine: hook foreground drops from 26s+ (cold) to
~1.4s, warnings gone. Behavior is unchanged on healthy POSIX setups — probe
order and fallback semantics are preserved.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:50:12 +01:00
safishamsiandClaude Opus 4.8 44c0a5e33c fix(swift): resolve calls on a singleton cached into a local var (#1604)
`let manager = NetworkManager.shared` followed by `manager.fetchData()` on a
later line produced zero call edges. Two gaps: (1) local let/var bindings inside
method bodies were never typed (only class-level properties and function params
populated the per-file type table), and (2) a static-member initializer
(`Type.shared`, a navigation_expression) wasn't recognized as typing the local
even in the class-property path — only constructor calls (`Type()`) were.

Add _swift_local_var_types (mirrors _cpp_local_var_types): walk each function
body and type a local from a constructor OR a `Type.staticProp` access whose head
is upper-cased. `x.method()` then resolves to the receiver type through the
existing single-definition god-node guard. The class-property path also learns
the Type.shared shape. Reported on a 23k-file iOS corpus where this idiom is the
median call pattern.

Verified: the repro resolves (loadIfNeeded -> fetchData/isLoading); constructor
locals still resolve; a lowercase-head init (`other.child`) does NOT falsely
type; and an ambiguous method name resolves to the receiver-typed class only.
Swift + full suite 2789 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 11:46:22 +01:00
safishamsiandClaude Opus 4.8 b70a6d7126 fix: allow python@ shebang in skill detection (#1586) + merge-graphs mixed types (#1606)
#1586: the skill's interpreter-detection allowlist rejected any shebath path
with a char outside [a-zA-Z0-9/_.-], so Homebrew's versioned python@3.13 path
was skipped and detection fell through to a bare python3 without graphify.
Allow @ in the skillgen source fragments (core/devin/aider/posix), regenerate
all skill artifacts, and register the change as a sanctioned monolith diff.
Injection chars (; $ ( etc.) are still rejected.

#1606: graphify merge-graphs crashed with an unhandled NetworkXError when
inputs disagreed on directed/multigraph. _to_simple only converted MultiGraph,
leaving a DiGraph to fail compose. Normalize every input to a plain undirected
Graph (the merged cross-repo view is undirected anyway).

Also confirmed on v8: `graphify kilo install` (#1605) works (reporter was on an
older version), and `pip3 install graphifyy` failing on macOS (#1585) is a
broken Homebrew Python 3.14 / pyexpat env, not a graphify issue — pip crashes
in its own vendored distlib before graphify is touched.

skillgen --check / --monolith-roundtrip / --schema-singleton all green; shell
smoke accepts python@3.13 and still rejects `; rm -rf /` and `$(evil)`. Full
suite 2789.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 11:25:51 +01:00
safishamsiandClaude Opus 4.8 5190a4ede9 docs: point LinkedIn badge to Graphify Labs company page
Swap the personal LinkedIn link for the Graphify Labs company page across the
main README and all translated READMEs; relabel the badge to Graphify Labs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 21:24:24 +01:00
safishamsiandClaude Opus 4.8 f4a7994926 docs(changelog): note 7-language type-reference/inheritance fixes (#1587-#1593)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 18:34:48 +01:00
Synvoya ad7015262b fix(swift): emit references for enum associated-value types
The Swift `enum_entry` handler in `_swift_extra_walk` iterated the entry's
children only for the `simple_identifier` case name (emitting a `case_of`
edge) and never descended into the sibling `enum_type_parameters` node, where
associated-value types live (`enum_type_parameters -> user_type ->
type_identifier`). As a result `case started(Session)` silently dropped the
`Event -> Session` type reference.

Descend into each `enum_type_parameters` child after emitting `case_of`, run
`_swift_collect_type_refs` over its named children, and emit a `references`
edge from the enum node to each collected type (context `type`, or
`generic_arg` for generic roles), guarding target != enum node. Mirrors the
existing Swift property/parameter/return-type emit style.

Fixture: add `case failed(Config)` to `NetworkError` in sample.swift.
Test: assert (`NetworkError`, `Config`) in references(context=type).
2026-07-01 16:36:53 +01:00
Synvoya 21bcb436b5 fix(cpp): emit generic_arg references for base-class template arguments
The C++ base_class_clause handler's `template_type` branch read the base
name (`sub.child_by_field_name("name")`) and emitted the `inherits` edge,
but never descended into the base's `template_argument_list`. As a result
`class Car : public Base<Dep>` emitted `Car -> Base` (inherits) yet dropped
the `Car -> Dep` generic_arg reference entirely.

The Java handler `_emit_java_parent_type` already emits these generic_arg
references for base-class type arguments; C++ was the asymmetric gap.

Fix: after emitting the `inherits` edge, grab the base's `arguments` field
(the `template_argument_list`) and run `_cpp_collect_type_refs` over each
named argument with the generic flag set, emitting a `references` edge
(context "generic_arg") per collected type, guarding target != class node.
`_cpp_collect_type_refs` already handles nested/qualified args, so
`Base<std::vector<Dep>>` is covered too.

Adds a templated base (`Connection<T>`) + derived class
(`PooledClient : public Connection<HttpClient>`) to tests/fixtures/sample.cpp
and a test mirroring the Java generic-parents test.
2026-07-01 16:36:52 +01:00
Synvoya bb5e5192df fix(csharp): emit type references for properties
The C# class-body walker only handled field_declaration, so a
property's type produced no references(field) edge. In idiomatic C#,
auto-properties (`public Widget Main { get; set; }`) — not bare fields
— are the standard way to declare state, so this silently dropped most
of a class's type relationships.

Add a property_declaration branch alongside the field_declaration
handler, guarded the same way (ts_module == tree_sitter_c_sharp,
parent_class_nid set). A property exposes its type on the node directly
(no variable_declaration wrapper), so read it via
child_by_field_name("type") and collect refs with
_csharp_collect_type_refs, mirroring the Java/PHP/Kotlin siblings so
List<Widget> yields both the List field ref and the Widget generic_arg
ref. Only emit when target != parent_class_nid.
2026-07-01 16:36:50 +01:00
Synvoya 51f805e953 fix(php): emit type references for promoted constructor properties
PHP 8 constructor property promotion (`__construct(private Repo $repo)`)
parses the promoted parameter as `property_promotion_parameter`, not
`simple_parameter`. The PHP parameter loop filtered on `simple_parameter`
only, so promoted params were skipped entirely: their type emitted no
`parameter_type` edge on the constructor, and — because a promoted param
is also a real class field — no `field` edge on the class either. A
non-promoted param in the same signature still emitted `parameter_type`,
so the type reference was silently dropped for exactly the promoted case.

The promoted param's type sits in the same direct named-child shape the
loop already reads for `simple_parameter`, so widening the filter to
accept `property_promotion_parameter` makes the existing type extraction
emit the `parameter_type` edge. Additionally, for a promoted param, emit
a `field`-context references edge on the class (mirroring the
`property_declaration` handler), guarded so it only fires when a parent
class is in scope and the target is not the class node itself. Normal
`simple_parameter` behaviour is unchanged.

Adds a promoted-property constructor to tests/fixtures/sample.php and
test_php_constructor_property_promotion_contexts asserting the promoted
type appears as both `field` and `parameter_type`, and that a
non-promoted param does not leak a field edge.
2026-07-01 16:36:49 +01:00
Synvoya cd3a376030 fix(objc): emit implements edge for protocol-to-protocol adoption
`@protocol Derived <Base>` dropped the protocol-adoption (inheritance)
edge. The protocol_declaration handler in extract_objc walked children
for method declarations but ignored the protocol_reference_list child
that holds the adopted protocols, so no implements edge was ever emitted
for protocol-on-protocol adoption.

The extractor already handled `@interface Foo <Proto>` adoption, but that
nests the protocol name under a parameterized_arguments node; protocol-on-
protocol adoption uses a different grammar node (protocol_reference_list)
whose adopted-name is a direct `identifier` child, so it was never
matched. Walk protocol_reference_list and emit an implements edge for each
adopted protocol, mirroring the @interface handling.

Adds a defined Base/Derived protocol pair to the ObjC fixture and a
regression test asserting the Derived->Base implements edge.
2026-07-01 16:36:48 +01:00
Synvoya a129ff2cd6 fix(powershell): emit inherits/implements edges for class base types
The `class_statement` handler read only the first `simple_name` child —
the class name — and never inspected the base type(s) after the `:`
token. As a result `class Dog : Animal` dropped the Dog->Animal
inheritance edge entirely; derived classes appeared as isolated nodes.

Walk the class_statement children, and once the `:` token is seen treat
each following `simple_name` as a base type. Matching the C# convention
(PowerShell has no syntactic base-vs-interface split), the first base is
emitted as `inherits` and the rest as `implements`, resolved via
ensure_named_node.

Adds a Shape/Circle inheritance pair to tests/fixtures/sample.ps1 and a
regression test asserting ("Circle","Shape") in the inherits edges.
2026-07-01 16:36:47 +01:00
Synvoya 67b4525f32 fix(scala): emit field type references for var declarations
The Scala field handler matched only `val_definition`, so a mutable field
(`var b: Repo`), which parses as `var_definition`, had its type reference
silently dropped from the graph. val and var nodes are structurally identical
(both expose a `type` field), so the existing type-collection logic works
unchanged. Widen the guard to accept var_definition.

Adds a var field to the Scala fixture and a regression test.
2026-07-01 16:36:47 +01:00
safishamsiandClaude Opus 4.8 784e9c833e fix(extract): case-sensitive cross-file resolution in case-sensitive languages (#1581)
Cross-file name resolution folded case for every language, so `from pathlib
import Path` resolved to a shell script's `export PATH=...` node — one variable
becoming the corpus's #1 god-node (266 false incoming edges on a real repo),
polluting god-node rankings, affected blast-radius, and clustering. Reported
with a precise diagnosis by @sheik-hiiobd.

Case is semantic in Python/Rust/Go/Java/C#/Kotlin/Swift/Ruby/C/C++/JS/TS: `Path`
(class), `PATH` (env var), `path` (variable) are distinct. Fix gates folding by
language at the two resolution sites the repro exercised:

- global cross-file CALL resolver: index by exact case; a folded index is built
  only for case-insensitive-language nodes (PHP/SQL/Nim) and consulted only when
  the calling file is such a language.
- type-reference STUB rewire (_rewire_unique_stub_nodes): match stubs to real
  defs by exact case, with a folded fallback restricted to case-insensitive-
  language definitions — so a case-sensitive `PATH` can never absorb a `Path`.

For case-sensitive languages this only ever removes false edges. Concept/doc
dedup (dedup.py, guarded to non-code nodes) is intentionally left folding.
Regression tests: Python `Path` no longer hits shell `PATH`; a case-differing
cross-file ref doesn't resolve; exact-case resolution still works; PHP fold
preserved. Full suite 2777.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 15:09:42 +01:00
safishamsiandClaude Opus 4.8 532a20e775 docs(changelog): note julia/rust-tuple-struct/systemverilog fixes (#1580, #1582, #1583)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 13:51:27 +01:00
Synvoya 297075c3f3 fix(systemverilog): emit field references for qualified class properties
The SystemVerilog class-body field regex in _augment_systemverilog_semantics
matched only unqualified `<type> <name>;` declarations. Its `^\s*` prefix
consumes leading whitespace but not leading class-property qualifiers, so a
qualified field such as `rand Config m_cfg;` (three tokens) failed the
two-token shape and its type reference was silently dropped from the graph.

Consume optional leading qualifiers (rand/randc/local/protected/static/const/
automatic/var) before the type token. Zero qualifiers preserves the existing
behavior; the type and name capture are unchanged.

Adds test_systemverilog_qualified_field_references plus rand- and
protected-qualified fields (and a Config class) to the shared .sv fixture.
2026-07-01 13:45:53 +01:00
Synvoya 7eb847bcf7 fix(rust): emit field type references for tuple structs
extract_rust() only traversed field_declaration_list (named-struct
bodies), so tuple structs -- whose positional fields nest under
ordered_field_declaration_list -- had every field type reference
silently dropped from the graph.

This is the same node shape the enum handler already accounts for
(tuple variants nest their types under ordered_field_declaration_list);
the struct path was simply left behind. Add an additive branch that,
for each type node in a tuple struct's ordered_field_declaration_list,
collects type refs via _rust_collect_type_refs and emits references
edges with the appropriate field / generic_arg context. The
named-struct path is untouched.

For `struct Wrapper(Logger, Config);` with Logger/Config defined
in-file, no field edges were produced before; both are now emitted.

Adds test_rust_tuple_struct_field_references and a tuple struct to the
shared Rust fixture covering plain and generic positional field types.
2026-07-01 13:45:53 +01:00
SynvoyaandClaude Opus 4.8 984a6a8f0a fix(julia): emit imports for qualified, relative, and scoped-selected forms
Only bare-identifier imports (`using Foo`) emitted edges. tree-sitter-julia
wraps qualified paths in `scoped_identifier` (`using Base.Threads`), relative
paths in `import_path` (`using ..Sibling`), and the package of a
`selected_import` may itself be a `scoped_identifier`
(`import Base.Threads: nthreads`). None of those were matched, so qualified and
relative imports were silently dropped, and scoped selected-imports pointed at
the selected symbol instead of the module.

Resolve the module name from identifier / scoped_identifier / import_path in
all three positions. Adds fixture lines + a regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 13:45:52 +01:00
safishamsiandClaude Opus 4.8 7e24c3b7e4 docs(changelog): note elixir/fortran/rust extractor fixes (#1577, #1578, #1579)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 12:00:48 +01:00
SynvoyaandClaude Opus 4.8 674184d462 fix(rust): emit references edges for enum variant field types
Enum variant payload types were silently dropped — `struct_item` and
`trait_item` had type-reference handlers but `enum_item` had none, so the
variant field types were never traversed.

Add an `enum_item` branch that walks
`enum_variant_list -> enum_variant -> ordered_field_declaration_list`
(tuple variants, `Click(Logger)`) and `field_declaration_list` (struct
variants, `Resize { size: Dim }`), emitting a `references` edge from the enum
to each field type. Reuses the same type collection as the struct path. Adds
an enum to the fixture and a regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 11:58:39 +01:00
SynvoyaandClaude Opus 4.8 b8f41c77eb fix(fortran): emit calls edges for function invocations
Function calls (`y = f(x)`) were silently dropped — only `subroutine_call`
(`call sub(...)`) was handled in walk_calls. tree-sitter-fortran represents a
function invocation as a `call_expression`, which had no branch, so every
function-to-function call produced no edge.

Handle `call_expression`. Because Fortran uses the same `name(...)` syntax for
array indexing, the callee is resolved against procedures defined in the file
(`target_nid in seen_ids`) before emitting — so array accesses like `arr(i)`
cannot fabricate spurious `calls` edges. Adds a function + caller to the
fixture and a regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 11:58:38 +01:00
SynvoyaandClaude Opus 4.8 f2ea6a6087 fix(elixir): expand multi-alias brace form into per-module imports edges
`alias Foo.{Bar, Baz}` (and the same import/require/use brace form) emitted
NO imports edges. tree-sitter-elixir represents it as a `dot` node holding the
base alias plus a trailing `tuple` of member aliases, but the import handler
only matched a bare `alias` child, so every multi-alias import was silently
dropped.

Add `_get_alias_modules`, which expands the brace form to `Foo.Bar`,
`Foo.Baz`, … while leaving the single form (`alias Foo.Bar`) unchanged. Adds a
fixture line + regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 11:58:38 +01:00
safishamsiandClaude Opus 4.8 8127ff9a9c fix(cluster): detect stale community labels on cluster-only re-cluster
Reported from a real run: after re-scoping a repo (5807->3710 nodes), the
228-community re-cluster kept run-1's 300 saved labels, so cids now covering a
different community wore the wrong (LLM) names — silently. cluster-only reused
.graphify_labels.json wholesale, and the overlap-based cid remap grabs a prior
cid on any overlap, inheriting a stale name.

Fix: write a per-community membership signature (sha256 of sorted member ids)
beside the labels. On reuse, keep a saved label only when the community's
signature is unchanged; a changed community is renamed by its deterministic
hub (correct-by-construction) with a warning to run `graphify label` for fresh
LLM names. For label files predating the signature, fall back to a community-
count check (a differing count means a different clustering -> don't trust cid
labels). Unchanged graphs reuse labels silently — no false warnings.

Verified: stale legacy labels (42) on a 12-community graph -> warned + hub-
renamed all + sig written; rerun on the unchanged graph -> silent reuse, labels
stable. Unit tests for the signature (deterministic, order-independent, changes
on membership change). Full suite 2771.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 11:52:50 +01:00
safishamsiandClaude Opus 4.8 e34e27c24c fix(extract): cross-file indirect_call survives id relativization (0.9.4 regression)
Local install-testing of 0.9.4 surfaced that `graphify extract .` dropped every
cross-file indirect_call edge — the headline feature, broken on the primary code
path — while the extract() API worked. Root cause: the cross-file callable-target
guard unioned per-file `callable_nids` (pre-remap ids), but extract() rewrites node
ids afterward (id_remap / prefix sym_remap / _disambiguate_colliding_node_ids). When
the scan root relativizes ids (cache_root == project root, which the CLI passes), the
guard set went stale and `tgt not in callable_nids` rejected every remapped target.
In-file indirect edges survived (emitted with consistently-remapped endpoints), which
masked it — only cross-file dropped.

Fix: mark callable defs with a `_callable` attribute on the node dict instead of
exporting an id list. A marker rides through every id remap; callable_nids is rebuilt
from the final (post-remap) nodes right before the pass that uses it, and the marker
is stripped before output (like origin_file). Regression test extracts with
cache_root == project root (the CLI shape) and asserts the cross-file edge survives
and _callable never ships to graph.json. Full suite 2769.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 11:43:05 +01:00
safishamsiandClaude Opus 4.8 b7f88afc30 release: 0.9.4
indirect_call dispatch arc (call args + cross-file, dispatch tables,
assignment/return, getattr, JS/TS), two incremental-update data fixes
(hyperedge preservation + ghost-node prune, incl. symlinked-root hardening),
direction-aware skill-version warning, deterministic hub community labels,
Ruby/Groovy inheritance edges, corrupt-graph.json error handling, cross-chunk
collision warning, Windows hook worker limit.

Built wheel validated in a clean venv: CLI reports 0.9.4, import resolves to
the installed package, new-feature smoke battery green, and a real `graphify
extract` produces indirect_call + inherits edges end-to-end.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 11:17:59 +01:00
safishamsiandClaude Opus 4.8 de7d362537 fix(build): relativize source_file across a symlinked root (#1571 follow-up)
Rigorous smoke testing surfaced an edge case the canonical-tmp unit tests
couldn't reach: when the scan root is under a symlink (macOS /var ->
/private/var, a symlinked home or git worktree), the absolute prune path and
the resolved root differ by prefix, so _norm_source_file's lexical
relative_to fails and the prune/replace match silently misses — deleted
files' ghost nodes survive. Latent in the pre-existing #1007 path too, now
that build_merge resolves the root.

Fix: when lexical relative_to fails, retry with both sides fully resolved.
Only the failure path resolves, so the common lexical match stays
filesystem-free (no per-node stat on the hot replace-per-source loop).

Adds a symlinked-root prune regression test (POSIX-only). Full suite 2768,
and the full end-to-end smoke battery (indirect_call all contexts, JS,
Ruby/Groovy inherits, hyperedge preservation, symlinked-root ghost prune,
corrupt-json errors, dedup collision warning) is green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 11:14:48 +01:00
safishamsiandClaude Opus 4.8 6eb7c014f4 test(build): add regression tests for corrupt graph.json (#1537)
#1537 shipped with a manual test checklist only. Add automated tests that
corrupt a graph.json and assert the actionable RuntimeError at all three load
paths (build_merge, affected.load_graph, diagnostics._read_json_file) plus a
happy-path guard. Also record the six merged small fixes in the changelog.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:49:43 +01:00
hibinmandClaude Opus 4.8 64a6093376 fix(groovy): emit inherits/implements edges for extends/implements
tree-sitter-groovy exposes inheritance via the same `superclass` and
`interfaces`/`type_list` fields as tree-sitter-java, but the inheritance-
emitting block in `_extract_generic` was gated on
`ts_module == "tree_sitter_java"`. Groovy was the only class-based JVM
language in the file with no inheritance handler, so every Groovy
`extends`/`implements` was silently dropped (contains/methods/imports/calls
were unaffected).

Widen the gate to include `tree_sitter_groovy`; the existing
`_emit_java_parent_type` path handles the identical node shapes verbatim.
Adds a base class + interface to the Groovy fixture and two regression
tests (extends -> inherits, implements -> implements).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:47:10 +01:00
hibinmandClaude Opus 4.8 a19b9e90ec fix(ruby): emit inherits edge for class superclass
`class Dog < Animal` exposes the base in the `superclass` field, but the
inheritance handler in `_extract_generic` had branches for
java/kotlin/c#/scala/cpp/php/swift/python and none for Ruby, so every Ruby
`inherits` edge was silently dropped (contains/methods/calls unaffected).

Add a Ruby branch that reads the `superclass` field, handling both a bare
`constant` (`< Animal`) and a `scope_resolution` (`< Foo::Bar` -> Bar).
Adds a subclass to the Ruby fixture and a regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:47:10 +01:00
Matias Duarte 879c05894d fix(hooks): limit Windows hook rebuild workers 2026-07-01 10:47:10 +01:00
Varun Nuthalapati 5320aa8eb1 fix(dedup): warn on cross-chunk node ID collision to surface silent data loss (#1504)
When two LLM extraction chunks each process a file with the same name in
different directories, they independently generate the same node IDs and
deduplicate_entities() silently drops one node (first-writer-wins). The
data loss had no indication in any log, counter, or output.

Adds a stderr WARNING when a duplicate ID comes from a different
source_file, telling the user which files collided and recommending the
per-subfolder extract + merge-graphs workflow to avoid it.
2026-07-01 10:47:10 +01:00
guy oronandClaude Opus 4.6 4a8d6bad97 fix: harden graph JSON loading against corruption (#1536)
Wrap unguarded json.loads() in build_merge(), load_graph(), and
_read_json_file() so corrupted graph.json files produce an actionable
RuntimeError instead of an unhelpful JSONDecodeError traceback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-01 10:47:10 +01:00
tpateeqandClaude Opus 4.8 93e8e445dd docs(build): correct deduplicate_by_label docstring — dormant, not auto-called
deduplicate_by_label is never wired into build(); the active dedup path is
deduplicate_entities (imported and called in build). Its docstring claimed
"Called in build() automatically," which was never true. Correct it to say the
helper is dormant/unused and to warn that it merges by label alone with no
file_type guard, so it must not be enabled for code nodes — same-label symbols
from different files/packages (e.g. two Account types) would collapse, the
cross-file conflation deduplicate_entities deliberately avoids for code (#1205).

Docstring only; no behavior change. The function is unused and superseded, so it
could reasonably be deleted instead — left in place here, flagged for your call.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 10:46:59 +01:00
safishamsiandClaude Opus 4.8 20547c4767 docs(changelog): note getattr slice 3 (#1575) and hub labels (#1576)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:32:59 +01:00
Sheik Ershad 1aab291caf feat(cluster): deterministic hub community labels (readable without an LLM)
Community labels defaulted to "Community N" whenever no LLM backend was configured,
making the report + suggested questions unreadable ("why does log_action connect
Community 70 to Community 129?"). Add `label_communities_by_hub`: name each community
after its highest-degree member — the structural hub — so the report reads "log_action"
/ "auth" with zero LLM cost. Ties break by node id for run-to-run stability; a community
with no members in the graph keeps the "Community N" placeholder.

Wired as the default base at both label-building sites — the label/standalone path in
__main__ and the watch/detect rebuild in watch.py. A configured LLM naming pass still
runs and overrides these with richer names; its no-backend placeholder fallback is
guarded so it can't clobber the hub labels.
2026-07-01 10:30:47 +01:00
Sheik Ershad 8fdbf50197 feat(extract): capture getattr(obj, "name") indirect_call edges (#1566 slice 3)
Reflective dispatch by string literal — getattr(obj, "handler") — resolves the
attribute name to a callable def and emits it under indirect_call (context
"getattr", INFERRED) at both function and module scope, so `graphify affected
handler` now covers getattr call sites.

The name is a STRING, not an identifier: it names an attribute and is never
shadowed by a param/local, so it resolves without the identifier shadow guard —
the inverse of the #1565/#1566 identifier paths. A dynamic name (a variable,
f-string, concatenation, or any expression) is not statically resolvable and emits
nothing; obj.getattr(...) (a method, not the builtin) and the 1-arg form are ignored.

Refactors the shared resolve-and-emit core out of _emit_indirect_ref into
_emit_indirect_by_name so the getattr path reuses it (callable-target-only,
cross-file deferral, dedup) without duplicating the guard; the identifier wrapper
is behavior-preserving. Full suite green.
2026-07-01 10:30:47 +01:00
safishamsiandClaude Opus 4.8 4f40967e8d fix(build): preserve hyperedges + harden prune root in build_merge (#1574, #1571)
build_merge backs `graphify --update`. Two incremental-update data bugs:

#1574 — it read only nodes+edges from the existing graph.json, never
hyperedges, and build() only sees the new chunks' hyperedges. So every
--update collapsed the graph's hyperedge set (the highest-signal semantic
groupings) down to just the re-extracted files'. Now existing hyperedges are
carried forward via attach_hyperedges (id-dedup): re-extracted files' prior
hyperedges are replaced by their new version (by source_file), deleted files'
are dropped via the prune set, and unchanged/global ones are preserved. This
mirrors what watch.py already did.

#1571 — when a caller omits `root`, absolute prune_sources (from
detect_incremental) never relativized to the stored relative source_file
keys, so deleted files' nodes survived as ghosts and accumulated across runs.
Added _infer_merge_root: fall back to the committed graphify-out/.graphify_root
marker, else the output dir's parent. This root now drives BOTH the prune set
and the replace-per-source normalization, so both work without an explicit
root. The CLI --update path and all shipped runbooks already pass root; this
hardens the library for any other caller.

5 tests: hyperedge preservation (unchanged/global kept, re-extracted replaced,
with and without root), deleted-file hyperedge prune, and root-less prune via
both the grandparent and .graphify_root-marker fallbacks. Full suite 2742.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:12:46 +01:00
safishamsiandClaude Opus 4.8 69b3997386 docs(changelog): note assignment/return indirect_call (#1569)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 23:27:46 +01:00
Sheik Ershad 311e63a7fc feat(extract): capture assignment/return indirect_call edges (#1566 slice 2)
A function bound to a name (cb = handler) or returned from a factory
(def make(): return handler) is a real reference, but indirect_call only
covered call arguments and dispatch tables, so `affected` still dropped these
callers.

Emit indirect_call (context "assignment"/"return", INFERRED) for the value-side
identifiers of a Python assignment RHS and a return, at function scope (owner =
enclosing function) and module scope (owner = file node). Reuses the shared
_emit_indirect_ref guard. Scans the VALUE side only -- the assignment target is
a new local binding, not a reference -- so the existing param/local shadow guard
still rejects the false edges #1565 fixed.

Negatives covered: param-shadow, local-shadow, non-callable emit nothing.
Full suite green; ruff clean.
2026-06-30 23:26:13 +01:00
safishamsiandClaude Opus 4.8 47033c8b75 fix(cli): make skill-version warning direction-aware (#1568)
_check_skill_version advised "Run 'graphify install' to update" on ANY
version mismatch. But `install` writes the package's OWN bundled skill and
re-stamps .graphify_version, so when the skill on disk is NEWER than the
running package, following that advice silently DOWNGRADES the skill to
silence the warning. The docstring even said "warn if the skill is from an
OLDER version" but the code never checked direction.

Compare versions numerically (new _version_tuple, so 0.10 > 0.9 and a
malformed stamp degrades instead of raising). When the skill is newer than
the package, recommend upgrading the package (uv tool upgrade / pip install
-U) instead of install; the older-skill case is unchanged. Hit in practice
by a stale `uv tool` CLI and by contributors whose dev checkout stamped a
newer skill. Reported by @TPAteeq.

4 tests (numeric ordering, both mismatch directions, silent-when-equal).
Full suite 2730 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 23:15:52 +01:00
safishamsiandClaude Opus 4.8 6dc1cb0dd7 feat(extract): capture indirect dispatch for JS/TS (#1566 slice 5)
Brings the indirect_call model to JavaScript and TypeScript, the next-
biggest callback-passing ecosystem. Now captured:

- callbacks passed by name as call arguments: `arr.map(fn)`, `setTimeout(fn)`,
  `el.addEventListener("x", fn)` — function-scoped, attributed to the caller.
- module-level callback registration (idiomatic in JS, unlike Python):
  Express routes `app.get("/", handler)`, event wiring `emitter.on("e", h)`,
  timers — attributed to the file.
- object/array dispatch tables: `const ROUTES = { create: handler }`,
  `const HOOKS = [onStart, onStop]`, object shorthand `{ handler }`.

Arrow-const functions (`const cb = () => {}`) are registered as callable
targets (threaded callable_def_nids + local_bound_names through
_js_extra_walk). Guards mirror Python: shadowing by param/local/module
reassignment is rejected (JS module shadow set excludes function-valued
declarators so arrow-consts stay resolvable), object KEYS and non-callable
values are excluded, inline arrows/function expressions are direct defs not
references, single-definition god-node guard cross-file.

Two cross-file fixes the JS import model exposed:
- a name that resolves to an import-surfaced FOREIGN symbol (JS named
  imports map the real node into the importing file's label map) is now
  deferred to the cross-file resolver instead of being mistaken for a local
  non-callable; the global callable_nids guard still rejects imported data.
- indirect_call dedup is now call-aware: a benign `imports` edge from a file
  to the symbol it imports no longer suppresses the indirect_call to it
  (only a real calls/indirect_call edge does).

Shared the resolve-and-emit helper across Python and JS/TS. 9 new tests
(func-arg, module object/array, Express-style registration, inline-arrow
negative, param-shadow, key/data exclusion, shorthand, cross-file import,
TS typed params). Full suite 2726 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 22:34:48 +01:00
safishamsiandClaude Opus 4.8 8288829613 feat(extract): capture dispatch tables as indirect_call edges (#1566)
Slice 1 of #1566. A function referenced as a VALUE in a dict/list/set/
tuple literal — the registry/route-table idiom (`ROUTES = {"create":
create_user}`, `HOOKS = [on_start, on_stop]`) — is an indirect dependency
that blast-radius must see, but the call-argument capture (#1565) didn't
cover it. Emit an indirect_call edge for each callable value:

- module-level tables attribute to the file node; function-scoped tables
  attribute to the enclosing function. Same-file and cross-file (an
  imported handler in a table routes through the cross-file resolver).
- dict KEYS are excluded (only values are references); non-callable values
  (a number, a string) never resolve; a name shadowed by a param/local or
  rebound at module scope is the local value, not the function.

Refactors the resolve-and-emit logic shared by the argument and table
paths into one guarded helper (_emit_python_indirect_ref) and threads the
edge `context` ("argument" | "collection") through the cross-file pass.
Adds _python_module_bound_names for the module-scope shadow set.

7 new tests (module dict/list, function-scoped, dict-keys-excluded,
non-callable-value, module-reassign shadow, cross-file table). Full suite
2717 passed. Python only; assignment/return refs + other languages remain
on #1566.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 22:17:53 +01:00
safishamsiandClaude Opus 4.8 cf747abeaf feat(extract): resolve cross-file indirect dispatch as indirect_call
#1565 captured a function passed by name as a call argument
(executor.submit(fn), Thread(target=fn), map(fn, xs)) only when the
callback was defined in the SAME file — it resolved through the in-file
label map. But the dominant real-world shape is cross-module: the callback
is imported (`from .handlers import on_event; pool.submit(on_event)`), so
the same-file map can't see it and the edge was dropped — exactly the
caller a blast-radius query must not miss.

When the argument identifier isn't defined in-file (and isn't shadowed by
a param/local — that guard already ran), emit an `indirect` raw_call and
let the existing cross-file resolution pass handle it, branching to a
distinct indirect_call/INFERRED edge instead of calls. It rides the same
single-definition god-node guard and import-evidence disambiguation as
direct calls (parity: when a direct call resolves, so does the indirect
one; when the name is ambiguous, both bail). Two added safeguards: the
target must be a real callable def (per-file callable_nids unioned across
the corpus) so an imported data constant can never become a dispatch
target, and an existing direct `calls` edge for the pair pre-empts it.

Smoke-verified: imported single-def callback resolves; ambiguous name
bails (same as direct); imported data constant rejected; direct+indirect
to the same target keeps only the direct edge; cross-file keyword
target=cb resolves. Full suite 2710 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 22:08:14 +01:00
Sheik ErshadandClaude Opus 4.8 19e7a31343 feat(extract): capture indirect dispatch as indirect_call edges (#1565)
`graphify affected` (blast radius) was blind to a function passed BY NAME as
a call argument — `executor.submit(fn)`, `Thread(target=fn)`, `map(fn, xs)`,
callbacks — so those callers were silently dropped from the affected set (an
under-counting blast radius reads complete while missing exactly where
regressions hide). Capture them as a distinct `indirect_call` relation
(INFERRED, context "argument"), kept separate from `calls` so strict
call-graph queries stay precise, and add it to DEFAULT_AFFECTED_RELATIONS.

Hardened over the original PR against the name-collision false edge (the
Doxygen #3748 trap): emit only when the argument identifier resolves to a
callable definition AND is not shadowed by a parameter or local binding in
the enclosing function. So `def via(pool, handler): pool.submit(handler)`
(handler is the param, not the module function) and `process(config)` where
`config` is local data emit no edge, while a genuine module function passed
by name still resolves. Dedup-safe against existing direct `calls` edges.
Python only; dict-literal / getattr-by-string / decorator dispatch deferred.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 21:53:46 +01:00
safishamsiandClaude Opus 4.8 0c551ace36 release: 0.9.3
Cross-file member-call resolution for C++/ObjC (#1547/#1556) and
namespace-aware C# type resolution (#1562), the work-memory overlay
(#1441), test-mock call-graph fix (#1553), hyperedge member-key aliases
(#1561), plus the TS/JS/ObjC resolution fixes (#1316/#1544/#1552/#1475).
See CHANGELOG.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 20:00:00 +01:00
TheFedaikinandClaude Opus 4.8 b9d8067d0a feat(csharp): namespace-aware cross-file type resolution (#1562)
Extends the C# type-reference resolver (#1466) to be namespace-aware,
advancing the #1318 shadow-node umbrella for C#:

- The namespace is folded into the C# node id (_make_id(stem, namespace,
  name)), so two same-named types in different namespaces in one file no
  longer collapse — replacing #1466's detect-and-skip workaround for
  multi-namespace files.
- Lexical per-block using-scope: a `using` applies only where it is in
  scope (file-level, or the enclosing namespace block via a scope chain),
  so sibling namespace blocks no longer share each other's usings.
- Qualified references (`Namespace.Type`) resolve via in-scope aliases
  (`using Q = X.Y`) then exact known namespaces; generics are stripped.

Preserves (and tightens) the refuse-rather-than-guess discipline: a bare
reference resolves only when exactly one in-scope namespace provides the
type; an ambiguous reference (e.g. `using A; using B;` both defining
`Widget`) resolves to nothing rather than fanning out. Verified: `using A`
-> A.Widget only; ambiguous -> no edge; qualified `B.Widget` -> B.Widget
regardless of usings; sibling-block using-scope isolated; no dangling
edges or fan-out.

Reconciled onto current v8 (the PR predated the C++/ObjC member-call
resolvers); full suite green, the C++/ObjC resolution coexists.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 19:32:10 +01:00
safishamsiandClaude Opus 4.8 49252d3cb7 feat(extract): cross-file member-call resolution for C++ and ObjC (#1547, #1556)
Connects paired classes across files: Main.cpp's `Foo f; f.bar()` now resolves
to Foo::bar, and ObjC `Foo *f = [[Foo alloc] init]; [f doThing]` to Foo's
doThing — the "connect with other classes" goal of #1547/#1556.

Design grounded in prior-art research (ctags qualified-name matching, Doxygen's
name-keyed false-edge failure modes, PAIGE's receiver-type approach, Clang USR):
resolve by RECEIVER TYPE, never bare name, and skip when the type can't be
inferred rather than guess (a false call edge / god-node is worse than a missing
one). Mirrors the existing Swift/Python/Ruby/TS member-call resolvers.

- C++ extractor now captures the member-call receiver (field_expression /
  qualified_identifier / pointer access) and builds a per-file type table from
  local declarations (`Foo f;`, `Foo* f;`, `Foo *f = ...;`); emits raw_calls.
- ObjC extractor emits raw_calls for message sends with the receiver + selector
  and a type table from `Foo *f = ...;` locals (existing in-file selector /
  alloc-init / dot-syntax / @selector matching preserved).
- New _resolve_cpp_member_calls / _resolve_objc_member_calls, registered for
  their suffixes. Receiver tiers: `Foo::bar()` / capitalized ObjC receiver and
  this/self/super (enclosing class) -> EXTRACTED; local-var-typed -> INFERRED.
  Single-definition god-node guard (skip unless exactly one type def matches);
  the just-shipped decl/def class merge makes a paired class one def so the
  guard resolves it. Verified: a.run() -> A::run only (not a same-named B::run);
  an uninferable receiver with run() in two classes emits zero edges (no
  fan-out); ObjC [f doThing] -> Foo only.
- build.py: the cross-language INFERRED-call prune treated .h/.cpp/.m as
  different families and dropped header/impl interop calls; unified the C family
  (.c .h .cc .cpp .hpp .cxx .hh .hxx .cu .cuh .metal .m .mm) so a .cpp/.m call to
  a .h-declared method survives.

Still open (tracked on #1547/#1556): the file-level `#include` edge can stay
uncanonicalized when the project root isn't symlink-resolved (the extract()
id-remap `continue`s on a /var-vs-/private/var mismatch) — the class connection
above is robust to it; include-reachability candidate narrowing and ObjC
dynamic-dispatch/id-typed receivers also deferred (expected low ObjC recall, per
the research).

Reported by @c0dezer019 (#1547) and @JabberYQ (#1556).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 18:30:05 +01:00
safishamsiandClaude Opus 4.8 3bc3feed54 fix(extract): merge header/impl class fragmentation + C++/ObjC header routing (#1556, #1547)
A class declared in a header (Foo.h/@interface) and defined in its impl
(Foo.cpp/Foo.m/@implementation) fragmented into two nodes: _file_stem
drops the extension so Foo.h and Foo.cpp share a node id, which
_disambiguate_colliding_node_ids then split apart by path — and the two
"defs" tripped every resolver's single-definition god-node guard,
cascading into missing .h<->.m/.cpp linkage and cross-file/cross-language
edges.

- Routing: a `.h` using `#import` now routes to extract_objc (#1556 bridging
  headers — extract_c drops `#import` as a preproc_call), and a `.h` with
  C++-only signals (class/namespace/template/::/access-specifiers) routes
  to extract_cpp (#1547 — the C grammar has no class_specifier, so a C++
  header previously yielded a junk node and lost every method). ObjC sniff
  keeps priority; a plain C header still routes to extract_c.
- Merge: a new _merge_decl_def_classes post-pass collapses the header/impl
  id-collision onto the header (declaration) variant, modeled on
  _merge_swift_extensions, gated so it fires ONLY for a clean sibling
  header/impl pair (same dir, same base stem, exactly one header) — two
  same-named classes in different directories have different stems and
  never collide, so they are never merged (god-node guard verified). C++
  method definitions retain their `Foo::` qualifier so a `Foo::bar` def
  keys onto the header declaration (one method node, not two); free
  functions keep their bare-name ids.

Result: one canonical class node per .h/.m or .h/.cpp pair with methods
unified, which unblocks the existing member-call resolvers (verified
Swift->ObjC calls and Swift `extension` folding now resolve). Strict
improvement over v8 (which produced junk/fragmented nodes here, verified).
Still open as follow-ups: cross-file C++ #include edge resolution and a
C++/ObjC cross-file member-call resolver (a pre-existing gap, not a
regression).

Reported by @JabberYQ (#1556) and @c0dezer019 (#1547).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 17:23:46 +01:00
safishamsiandClaude Opus 4.8 bee3849810 fix(resolve): test mocks no longer erase the real cross-file call graph (#1553)
The cross-file call resolver bailed (#543/#1219 god-node guard) whenever a
bare callee name had 2+ definitions without unique import evidence — so a
single same-named test mock (or any same-named symbol) dropped the real
`calls` edge, erasing the call graph wherever a mock existed (the reporter
saw a 76-stub Pester suite wipe everything).

Replace the blunt bail with a smarter guard: when a name is ambiguous and
import evidence doesn't resolve it, apply tie-breakers — non-test
preference (a shared, segment-aware _is_test_path classifier) then path
proximity — and emit an INFERRED edge ONLY if exactly one candidate
survives, else keep bailing. A real def + a test mock resolves to the real
def; two genuine non-test defs still bail (god-node guard intact, no
fan-out). Wired into both the extract.py pass and the symbol_resolution.py
copy via the shared classifier.

Reported by @Schweinehund.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 16:59:16 +01:00
safishamsiandClaude Opus 4.8 bd885cc97d fix(hyperedge): accept members/node_ids alias keys for the member list (#1561)
A hyperedge's member list is canonically keyed `nodes`, but producers
(LLM/subagent drift, externally-supplied graph.json) sometimes emit
`members` or `node_ids` — graphify only read `nodes`, so those hyperedges
silently lost their members, and semantic_cleanup's prune dropped them
entirely. Normalize the member key to `nodes` at one ingest chokepoint in
build_from_json (and in semantic_cleanup, which runs pre-build), deduping
and warning, so every downstream consumer sees the canonical key. Mirrors
the existing from/to edge-endpoint aliasing.

Reported by @askalot-io.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 16:58:23 +01:00
c865a3c9b0 fix(reflect): layout-ordered source resolution for overlay staleness (#1558)
Refines the staleness file resolution (00e00a0) by folding in the two
genuine merits of @TPAteeq's parallel fix (#1558), which independently
and correctly diagnosed the same root-mismatch bug:

- Layout-ordered candidates: try the layout-appropriate root FIRST (the
  graphify-out parent for the standard layout, graph.json's own dir for a
  flat layout) before the other. The prior order tried the grandparent
  first unconditionally, which in a flat layout (graph.json at the project
  root) could fingerprint a same-named file one directory up. Existence
  checking is kept on top, so a defeated name heuristic or a stale
  .graphify_root marker still falls through to the real file.
- Adds @TPAteeq's .graphify_root-marker-driven regression test, plus a
  flat-layout test that pins the ordering (editing the real file flips
  stale; editing the same-named decoy one dir up does not).

Co-Authored-By: tpateeq <mohammedateequddin399@gmail.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 12:57:33 +01:00
safishamsiandClaude Opus 4.8 2cdc212b43 docs: README work-memory overlay note + Unreleased changelog
README: document that `reflect --graph` writes the .graphify_learning.json
overlay and that explain/query surface a Lesson hint (with the
code-changed staleness flag).

CHANGELOG: add an Unreleased section for the post-0.9.2 work — the
work-memory overlay (#1441/#1542), this.field.method() injected-field
resolution (#1316), TS wildcard path aliases (#1544), JS namespace
re-exports (#1552), and the ObjC dot-syntax/@selector edges (#1475/#1543).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 12:42:25 +01:00
safishamsiandClaude Opus 4.8 00e00a0b5f fix(reflect): work-memory staleness false-positive on relative source paths
The overlay fingerprint resolved a node's source_file against
graph_path.parent (the graphify-out/ dir), but source_file is stored
relative to the PROJECT root — so graphify-out/auth.py never existed and
_is_stale flagged EVERY verdict "code changed since — re-verify" the
moment it was written. (The original staleness test used an absolute
source_file, which masked it.)

Fix: resolve the file by trying the likely roots in order (.graphify_root
marker, graphify-out's parent, graph.json's own dir, cwd) and use the
first that exists — the same search at write and read — and fingerprint
file CONTENT only (sha256 of bytes, no path mixed in) so the hash is
root-independent and a committed sidecar stays valid across checkouts.
Drops the brittle directory-name-based root guess.

Adds a regression test with a relative source_file under the graphify-out
layout (stale=False right after reflect, True after an edit).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 12:40:20 +01:00
safishamsiandClaude Opus 4.8 5779767fd3 feat(reflect): work-memory overlay — surface learned verdicts as a graph sidecar (#1441)
Projects the verdicts `graphify reflect` already distills (preferred /
tentative / contested, exponential time-decayed) into a derived
experiential layer the read surfaces consume, so accumulated agent
experience actually shows up where you look — without polluting the
structural graph.

Design (grounded in agent-memory + provenance literature; a redesign of
the #1542 approach):
- SIDECAR, not graph.json stamping. `reflect` writes `.graphify_learning.json`
  next to graph.json (an additional output, so the git hooks produce it
  automatically). graph.json stays purely structural; nothing leaks into
  GraphML; no graph.json churn. Mirrors the named-graph / event-sourcing
  separation of durable truth from a derived layer.
- Reuses the existing reflect aggregate (its `_decay` is the
  recency-weighted exponential model; `_finalize_sources` the
  classification) — no new scoring.
- PROVENANCE: each verdict carries the source questions/dates that produced
  it (cap 5, most-recent first).
- STALENESS: each verdict stores the node's file fingerprint; on read, a
  changed source file flags the verdict stale ("code changed since —
  re-verify") rather than presenting a confident lesson on rewritten code.
- CONTESTED surfaced distinctly (useful N / dead-end M), not averaged away.
- DEAD-ENDS stay QUERY-SCOPED — never a node-level status; they appear only
  in the report as question -> nodes.
- Read surfaces (explain / query+MCP / GRAPH_REPORT / graph.html) merge the
  overlay at read time, sanitized; un-annotated graphs are byte-identical.

Deferred (logged): letting verdicts influence query/seed traversal — the
recommender feedback-loop / Matthew-effect risk means that needs
propensity correction + exploration, not naive biasing.

Builds on the idea in #1441/#1542 (thanks @TPAteeq).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 11:19:54 +01:00
guy oronandClaude Opus 4.8 0792b419fc feat(objc): dot-syntax property accesses and @selector() call edges (#1475, #1543)
`self.product.name` dot-syntax now emits an `accesses` edge and
`@selector(method)` emits a `calls` edge, both resolved only to an
unambiguous in-scope definition (a sibling method of the same class for
dot-syntax; exactly one method by exact selector name for @selector) so
no false-edge fan-out occurs when multiple classes share a name.

Hardened over the original PR: resolution now matches the method node id
EXACTLY (a method id is _make_id(container, name)) rather than by
`endswith` suffix. The substring match would mis-resolve `self.name` to a
sibling `-surname` (false positive) and, when a substring-colliding
sibling existed, suppress the correct edge (false negative); exact
matching fixes both. Adds substring-collision regression tests
(`-name`/`-surname`, `-doThing`/`-reallyDoThing`).

Completes the #1475 ObjC follow-ups (Bug 5 dot-syntax accesses, Bug 6b
@selector target-action).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 09:54:28 +01:00
guy oronandClaude Opus 4.8 1801da0634 feat(ts): resolve this.field.method() calls via constructor-injection types (#1316)
A member call through a constructor-injected dependency
(`constructor(private db: Database)` ... `this.db.query()`) now produces
a calls edge to the field type's method. The field->type map is captured
from constructor parameter-properties, and resolution reuses the existing
single-definition god-node guard (like the Swift/Python/Ruby member-call
resolvers): the edge is emitted only when the field's type name resolves
to exactly one class definition that owns the method, so an ambiguous or
unknown/untyped field produces no edge — no global name-match fan-out.
Edges are EXTRACTED (the type is explicit from the annotation). TS/JS-only
and additive; scope is constructor parameter-property injection.

Adds the decisive regression tests the implementation needed: two classes
defining the same method name where the injected field is typed to one of
them (must resolve to that one only), and an ambiguous type-name case
(must emit no edge).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 09:46:16 +01:00
oleksii-tumanovandClaude Opus 4.8 c8c604d08c feat(js): resolve namespace re-export bindings (export * as ns from) (#1552)
`export * as ns from './mod'` now creates a real symbol node for the
namespace binding `ns`, registers it as a named export (so a downstream
`import { ns }` resolves to it), and emits a file-level `re_exports` edge
to the target module. The binding is treated as a single opaque symbol —
`ns.member` accesses are deliberately NOT expanded into per-member
name-matching, avoiding the over-linking that would fan false edges.
Includes re-export cycle and deep-chain recursion guards.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 09:42:49 +01:00
oleksii-tumanovandClaude Opus 4.8 57469641cd feat(js): resolve TypeScript wildcard path aliases (#1544)
Extends the tsconfig path-alias resolver (#1531) with single-`*` wildcard
capture and substitution: a pattern like `@app/*` or `@*/interfaces`
captures the matched segment and substitutes it into each target in
declared order, honoring baseUrl and tsc's longest-prefix / exact-wins
specificity rules, and preserving #1531's first-existing-target-wins
fallback (no false edge when nothing resolves). Builds on the
_resolve_tsconfig_alias helper rather than reintroducing inline loops;
multi-star patterns remain out of scope.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 09:41:50 +01:00
safishamsiandClaude Opus 4.8 544f95efa6 release: 0.9.2
Ruby type-aware member-call resolution and workspace exports-map
resolution, the #1529 alias/workspace import-edge regression fix, tsconfig
paths fallbacks, semantic-cache pruning, three ObjC extractor fixes, Swift
static-call confidence, the secondary LLM timeout, GraphML null coercion,
host-generic install wording, and Dependabot dep bumps. See CHANGELOG.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 16:25:30 +01:00
safishamsiandClaude Opus 4.8 1d8d278f9e docs: add Unreleased changelog section for today's fixes
Covers #1499 (Ruby type-aware resolution), #1308/#1541 (workspace
exports map), #1529 (alias/workspace import-edge regression), #1531
(tsconfig paths fallbacks), #1527 (semantic cache pruning), #1475 (three
ObjC fixes), #1533 (Swift static-call confidence), #1442 (secondary LLM
timeout), #1502 (GraphML null coercion + save-result --answer-file),
#1530 (host-generic skill wording), and the Dependabot dep bumps.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 15:00:59 +01:00
safishamsiandClaude Opus 4.8 51fc00a30f fix(swift): type-qualified static calls resolve as EXTRACTED, not INFERRED (#1533)
A type-qualified Swift call (`Type.staticMethod()`, `Singleton.shared.method()`)
names the receiver type explicitly in source, so the resolved edge is an exact
reference — now emitted as EXTRACTED (1.0), matching the Python
qualified-class-method pass (_resolve_python_member_calls). Instance calls whose
receiver type comes from local inference (`obj.method()`) stay INFERRED (0.8).
Resolution and the single-definition god-node guard are unchanged.

This addresses the actionable part of #1533's "static calls" report: the edge
was always produced (graphify models calls as method->method), it was just
under-confident. Updated the confidence test to assert the instance/type-qualified
split.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 14:49:42 +01:00
safishamsiandClaude Opus 4.8 1652dadd60 fix(objc): NS_ASSUME_NONNULL parse failure, dangling .m imports, alloc/init refs (#1475)
Three residual ObjC extractor bugs from the #1475 thread, each reproduced
against the real tree-sitter-objc grammar:

1. NS_ASSUME_NONNULL_BEGIN before @interface made the parser fail to emit
   a class_interface node at all (the whole interface was swallowed into
   ERROR nodes), so headers using the macro produced no class node. Blank
   the two argument-less annotation macros to equal-length spaces before
   parsing (offset-preserving; macro-free files are byte-identical). The
   reporter's "@class breaks it" hypothesis was wrong — only the macro does.

2. Quoted `#import "X.h"` edges dangled once a `.h`/`.m` pair existed: the
   target used the bare stem, which the post-pass canonicalizes and then
   _disambiguate_colliding_node_ids salts apart by path, so the import
   target no longer matched. Resolve the include to a real file (mirroring
   _import_c), and repoint imports/imports_from edges to the header variant
   in _disambiguate_colliding_node_ids — taking precedence over the
   same-source-file salt so a `.m` importing its own `.h` resolves to the
   header instead of self-looping. Also repairs the equivalent latent
   C-include dangling bug.

3. `[[Foo alloc] init]` produced no edge — walk_calls only reconstructed
   selectors and skipped the receiver. Emit a `references` edge from the
   allocating method to the class, resolved via the unique-class stub guard
   (ensure_named_node + _rewire_unique_stub_nodes) so unknown/ambiguous
   names produce no false edge. The calls-to-init edge is deliberately
   deferred (init selectors are ambiguous across classes).

Reported by JabberYQ with a precise repro and test repo. Adds regression
tests incl. a self-loop guard on the import edges. Still open on #1475:
dot-syntax property accesses (Bug 5) and @selector target-action (Bug 6b).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 14:41:22 +01:00
guy oronandClaude Opus 4.8 e8dabadeb0 feat(imports): resolve workspace subpath exports via package.json exports map (#1308)
Workspace imports with subpath exports (e.g.
`import { x } from "@scope/pkg/browser"`) now resolve through the
package's `exports` map instead of falling back to a bare path. Supports
string values, condition objects, nested conditions, and single-`*`
wildcard patterns (`"./*": "./src/*.js"`), falling back to the existing
bare-path/index resolution when there is no exports map or no match.

Adapted from #1541, taking only the exports-map resolver and not that
PR's competing import-node-ID normalization (current v8 already resolves
the node-ID mismatch via the #1529 id-remap post-pass, and the PR's
_file_stem approach regressed the relative-input alias case). Two
hardening changes over the original:
- `default` is consulted LAST in the condition priority (it is Node's
  catch-all), so a matching `import`/`module`/`svelte` condition wins.
- Export targets that escape the package directory are rejected
  (`_contained_in_package`), so a malicious `exports` value like
  `"./x": "../../../etc/..."` cannot resolve to a file outside the package.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 13:57:16 +01:00
safishamsiandClaude Opus 4.8 7a9cda2452 fix(cache): prune orphan semantic-cache entries at end of extract (#1527)
The AST cache is version-swept but the semantic/LLM cache had no pruning,
so it grew unbounded: it is content-hash-keyed, so every content change
or file deletion leaves a permanent orphan entry (reporter saw 152
entries for 124 live docs). This matters for the committed-cache workflow
where the semantic cache is published for warm CI rebuilds.

Adds prune_semantic_cache(root, live_hashes) and wires it into the end of
the extract path, sweeping cache/semantic/*.json entries whose hash is not
in the live set. The live set is computed from the FULL detected document
set (not the incremental changed-subset, which would delete valid
entries), using the same file_hash recipe save_semantic_cache uses.
Best-effort (unlink guarded), only touches cache/semantic/ (.tmp and
cache/ast/** untouched), and keeps the semantic cache unversioned so
releases never re-bill LLM extraction.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 13:14:37 +01:00
safishamsiandClaude Opus 4.8 2133539930 fix(js): resolve alias/workspace import edges + honor tsconfig paths fallbacks (#1529, #1531)
#1529 (regression from the 0.9.0 full-repo-relative node-ID migration):
relative JS/TS imports resolve to repo-relative paths and ride the
extract() id-remap to canonical node IDs, but tsconfig path-alias and
workspace-package imports resolve to ABSOLUTE paths (their bases are
.resolve()'d), so the import-target ID baked in the on-disk prefix and
never matched the repo-relative definition node — the edge was dropped at
build (common on Next.js/SvelteKit `@/`-alias codebases). The id-remap
post-pass now also registers the absolute-resolved form of each input
path (file-level edges) and both the input-form and absolute-form symbol
prefixes (named-import edges), so alias/workspace import targets remap to
the canonical ID. Verified the built graph has no orphan nodes or
dangling edges.

#1531: tsconfig `paths` values are ordered fallback lists (tsc tries each
target until one resolves), but only targets[0] was kept. The alias map
now stores all targets in order, and a single _resolve_tsconfig_alias
helper (replacing six duplicated inline loops) returns the first target
whose candidate exists on disk, falling back to the first candidate when
none exist (no false edge). Wildcards, baseUrl, and array `extends` are
preserved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 13:14:36 +01:00
safishamsiandClaude Opus 4.8 36b5e5cb29 chore(deps): drop unused safety dev dep (removes unfixable nltk HIGH)
`safety` was declared in the dev group but never invoked — the CI
security-scan job only runs bandit and pip-audit, and pip-audit already
provides the same dependency-CVE scanning. Its only practical effect was
pulling in nltk, which carries an unpatched HIGH path-traversal advisory
(GHSA-p4gq-832x-fm9v) with no fix available.

Removing safety drops nltk (and safety-schemas/typer/tenacity/tomlkit)
from the lockfile entirely, closing the alert with no loss of coverage.
Updated the stale CI comment that referenced safety. Full suite green
(2537 passed); pip-audit and bandit unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 11:29:45 +01:00
safishamsiandClaude Opus 4.8 738c9cebcb chore(deps): bump msgpack 1.2.1 and pydantic-settings 2.14.2 (Dependabot)
Resolve two Dependabot alerts in transitive deps:

- msgpack 1.1.2 -> 1.2.1 (HIGH, GHSA-6v7p-g79w-8964): out-of-bounds
  read / crash on Unpacker reuse after a caught error. Pulled only via
  cachecontrol -> pip-audit (dev group), so not in the published wheel's
  closure, but a fix is available so we take it.
- pydantic-settings 2.14.1 -> 2.14.2 (MEDIUM, GHSA-4xgf-cpjx-pc3j):
  NestedSecretsSettingsSource follows symlinks outside secrets_dir.
  Pulled via mcp (the [mcp]/[all] extra); graphify does not use the
  affected secrets-dir source, but the fix is free.

Lockfile-only; both are transitive. Full suite green (2537 passed),
MCP/serve tests pass on the bumped versions.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 11:26:29 +01:00
Ariadne MitophaneandClaude Opus 4.8 e3e4198038 fix(skillgen): host-generic /graphify install guidance (#1530)
Generated install/skill guidance told agents to invoke a literal `skill`
tool with `skill: "graphify"`, which is host-specific and not valid in
every environment. The always-on AGENTS fragment, packaged artifact,
expected snapshot, and _skill_registration() output now use host-generic
wording: "use the installed graphify skill or instructions". Also decodes
skillgen git blob reads as UTF-8 for Windows and replaces stale English
code-block examples in the translated READMEs.

The always-on roundtrip guard deliberately freezes the v8 baseline, so an
intentional wording change would otherwise fail it. Rather than only
patching the pytest mirror (which left the blocking CLI guard
--always-on-roundtrip red, as the original PR did), this adds an explicit,
reviewable ALWAYS_ON_SANCTIONED_EDITS registry: the guard applies the
approved old->new substitution to the baseline before the byte-for-byte
compare, so this exact sentence is allowed while any other drift still
fails. CLI guard and pytest test now agree and CI passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 10:01:06 +01:00
antonioscarinciandClaude Opus 4.8 407a7f142d fix(export,cli): GraphML null-attr coercion + save-result --answer-file (#1502)
Two cross-platform fixes salvaged from #1502:

- to_graphml: nx.write_graphml raises ValueError on None attribute
  values, so a node/edge carrying a null field crashed the export.
  Coerce None -> "" for node and edge attributes before writing.

- save-result: add --answer-file as an alternative to --answer so long
  or multiline answers can be passed via a file instead of a fragile
  inline shell arg (notably Windows/PowerShell quoting). Exactly one of
  --answer / --answer-file is required.

The rest of #1502 (a version downgrade and a hand-edited generated
skill-windows.md that fails skillgen --check, plus duplicated
windows-scripts) is left for rework on the PR.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 09:54:08 +01:00
DhruvTilvaandClaude Opus 4.8 4e4935a64a fix(llm): enforce API timeout in the secondary LLM dispatch path (#1442)
_call_llm (used by the dedup LLM tiebreaker) built its Anthropic and
OpenAI-compatible clients with max_retries but no timeout, so requests
on this path silently ignored GRAPHIFY_API_TIMEOUT — unlike the primary
extraction paths (_call_openai_compat / _call_claude) which already pass
both. Add timeout=_resolve_api_timeout() to both constructors.

The PR branch self-neutralized: a v8 merge resolved the conflict in
favor of the max_retries-bearing line and dropped the original one-line
fix, so it is re-applied here on top of current v8 with max_retries
preserved. Adds regression coverage for both _call_llm branches, which
were previously untested.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 09:45:03 +01:00
vamsi pavan mahesh gunturuandClaude Opus 4.8 86ecb769b6 feat(ruby): type-aware member-call resolution via a resolver framework (#1499)
Resolve Ruby `obj.method()` calls by the inferred type of the receiver
instead of by globally-unique method name. `p = Processor.new; p.run`
now emits a `calls` edge to `Processor#run` and survives name collisions
with unrelated `Worker#run` definitions, where the old name-based match
either resolved by luck or dropped the edge as ambiguous.

Introduces graphify/resolver_registry.py, a behavior-identical
formalization of the existing tail-of-extract() language resolution
passes (Swift #1356, Python #1446 become registered entries), and
graphify/ruby_resolution.py, its first new consumer. Receiver type is
inferred only from unambiguous local `var = ClassName.new` bindings;
ambiguous or unknown receivers resolve to nothing (no false positives).

Note: Ruby member calls are now excluded from name-based cross-file
resolution and resolved by inferred type only. This is an intentional
precision-over-recall change scoped to Ruby: a cross-file `var.method`
whose receiver type cannot be proven from a local `X.new` binding no
longer resolves by name-luck (it produces no edge rather than a possibly
wrong one), matching the project's confidence model.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 09:40:22 +01:00
safishamsiandClaude Opus 4.8 12193a89f1 chore: untrack committed .DS_Store files
These were committed before .gitignore included the .DS_Store rule, so
gitignore never removed them from tracking. Untrack them (they remain
on local disk, just leave git) — the existing .gitignore rule keeps
them out going forward.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 09:24:02 +01:00
safishamsiandClaude Opus 4.8 199061207f docs: add Discord badge to README
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 22:45:49 +01:00
safishamsiandClaude Opus 4.8 b7e256f779 release: 0.9.1
Patch over 0.9.0: completes the node-ID work (fully closes #1504 via injective
salt #1522), stops origin_file leaking into graph.json (#1516), extends cross-file
stub disambiguation to the six dedicated extractors (#1515), Java type-param skip
(#1518) + record component refs (#1519), prunes a deleted import's edge on update
(#1521), and retries rate-limited (429) requests instead of dropping chunks (#1523).
All non-breaking.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 20:15:44 +01:00
safishamsiandClaude Opus 4.8 0ca73bd00b docs: document GRAPHIFY_MAX_RETRIES env var (#1523)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 20:13:55 +01:00
safishamsiandClaude Opus 4.8 64c1f21070 fix(llm): retry rate-limited (429) requests instead of dropping the chunk (#1523)
On strict per-org concurrency/RPM caps (notably Moonshot/kimi), a parallel
`graphify extract --force` 429'd, and because the provider SDKs default to only
max_retries=2, the chunk gave up after two attempts, logged `chunk N failed`, and
was silently dropped — an incomplete graph plus the screen full of
rate_limit_reached_error spam in the report. The SDKs already back off
exponentially and honor Retry-After; they just need more attempts to outlast the
rate window.

The OpenAI-compatible, Azure, and Anthropic clients are now built with
max_retries=_resolve_max_retries() (default 6, override via GRAPHIFY_MAX_RETRIES;
0 disables). For very tight accounts, --max-concurrency 1 further cuts the
concurrency that trips org-level limits.

Reported by @bercedev (#1523). Tests: _resolve_max_retries default/env/invalid,
and the OpenAI-compatible client is constructed with retries.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 20:11:18 +01:00
safishamsiandClaude Opus 4.8 22a5afb251 docs(changelog): add #1521, #1522, #1519 entries
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:57:33 +01:00
oleksii-tumanovandClaude Opus 4.8 981e2b93cf fix(extract): emit Java record component references (#1519)
A Java record's component types produced no edges, so a record's data dependencies
were invisible. The record_declaration handler now emits `references` edges from
each component type (field context; generic_arg for type arguments), skipping
primitives and — via #1518's in-scope type-parameter filtering — the record's own
type parameters. Handles standard, generic, primitive, and varargs components.

Ported from PR #1520 by @oleksii-tumanov (clean 3-way onto v8; builds on #1518).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:55:51 +01:00
safishamsiandClaude Opus 4.8 35fb437365 fix(ids): salt residual separator-collision node IDs injectively (#1522)
0.9.0 made the node-ID stem the full repo-relative path, but normalize_id collapses
every non-word run to "_", so the path separator is indistinguishable from inner
punctuation: foo/bar_baz.py and foo_bar/baz.py both normalized to foo_bar_baz and
still silently merged (the residual of #1504). The existing _disambiguate_colliding
_node_ids salt didn't help — it salted with _make_id(source_key, old_id), which
re-normalizes the path with the same lossy recipe, so the two colliders produced an
identical salted id.

When two distinct source paths' naive salts still collide, append a short stable
sha1(source_key)[:6] — injective over distinct paths — so they separate. Computed in
code from source_file (never trusted from the LLM), so AST<->semantic parity holds.

Blast radius: minimal/non-breaking — only the actual residual colliders get a hash
suffix. Non-colliding ids (the 99%, incl. the common #1504 case like two README.md
in different dirs) are byte-identical to 0.9.0 (verified: src/auth/session.py ->
src_auth_session, docs/v1/api/README.md -> docs_v1_api_readme unchanged). This is a
0.9.1 patch, not another migration.

Reported by @sub4biz (#1522). Regression tests cover both the collider-separation
and the non-collider-unchanged cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:54:48 +01:00
safishamsiandClaude Opus 4.8 0080d8ac43 fix(update): prune edges owned by a re-extracted file (#1521)
`graphify update` preserved old edges keyed only on endpoint-node membership, so a
removed import's edge survived forever whenever both endpoint nodes still existed
(e.g. a.py no longer imports b, but both a and b are still present). The stale edge
drove phantom circular-dependency findings; `--force` didn't help (it only gates
the node-count shrink guard), only a clean rebuild did.

_rebuild_code (watch.py) now also drops preserved edges whose source_file was
re-extracted this run — an edge is owned by the file it was extracted from, and the
fresh extraction re-emits whichever ones still exist. Scoped to source_file
ownership (and the full-rebuild case, where evict_sources lists only deleted
files), so edges with no source_file or owned by a non-re-extracted file are kept —
cross-file edges that merely point at a re-extracted file (#1402 sourceless
stubs/rewire) are not over-pruned.

Reported by @UltronOfSpace (#1521). Regression test: a removed import's edge is
gone after update; verified no over-prune (still-present imports survive) and no
regression to deleted-file pruning.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:29:51 +01:00
safishamsiandClaude Opus 4.8 faa9218907 chore: sync uv.lock to 0.9.0
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:06:28 +01:00
safishamsiandClaude Opus 4.8 67d8c53ccc docs(changelog): add #1515 and #1518 entries to Unreleased
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:05:09 +01:00
oleksii-tumanovandClaude Opus 4.8 8b9a99828a fix(extract): skip Java type-parameter references (#1518)
The generic-parent support (#1511) emitted a spurious references/generic_arg edge
(and a sourceless stub node) for a bare type parameter — the T in
`class Box<T> extends Container<T>` — because the Java extractor had no type-
parameter tracking. _java_collect_type_refs now collects the in-scope type-
parameter names (walking class/interface/record/method/constructor declarations,
including bounded and multiple params) and skips references to them, while keeping
every real type. Scoped to the declaring node, so a real class that shares a name
with a type parameter elsewhere is still referenced.

Ported from PR #1518 by @oleksii-tumanov. Closes the nit flagged when #1511 landed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:05:09 +01:00
Mohammed AteeqandClaude Opus 4.8 d177f04270 fix(extract): add origin_file to cross-file stubs in the six dedicated extractors (#1515)
The #1462 same-label cross-file stub disambiguation (the origin_file key) only
existed in the generic extractor, so the six dedicated extractors — Julia,
Fortran, Go, Rust, PowerShell, ObjC — still collapsed same-named imported-type
stubs from different files into one conflated bare-id node (a false cross-package
link). Each now sets origin_file on its sourceless stub, identical to the generic
extractor; the generic _node_disambiguation_source_key consumes it, so two files
importing the same type stay distinct while source_file stays empty (the #1402
rewire onto a real definition is unchanged).

Ported from PR #1515 by @TPAteeq. Must ship with #1516: this widens origin_file to
six more languages, and #1516 is what strips it from graph.json. Verified: a 2-file
Go corpus now yields 2 distinct Widget stubs AND graph.json carries no origin_file.
Resolved a test-insertion conflict with #1516 by keeping both tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 19:01:55 +01:00
Mohammed AteeqandClaude Opus 4.8 afa4aded2e fix(extract): drop internal origin_file so it stops leaking into graph.json (#1516)
The origin_file disambiguation field (#1462) is internal — it's consumed by the
colliding-id pass and must not be persisted. In 0.9.0 it shipped into graph.json
as an absolute, machine-specific path (the same portability bug class as #555,
#932), breaking on clone/move. It's now popped at the single extract() output
chokepoint, AFTER _disambiguate_colliding_node_ids has consumed it, so all persist
paths (clustered, --no-cluster, cluster-only) emit clean output. _origin is kept
(the incremental watcher relies on it, #1116).

Ported from PR #1516 by @TPAteeq. Verified: fresh extract (clustered and
--no-cluster) produces graph.json with zero origin_file fields; the #1462 same-
label disambiguation still works (it runs before the strip).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 18:54:58 +01:00
safishamsiandClaude Opus 4.8 94e5bafc89 docs: document the --timing flag in the extract examples (#1490)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 18:28:31 +01:00
safishamsiandClaude Opus 4.8 92e682f1de release: 0.9.0
BREAKING: node IDs now include the full repo-relative path (#1504, #1509) — fixes
silent data loss when same-named files live in different directories, and aligns
the AST and LLM id rules. Existing graphs migrate automatically on next build;
`graphify extract --force` to recover previously-collided nodes; Neo4j persisted
stores need a re-import. Also ships the --timing flag (#1490).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 18:20:10 +01:00
safishamsiandClaude Opus 4.8 73710d33ce fix(ids): legacy-id detector only inspects file-level nodes (no Go false-positive)
The graph_has_legacy_ids nudge flagged fresh v9 graphs that contain Go code,
because the Go extractor scopes a type node by package directory
(_make_id(pkg_dir, name) -> "sub_thing"), which coincides with the OLD one-parent
file-stem form of pkg/sub/thing.go even though it's a current, by-design
package-scoped id (methods on a type across files in a package share one node).

The detector now inspects only file-level nodes (source_location "L1"), whose id is
unambiguously the file stem and which the migration actually re-keys. This still
catches a genuine pre-#1504 graph (its file nodes carry the old stem) while leaving
package/dir-scoped symbol ids alone. Verified end-to-end: a fresh Go graph no longer
triggers the rebuild nudge; a real legacy graph still does.

The migration itself was already correct — file nodes and Python/AST symbols
migrate to full-path ids; Go's package-scoped type ids are intentional and
unaffected. This only fixes the over-eager warning.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 17:52:34 +01:00
safishamsiandClaude Opus 4.8 3999dbc67e feat(ids): warn on legacy-id graphs + harden re-key source_file contract (#1504)
Two pre-0.9.0 safety to-dos from the migration spike:

1. Auto-detect-and-warn: graph_has_legacy_ids() samples a loaded graph's node ids
   and detects the pre-#1504 (parent-dir/filename) scheme. Read-only consumers that
   don't re-extract — `graphify query` and the MCP serve loader — now print a
   one-line nudge to rebuild with `extract --force` when they load an old graph.
   Fires only on legacy graphs (verified: canonical graphs stay silent).

2. Re-key source_file contract: pinned with tests that a relative source_file is
   migrated to the full-path id while an absolute/unrelativizable one is skipped
   (its on-disk path must never leak into a persisted id). The is_absolute() guard
   already enforced this; the tests make the contract explicit.

Full suite 2507 passed. Lands on v9.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 17:29:57 +01:00
safishamsiandClaude Opus 4.8 388d1b64db docs(changelog): clarify --force is needed to recover previously-collided nodes (#1504)
Rigorous testing surfaced the nuance: the ID-format migration is automatic, but
same-named files that already collapsed into one node under the old rule are only
recovered as distinct nodes by a fresh extract --force (migrating an already-
collided graph/cache can't resurrect already-dropped nodes; edges referencing a
shared old id are ambiguous). Fresh extraction yields distinct nodes as expected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 17:12:30 +01:00
safishamsiandClaude Opus 4.8 b46634ef7a fix(ids): node IDs include the full repo-relative path (#1504, #1509)
BREAKING node-ID format change. The stem that prefixes every node id was the
immediate parent dir + filename, so same-named files in different directories
collided into one last-writer-wins node and silently dropped graph content
(docs/v1/api/README.md and docs/v2/api/README.md both -> api_readme). The stem is
now the full repo-relative path (docs_v1_api_readme vs docs_v2_api_readme);
top-level files are unchanged (setup.py -> setup).

- extractors/base.py::_file_stem -> full path (as_posix; make_id collapses
  separators). The two hand-copied stems (symbol_resolution, mcp_ingest) now
  import the canonical one, so they can't drift again.
- llm.py system prompt + extraction-spec fragments aligned to the same rule,
  fixing the #1509 AST<->LLM divergence (prompt used zero parent dirs -> ghosts).
  Regenerated + blessed the per-host specs.
- build_from_json deterministically re-keys every non-AST node id from its
  source_file via the new stem (and registers old-stem aliases), so a cached or
  pre-migration semantic fragment carrying an old short id reconciles with the
  AST node instead of spawning a ghost. The semantic cache is unversioned, so
  this code-side re-key (not LLM prose) is what makes it survive the format change
  with no re-bill. AST nodes are already canonical and skipped.
- Migration: existing graphs migrate automatically on the next build/update (the
  re-key runs in build_from_json, including the whole graph fed back through
  build_merge); `graphify extract --force` for a clean rebuild. Neo4j persisted
  stores need a re-import; GraphML layouts go stale.

Full suite green (2505 passed); #1504 collision fixed and old-id fragments
re-keyed verified by smoke. Lands on v9 for review before a 0.9.0 release.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 16:57:00 +01:00
safishamsiandClaude Opus 4.8 21a9f1f0b5 chore: sync uv.lock to 0.8.51
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 16:49:56 +01:00
safishamsiandClaude Opus 4.8 f7f89d7d84 feat(cli): --timing flag for per-stage timings on extract and cluster-only (#1490)
Adds an opt-in --timing flag that prints per-stage wall-clock timings to stderr so
slow stages are visible on large corpora. extract reports detect / AST extract /
semantic extract / build / cluster / analyze / export (and write on --no-cluster);
cluster-only reports load / cluster / analyze / label / report / export; both end
with a total. A small _StageTimer helper uses monotonic perf_counter.

Off by default and stderr-only, so default output and machine-read stdout/graph.json
are byte-identical (the extract arg loop already swallows unknown flags). Added a
regression test asserting the lines appear with --timing and are absent without it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 16:17:21 +01:00
safishamsiandClaude Opus 4.8 7592244386 docs: document --obsidian-dir and its existing-vault safety (#1506)
The --obsidian-dir flag was undocumented in the README. Add it to the command
list with a note that exporting into an existing vault never overwrites the user's
own notes or .obsidian config (the guard shipped in 0.8.51).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 11:33:36 +01:00
safishamsiandClaude Opus 4.8 8e98b916f4 release: 0.8.51
Dates the 0.8.51 CHANGELOG and bumps the version. Highlights: Obsidian export no
longer overwrites user notes / .obsidian config in an existing vault (#1506);
cross-file node-ID cluster fixes — C# resolver (#1466), Go sourceless stubs
(#1500), import-stub disambiguation (#1462); Java enum/annotation type nodes
(#1512) + generic parents (#1510); explain/affected source-file path lookup
(#1503); claude-cli Windows GBK fix (#1505); macOS install docs (#1471) and the
global-add docs fix (#1489).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 11:20:23 +01:00
safishamsiandClaude Opus 4.8 8b177cb33d fix(export): don't overwrite user notes or .obsidian config in an existing vault (#1506)
to_obsidian wrote one note per node straight into the target directory and
unconditionally replaced .obsidian/graph.json. Pointing --obsidian-dir at a real
vault could therefore clobber a user note whose name matched a graph node
(Database.md) and destroy the user's graph-view settings — silently, no backup,
irreversible.

graphify now records the files it owns in .graphify_obsidian_manifest.json and
refuses to overwrite any pre-existing file it didn't create: such a file is skipped
and reported in a single aggregated warning. A re-run still updates graphify's own
notes (they're in the manifest), and .obsidian/graph.json is only written when it
doesn't already exist or graphify owns it. The default graphify-out/obsidian output
and the flat note layout are unchanged.

Added regression tests: existing-vault preserves user note + .obsidian settings,
empty dir still gets the full vault, and a re-run updates own notes but not a
user-added file. The CHANGELOG also records the @oleksii-tumanov Java fixes
(#1512/#1510) and the @nuthalapativarun Windows GBK fix (#1505) committed just prior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 10:56:39 +01:00
nuthalapativarunandClaude Opus 4.8 0e8d92cf5f fix(llm): tolerate non-UTF8 claude-cli output on Windows GBK systems (#1505)
On Windows where claude.cmd emits GBK/cp936 bytes, the claude-cli subprocess
decoding raised UnicodeDecodeError and crashed extraction. Both claude-cli
subprocess.run sites (_call_claude_cli and the claude-cli branch of _call_llm) now
pass errors="replace", so incidental non-UTF8 console chatter decodes to
replacement chars instead of crashing — the structured JSON payload (ASCII/UTF-8
on stdout) is unaffected. capture_output=True means the single errors= covers both
stdout and stderr.

Ported from PR #1507 by @nuthalapativarun (dropped an unrelated .gitignore change).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 10:32:57 +01:00
oleksii-tumanovandClaude Opus 4.8 1f3f1c1ca6 fix(extract): emit Java generic parent relationships (#1510)
A generic parent — `class Foo extends Bar<T>` or `implements List<T>` — is a
`generic_type` node in the tree, but the inheritance extractor only fired on a
bare `type_identifier`, so those inherits/implements edges were silently dropped.
The parent type is now unwrapped to its base (`Bar<T>` -> `Bar`) for the
inherits/implements edge, and the type arguments are emitted as `generic_arg`
references.

Ported from PR #1511 by @oleksii-tumanov. Known pre-existing limitation (not
introduced here, worth a separate follow-up): the extractor has no type-parameter
tracking, so a bare parameter like `T` in `extends Container<T>` still produces a
`generic_arg` reference to `T`; the inherits/implements edge itself always targets
the real base type, never `T`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 10:31:57 +01:00
oleksii-tumanovandClaude Opus 4.8 940cb53f4d fix(extract): emit Java enum and annotation declarations as type nodes (#1512)
Java `enum` and `@interface` (annotation) declarations weren't in _JAVA_CONFIG's
class_types, so they were never emitted as type nodes — a field typed as an enum or
a class annotated with a project annotation referenced a node that didn't exist
(dangling). enum_declaration and annotation_type_declaration are now extracted as
first-class (sourced) type nodes, so those references resolve onto them.

Ported from PR #1513 by @oleksii-tumanov.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 10:31:22 +01:00
behavio1andClaude Opus 4.8 1b994965bb fix: resolve explain/affected when a source-file path matches multiple nodes (#1503)
A path query like `explain "app/api/route.ts"` tokenized to terms that matched no
node, so explain/affected returned "No node matching". Source-file paths are now
part of the search index and matched exactly (serve._find_node gains a leading
source-exact tier; affected.resolve_seed gains a source-file match). When several
nodes share a source_file (e.g. a file-level node plus a function node), the lookup
prefers the file-level node — the L1 node whose label basename matches the queried
filename, falling back to the unique L1 or unique basename match, else None.

Ported from PR #1503 by @behavio1. Maintainer fixes on top: aligned trailing-
separator handling between resolve_seed and _find_node (affected previously
returned None for a trailing-slash path that explain resolved), corrected the
stale "three-tier" _find_node docstring, and added regression tests for the
trailing-slash parity and the ambiguous-no-file-node -> None case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 23:57:39 +01:00
Mohammed AteeqandClaude Opus 4.8 11dc819c3f docs(install): uv tool PATH setup + uvx --from graphifyy for macOS (#1471)
Documents two expected uv behaviors that read as bugs on macOS: (1) uv tool
install puts `graphify` in ~/.local/bin which a fresh zsh shell may not have on
PATH (run `uv tool update-shell`); (2) `uvx graphify` fails because the package is
`graphifyy` and `graphify` is only its console script — use
`uvx --from graphifyy graphify install`. README install note + Troubleshooting.

Ported from PR #1474 by @TPAteeq. Maintainer fix on port: moved the CHANGELOG
entry from the already-released 0.8.50 block (where the stale base placed it) into
the current Unreleased section.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 23:55:14 +01:00
Michael KatsoulakisandClaude Opus 4.8 1225677b8a docs: fix graphify global add example (#1489)
The README showed `global add graph.json myrepo` (positional tag) writing to
`~/.graphify/global.json`. The real CLI takes the tag via `--as` (the positional
was silently ignored) and the file is `~/.graphify/global-graph.json`. Corrected
to `global add graph.json --as myrepo`.

Ported from PR #1489 by @MikeKatsoulakis.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 23:53:50 +01:00
safishamsiandClaude Opus 4.8 6a45263bc0 chore: sync uv.lock to 0.8.50
The lockfile's own package version trailed the pyproject bump; uv regenerated it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 23:43:35 +01:00
jiangyq9andClaude Opus 4.8 6509d0ca6f fix(extract): disambiguate imported type stubs across files without blocking rewire (#1462)
Two files that both import and use the same type as a bare name (e.g.
`from pathlib import Path` used as a type hint in a.py and b.py) collapsed into one
node, even with no project definition to anchor them. The referencing file is now
recorded in an internal `origin_file` field and used as the disambiguation key when
_disambiguate_colliding_node_ids splits same-id nodes — while source_file stays
empty, so the corpus-level rewire still collapses these stubs onto a real project
definition when one exists (the #1402 path is untouched). origin_file is read only
inside disambiguation; the rewire and the Java/C# type resolvers key off
source_file as before.

Ported from PR #1479 by @jiangyq9 (squash-merged onto current v8; the branch's
stale base made the raw diff appear to revert later features — the 3-way merge
applies only the surgical origin_file change). Resolved a test-adjacency conflict
with #1500 by keeping both cross-file tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 23:38:26 +01:00
TheFedaikinandClaude Opus 4.8 76b6eabdb0 feat(extract): resolve C# cross-file type references + enum/struct/record (#1466)
Adds _resolve_csharp_type_references (graphify/extractors/csharp.py), the C#
counterpart to _resolve_java_type_references. It re-points dangling
inherits/implements/references edges from no-source shadow stubs onto the real
definitions, disambiguating same-named types across namespaces using the
referencing file's `using` directives + enclosing namespace; ambiguous matches
are refused (unique-hit guardrail), not guessed. Runs after id-disambiguation and
the sourceless-stub rewire, on the ambiguous remainder, behind a log-and-skip
try/except. _CSHARP_CONFIG is broadened to extract enum/struct/record as type
definitions so references to them resolve too.

Ported from PR #1466 by @TheFedaikin. Known follow-up: types declared in
nested/multiple namespaces in one file aren't registered as targets yet (fails
safe — under-resolves to a stub, never mis-resolves). Advances #1318 for C#.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 23:36:47 +01:00
Mohammed AteeqandClaude Opus 4.8 36b76ce8e0 fix(extract): Go cross-file type refs emit sourceless stubs (#1500)
Go's ensure_named_node emitted a SOURCED stub for a cross-file type reference,
unlike the generic/ObjC/Java extractors which emit sourceless ones. A sourced stub
bakes the referencing file's path into the node id at disambiguation time, which
blocks the corpus-level rewire from collapsing it onto the real definition — so a
type defined in one Go file and referenced from two others produced three nodes
(the real def plus two phantom per-file duplicates). Go now emits a sourceless
stub like the other languages, so the rewire collapses them to a single node.

Ported from PR #1501 by @TPAteeq. Closes the #1402 gap for Go.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 23:32:55 +01:00
safishamsiandClaude Opus 4.8 b17e88cc49 release: 0.8.50
Dates the 0.8.50 CHANGELOG and bumps the version. Highlights: WPF/XAML extraction
+ ViewModel/binding links (#1460/#1473), Objective-C relationship fixes (#1475),
.vue SFC grammar fix (#1468), Metal shader indexing (#1480), Java field/annotation
references (#1485/#1487), portable wiki links (#1444), *_BASE_URL backend overrides
(#1458), non-streaming OpenAI-compatible calls (#1223), reflect --if-stale sidecar
freshness (#1470), label --missing-only (#1481), canvas grid + case-fold dedup
(#1452/#1453), the Read|Glob hook extension fix (#1463), and the no-API-key skill
clarification (#1461).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:26:04 +01:00
jiangyq9andClaude Opus 4.8 a16b5bd151 feat(label): add --missing-only flag for incremental community naming (#1481)
`graphify label --missing-only` restricts LLM labeling to communities that are
unnamed or still hold a `Community N` placeholder, preserving existing
non-placeholder labels read from .graphify_labels.json and merging new labels over
them. Lets a large graph be relabeled incrementally without re-naming (and paying
for) communities that already have good names.

Ported from PR #1481 by @jiangyq9. This supersedes the earlier #1421 by
@matiasduartee, which proposed the same flag — credit to @matiasduartee for the
original; #1481 is written against the current label signature (post-#1390
max-concurrency/batch-size) and merges clean, where #1421 had drifted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:19:15 +01:00
jiangyq9andClaude Opus 4.8 652ba42e61 feat(extract): index Metal (.metal) shader files (#1480)
Metal Shading Language is C++14, so .metal files are classified as code and routed
through the existing C++ extractor, mirroring the CUDA .cu/.cuh reuse. Also adds
.cu/.cuh/.metal to build.py's _LANG_FAMILY map (they were all missing), so the
cross-language phantom-`calls`-edge filter treats them as C++. README language
table updated.

Ported from PR #1480 by @jiangyq9. This supersedes the earlier #1450 by
@GoodOlClint (same .metal -> C++ approach and fixture) — credit to @GoodOlClint
for the original; #1480 additionally closes the CUDA family-map gap and updates
the docs, and merges clean against current v8.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:19:15 +01:00
Mohammed AteeqandClaude Opus 4.8 7a94f72779 fix(wiki): portable relative markdown links so navigation works outside Obsidian (#1444)
to_wiki emitted Obsidian `[[Title]]` wikilinks. Outside Obsidian `[[Domain Data
Models]]` resolves to a literal "Domain Data Models.md", but the article file is
the slugged "Domain_Data_Models.md", so nearly every community/god-node link
opened an empty page; god-node articles also linked node-level neighbors that
never get an article file, so those were dead even inside Obsidian.

Links are now standard `[display](slug.md)` with the target URL-encoded (spaces,
&, parentheses, # survive in CommonMark and Obsidian alike); a link whose target
has no article is rendered as plain text instead of left dangling. A label->slug
resolver is built up front so a link points at the real on-disk filename incl. the
case-fold collision suffix.

Ported from PR #1465 by @TPAteeq. Maintainer edit: trimmed the CHANGELOG wording
that overstated the guarantee ("always matches ... collision suffix and all") —
two articles sharing a byte-identical label still keep the first slug (pre-existing
behavior, same as the old [[label]]), so the claim is scoped to the case-fold case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:19:15 +01:00
jiangyq9andClaude Opus 4.8 ff47316b8a fix(llm): force non-streaming on OpenAI-compatible calls (#1223)
Some OpenAI-compatible gateways default to SSE streaming when `stream` is omitted,
but graphify always reads the result as a single resp.choices[0]. The call would
then fail against those gateways. Pass `stream: False` explicitly.

Ported from PR #1482 by @jiangyq9 (covers the extraction dispatch path,
_call_openai_compat). Maintainer fix on top: applied the same `stream: False` to
the second OpenAI-compatible call site, _call_llm, which feeds the --dedup-llm
tiebreaker and had the identical bug.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:19:15 +01:00
oleksii-tumanovandClaude Opus 4.8 9b49bfd9eb fix(extract): emit references for Java type annotations (#1487)
Annotations on Java classes/interfaces/records (e.g. @Service, @Entity) produced
no edge, so type-level framework wiring was invisible even though method-level
annotations were already captured. The class/interface/record handler now emits
`references` edges with the existing `attribute` context, reusing the renamed
`_java_annotation_names` helper (was `_java_method_annotation_names`; logic
unchanged) at both the type and method call sites.

Ported from PR #1487 by @oleksii-tumanov. Resolved an additive test conflict with
#1485 by keeping both new test functions.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:19:15 +01:00
oleksii-tumanovandClaude Opus 4.8 31b3752902 fix(extract): emit references for Java field types (#1485)
Java field declarations produced no `references` edge for their type, so a class's
data dependencies (its field types) were missing from the graph even though
parameter and return types were already captured. The field handler now collects
the declared type via the same `_java_collect_type_refs` helper used elsewhere,
preserving the `field` and `generic_arg` contexts and skipping primitives
(int/boolean/etc.), matching the existing C#/PHP/Kotlin field handlers.

Ported from PR #1485 by @oleksii-tumanov.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:19:15 +01:00
safishamsiandClaude Opus 4.8 8994b5500c fix(extract): recover dropped Objective-C relationships (#1475)
A detailed report (#1475) showed the ObjC extractor silently dropping ~60% of
code-level relationships. Five fixes:

1. Dispatch: ObjC `.h` headers were parsed by extract_c (1 node, 0 edges, losing
   every @interface/@protocol/@property/method). _get_extractor now routes a `.h`
   to extract_objc when it contains an ObjC-only directive
   (@interface/@protocol/@implementation/@import) — these are illegal in C/C++, so
   the sniff never hijacks a genuine C/C++ header (verified: a plain C/C++ `.h`
   stays on its existing extractor).

2. Calls: the method-body pass produced zero `calls` edges because it matched
   child types `selector`/`keyword_argument_list`, but tree-sitter-objc tags
   selector parts with the field name `method` (type `identifier`). The selector
   is now reconstructed from every `method`-field child, explicitly skipping the
   `receiver` field — so self/super/ClassName receivers are never mistaken for a
   selector, and compound sends ([self a:x b:y]) resolve too. (Avoids the report's
   suggested `"identifier"` fix, which would have matched receivers as selectors.)

3. Generic property types: NSArray<Product *> * wraps the type in a
   generic_specifier, so the old direct-type_identifier scan saw nothing. The
   element (Product) and container (NSArray) are now both referenced.

4. Class methods: `+ (…)shared` was labeled -shared; the +/- sigil is now read
   from the method node's first child.

5. @import: `@import Foundation;` (a module_import node) now emits an imports edge.

Dot-syntax property `accesses` (Bug 5) and @selector(...) target-action edges
(Bug 6b) need type/name resolution policy and are left as follow-ups. Added six
regression tests; the reporter's claim that compound messages lack a
message_expression wrapper (Bug 6a) was checked against the real AST and refuted —
they share Bug 2's root cause, fixed by the same field-name change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 18:08:11 +01:00
Michael KatsoulakisandClaude Opus 4.8 905e0a7a2e feat(extract): link XAML views to ViewModels and extract binding references (#1473)
Builds on the initial XAML support (#1460). Resolves a view to its ViewModel from
an explicit <Window.DataContext><vm:MainViewModel/>, a design-time
d:DataContext="{d:DesignInstance Type=...}", the View->ViewModel naming
convention, or Prism ViewModelLocator.AutoWireViewModel="True". Resolution is
always against an actually-extracted C# class node, so a name matching no class
(or an ambiguous 2+) emits no edge -- explicit DataContext is EXTRACTED,
convention/Prism are INFERRED. Also extracts binding paths ({Binding User.Name},
Path=Order.Total), commands (Command="{Binding SaveCommand}"), converters, and
CommunityToolkit [ObservableProperty]/[RelayCommand] generated members.

The #1460 event-handler hardening is preserved unchanged: events still resolve
only to methods with a .NET (object sender, ...EventArgs e) signature, and the
free-form-attribute denylist still prevents values like Content="Save" from
fabricating event edges (both regression tests still pass). ViewModel discovery is
bounded to the active extraction root.

Ported from PR #1473 by @MikeKatsoulakis (clean 3-way merge onto current v8).
Maintainer fix on top: the CommunityToolkit member reader now reads the
code-behind with errors="replace", so a non-UTF8 ViewModel .cs can't raise
UnicodeDecodeError and abort extract_xaml (matches every other reader in the
module). Added a regression test for that case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 10:23:10 +01:00
papintoandClaude Opus 4.8 349465b8af fix(extract): parse .vue SFC <script> with the right grammar (#1468)
.vue files were dispatched to extract_js, which picks a tree-sitter grammar by
suffix. .vue is neither .ts nor .tsx, so the whole SFC -- <template> markup,
<script>, and <style> -- was fed to the JavaScript grammar, producing a top-level
ERROR node and recovering no imports, symbols, or type references.

A dedicated extract_vue masks everything outside <script> (replacing it with
spaces so symbol line numbers stay accurate) and parses just the script with the
grammar named by `lang` (ts default; tsx/js/jsx honored). .vue also joins the
cross-file symbol-resolution pass now that it parses cleanly.

Ported from PR #1468 by @papinto. Maintainer fix on top: the <script> open-tag
scan now skips over quoted attribute values, so a `>` inside one (Vue 3.3+ generic
components, e.g. generic="T extends Record<string, unknown>") no longer ends the
tag early and swallow the body. Added a regression test for that case.

(CHANGELOG also records #1470, committed just prior.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 10:20:53 +01:00
oleksii-tumanovandClaude Opus 4.8 75a5e6d5ff fix(reflect): include analysis/labels sidecars in --if-stale freshness check (#1470)
graphify reflect renders LESSONS.md from the memory docs and the
.graphify_analysis.json / .graphify_labels.json sidecars, but reflect --if-stale
only stat'd the memory docs and graph.json. So after community analysis or labels
changed (without the graph changing), --if-stale wrongly reported lessons fresh and
skipped the regen, leaving LESSONS.md stale. The freshness check now also stats the
analysis and labels sidecars, using the same custom --analysis / --labels paths the
run itself uses (so the check and the run can't disagree about which files matter),
and treats a missing sidecar as not-an-input. This makes the documented "no-op when
LESSONS.md is newer than every input" contract actually true.

Ported from PR #1470 by @oleksii-tumanov.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 10:09:52 +01:00
marketechniksandClaude Opus 4.8 9b583a0dd5 fix(hooks): match the real file extension in the Read|Glob hook (#1463)
The Read|Glob PreToolUse hook (the "run graphify first" nudge, shared by the
Claude Code and CodeBuddy installers via _READ_SETTINGS_HOOK) decided whether to
nudge by substring-scanning the joined file_path/pattern/path for known
extensions. That had two opposite failures: '.js' is a substring of '.json' so
package.json / tsconfig.json spuriously fired, and .astro/.vue/.svelte weren't in
the set so Astro/Vue/Svelte projects never nudged on their primary source type.

The hook now compares each value's real trailing extension (segment after the
last '/', then after the last '.') against the set, and adds .astro/.vue/.svelte.
package.json -> tail .json (silent); **/*.astro -> tail .astro (fires); an
extension on a directory component (my.ts/file) correctly stays silent. The
graphify-out/ suppression and fail-open behavior are unchanged.

Ported from PR #1464 by @marketechniks onto current v8. Added three regression
tests on top of the PR's (multi-dot a.test.tsx / foo.min.js, a Windows backslash
path, and the directory-extension trap) to pin the trickiest parts of the new
segment-split logic.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 20:33:00 +01:00
safishamsiandClaude Opus 4.8 1e3270a374 fix(skill): state up front that no API key is required, with a non-subagent fallback (#1461)
Hermes and the other AGENTS.md hosts (Codex, Aider, OpenClaw, Droid, Trae, ...)
run the graphify CLI directly and do not dispatch subagents. The Step 3 extraction
guidance only described the no-API-key path as "fall straight through to subagent
dispatch", so on `/graphify .` those agents had no path they could take, fixated on
the GEMINI/ANTHROPIC key language, and looped for minutes insisting on a missing key
before eventually proceeding (a pure-code corpus is AST-only and needs no key at all).

Step 3 now opens with a hoisted, host-agnostic statement -- graphify needs no API
key, never prompt for one, never block on one; code is AST-only; a code-only corpus
skips semantic extraction entirely -- and the no-key fallback now spells out a
terminal-only path (write the empty semantic file and continue, or extract content
inline) instead of assuming subagent dispatch.

Applied in the shared core fragment and in the aider/devin core variants, so all 16
skill bodies carry it; the aider/devin change is registered as a sanctioned
monolith-roundtrip diff. Regression test (test_extraction_states_no_api_key_required_
for_every_host) renders every host and pins the wording, ordering, and the
non-subagent fallback so this can't silently regress.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 14:05:34 +01:00
Michael KatsoulakisandClaude Opus 4.8 7dc5d968a3 feat(extract): WPF/XAML structural extraction with code-behind bridge (#1460)
Makes .xaml a first-class code input. extract_xaml() uses stdlib XML (no new
parser dependency) behind the same DOCTYPE/ENTITY and size guards as the .csproj
extractor, and captures: the root element, named controls (x:Name/Name) and their
control types, {Binding ...} references, x:Class, and -- the useful part -- a
bridge from the view markup to its .xaml.cs code-behind by resolving event-handler
attributes to the matching methods on the partial class.

Ported from PR #1460 by @MikeKatsoulakis onto current v8.

Maintainer hardening on top of the original PR: event resolution is now gated so
it can't fabricate edges. The original matched any attribute value against
code-behind method names, so Content="Save" next to a business method Save(), or
Tag="<a-handler-name>", produced spurious "event" edges. Resolution now requires
(a) the attribute is not a known free-form/identity property (Content, Text, Tag,
Title, ToolTip, Header, ...), (b) the value is a bare identifier, and (c) the
matched method actually has the .NET event-handler signature
(object sender, <T>EventArgs e) -- read from the code-behind source since the C#
extractor does not record parameter lists on method nodes. Added regression tests
for both false-positive cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 13:00:47 +01:00
jc2shileandClaude Opus 4.8 68dba89a99 feat(llm): honor *_BASE_URL for kimi/gemini/deepseek backends (#1458)
The kimi, gemini, and deepseek backends hardcoded their base_url, so users
behind an OpenAI-compatible proxy/gateway or running a self-hosted relay had no
way to redirect them (unlike ollama/openai, which already read *_BASE_URL). Each
backend now reads KIMI_BASE_URL / GEMINI_BASE_URL / DEEPSEEK_BASE_URL and falls
back to its official default when unset, so behavior is unchanged for anyone who
doesn't set the variable.

Ported from PR #1458 by @jc2shile onto current v8. The PR branch carried 624
unrelated files from a stale base; this lands just the clean 16-line llm.py
change. Added subprocess-based tests covering both the override and the default
for all three backends (BACKENDS reads the env at import time, so each case runs
in a fresh interpreter).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 12:31:19 +01:00
Mohammed AteeqandClaude Opus 4.8 7278e24d8a fix(export): lay out canvas node cards in the box's sqrt(n)-column grid (#1452)
to_canvas sized each community group box for a ceil(sqrt(n))-column grid but the
placement loop hardcoded 3 columns, so any community bigger than ~9 members
rendered as a cramped 3-wide strip in an over-wide, mostly-empty box (and the box
width/height didn't even agree — w used sqrt(n), h used /3). The column count is
now computed once per community (inner_cols) and reused for box width, box height,
and card placement, so the cards fill the box. Cosmetic, no data change.

Ported from PR #1459 by @TPAteeq onto current v8 (clean: only the grid math
changed, the #1457 dedup helper is untouched). Verified the geometry on a real
canvas: n=25 -> 5x5 grid with every card inside its box; n=10 -> 4 columns.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 12:26:10 +01:00
Mohammed AteeqandClaude Opus 4.8 5d63aad596 fix(export): case-fold filename dedup so case-only labels don't overwrite (#1453)
to_obsidian / to_canvas / to_wiki keyed filename dedup on the exact-case name,
so two labels differing only by case (e.g. `References` vs `references`) counted
as non-colliding and the second write clobbered the first on case-insensitive
filesystems (macOS/APFS, Windows/NTFS) — silently, no suffix, no warning.

Dedup now folds case (keyed on the lowercased name) while emitting the
original-case filename, so any pair that would collide on disk gets a numeric
suffix. The obsidian/canvas dedup is one shared helper (`_dedup_node_filenames`)
so they can't drift; wiki's slug dedup gets the matching fix; the `_COMMUNITY_*`
overview notes (which had no dedup at all) are covered; and a generated `base_1`
is re-checked so it can't overwrite a node literally labelled `base_1`.

Ported from PR #1457 by @TPAteeq onto current v8. Verified with a rigorous
edge-case battery (case-only collision, base_1 literal re-check -> base_1_1,
community-label case fold, determinism) plus the PR's tests; full suite 2404
passed, ruff + skillgen clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 10:41:46 +01:00
safishamsiandClaude Opus 4.8 e4ff54f4e0 docs(changelog): present 0.8.49 changes directly (drop internal packaging note)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 10:24:58 +01:00
safishamsiandClaude Opus 4.8 6d3c9594e3 Release 0.8.49 — fix wheel packaging for graphify.extractors
0.8.48 added graphify/extractors/ (the per-language split, #1212) but
[tool.setuptools] packages listed only "graphify", so the subpackage was
omitted from the wheel and `graphify extract` raised ModuleNotFoundError on a
fresh install. Editable/dev installs and the test suite import from the source
tree, so it passed CI and local smoke but broke the published package. Add
graphify.extractors to packages; verified the rebuilt wheel imports and extracts
in a clean venv. 0.8.48 is yanked.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 10:00:58 +01:00
safishamsiandClaude Opus 4.8 bc362cbb74 Release 0.8.48
get_community shows the community name (#1448); starlette floored >=1.3.1 for
CVE-2026-48818 / CVE-2026-54283 (#1391, #1396); begin per-language extractor
split into graphify/extractors/ (#1212); parallel community labeling via
--max-concurrency / --batch-size (#1390); reflect dedups dead-ends/corrections;
and the work-memory loop no longer depends on the git hook (reflect --if-stale).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 09:17:21 +01:00
rmart1308andClaude Opus 4.8 f9ded63350 fix(serve): show community name in get_community MCP output (#1448)
get_community was the only graph tool still returning a bare numeric id, while
get_node and the query-traversal output already render the community_name
attribute to_json writes onto every node. Read the name from the community's
member nodes and put it in the header ("Community 12 — Auth & Sessions"),
sanitised like every other LLM-derived field.

Ported from PR #1448 by @rmart1308 onto current v8, with two additions: the name
is skipped when it is just the "Community N" placeholder (written for unnamed
communities) so the header never doubles to "Community 12 — Community 12", and
the formatting is extracted to a module-level _community_header() with focused
tests (named / placeholder / empty / sanitised). Full suite 2397 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:19:40 +01:00
safishamsiandClaude Opus 4.8 ec6b397ee8 security: floor starlette >=1.3.1 (CVE-2026-48818, CVE-2026-54283)
starlette underpins the HTTP MCP transport (serve_http); graphify/serve.py
imports it directly (Starlette/Middleware/Route) but it was only present
transitively via mcp, with no version floor — so end users installing
graphifyy[mcp] could resolve a vulnerable starlette even after a lockfile bump.
Declare it in the mcp (and all) extras and floor at >=1.3.1, which carries the
fixes for both CVEs (1.3.1 >= the 1.1.0 fix for CVE-2026-48818 and is the fix
for CVE-2026-54283). Lock regenerated 1.0.0 -> 1.3.1.

Supersedes the lock-only bumps in #1391 and #1396 (both targeted 1.3.1 from a
stale base) with a pyproject floor that also protects end users. stdio MCP and
CLI are unaffected. serve/MCP/HTTP tests pass on 1.3.1; full suite 2393 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 20:59:20 +01:00
safishamsiandClaude Opus 4.8 a95a8339ca chore(extract): drop now-dead from .ids import make_id import
The extractor-split port (b3ab221) moved `_make_id` (the only user of
`make_id`) into graphify/extractors/base.py, leaving the top-level
`from .ids import make_id` in extract.py unused. Remove it. Surfaced by
`ruff --select F` (F401); harmless at runtime and not in the enforced lint
set, but it is dead code from the move. extract.py F-issue count back to the
pre-port baseline; module imports and the zig/elixir/razor/blade tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:32:21 +01:00
TheFedaikinandClaude Opus 4.8 b3ab221762 refactor(extract): begin per-language extractor split (#1212)
Move the blade/elixir/razor/zig extractors and the shared primitives
(_make_id, _file_stem, _read_text, _LANGUAGE_BUILTIN_GLOBALS) out of the
13k-line extract.py into a graphify/extractors/ package: base.py holds the
shared pieces, one module per language, and __init__ seeds a
LANGUAGE_EXTRACTORS registry for future dispatch. Import direction is strictly
extract.py -> extractors/ (extractors never import extract), so there is no
cycle. extract.py re-exports every moved name, leaving all callers and the
dispatch table unchanged.

Ported from PR #1291 by @TheFedaikin onto current v8 as a thin, behavior-neutral
slice (the PR itself was branched 31 commits behind and entangled with unrelated
files). Verified the moved code is byte-identical to current v8 before porting;
full suite 2393 passed, the zig/elixir/razor/blade extractor tests pass, ruff and
skillgen --check clean. Also gitignores .DS_Store.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 17:51:04 +01:00
safishamsiandClaude Opus 4.8 22a58ffc20 feat: parallel community labeling via --max-concurrency / --batch-size (#1390)
label_communities ran batches one LLM call at a time, so a large graph needed
hundreds of sequential calls even on backends that allow heavy concurrency. It
now fans batches out across a thread pool, mirroring extract_corpus_parallel:
results are returned per batch and merged on the main thread (labels dict is
never mutated concurrently, no lock), and workers==1 keeps the original
sequential path verbatim. ollama and claude-cli are forced serial unless the
matching GRAPHIFY_*_PARALLEL env opt-in is set (same guard as extract).

generate_community_labels threads max_concurrency + batch_size through, and the
cluster-only/label CLI parses --max-concurrency and --batch-size (both `--flag N`
and `--flag=N` forms; the space form is parsed explicitly so the value is not
mistaken for the positional scan path by the arg-walk's catch-all).

Output is deterministic regardless of concurrency (keyed by community id). Tests:
parallel == sequential result, batch-size controls batch count, batches actually
run concurrently, ollama forced serial, and the CLI parses both new flags. Full
suite 2393 passed; ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 13:53:33 +01:00
safishamsiandClaude Opus 4.8 1a14e94e53 fix(reflect): dedupe dead-ends and corrections by question
Saving the same Q&A more than once duplicated lines in the "known dead ends" and
"corrections" sections: both lists were appended per memory doc with no key, while
node scoring already dedups by node. They now collapse by question, keeping the
most recent entry (docs are processed oldest-first, so a re-corrected question
shows its latest correction). Output stays deterministic, ordered by (date,
question). Applied to both the flat lists and the per-community buckets.

Found by a user running it on a 104-file Go codebase. Added a regression test
covering the dedupe and the recency-wins correction. Full suite 2389 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 12:48:57 +01:00
safishamsiandClaude Opus 4.8 d193b6277d feat(reflect): --if-stale to skip redundant runs; agent uses it at session start
Both the agent (session start) and the post-commit hook can run reflect; the runs
are deterministic and idempotent, but back-to-back ones are wasted work. Add
`graphify reflect --if-stale`, which no-ops when LESSONS.md is already at least as
new as every input (the memory docs and the graph). The skill's session-start
guidance now uses `--if-stale`, so when the hook just refreshed the file the
agent's run costs almost nothing, while a skill-only install still refreshes
on demand.

New lessons_fresh() helper + 5 tests (mtime freshness in each direction, and the
CLI skip/run behavior). Regenerated per-host references + re-blessed expected/;
all five skillgen guards pass; full suite 2388 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 12:26:39 +01:00
safishamsiandClaude Opus 4.8 c06db05351 fix(skill): agent self-refreshes LESSONS.md so work-memory works without the hook
A skill-only install (no `graphify hook install`) recorded outcomes via
save-result but never ran reflect, so LESSONS.md was never generated or
refreshed and the lessons never surfaced. The query reference now instructs the
agent to run `graphify reflect` itself at the start of graph work (cheap,
deterministic, no-op with no saved outcomes) before reading LESSONS.md. The
post-commit hook stays as a between-session freshness optimization, not a
requirement. Regenerated per-host references/query.md + re-blessed expected/;
all five skillgen guards pass; full suite 2383 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 12:17:16 +01:00
safishamsiandClaude Opus 4.8 f87011b38e Release 0.8.47
Work-memory (#1441): save-result --outcome + graphify reflect, with recency-decayed
scoring, corroboration threshold, label-matched node-existence gate, contested
handling, and zero-config adoption (skill reads LESSONS.md + records outcomes; git
hooks auto-reflect). Fixes: Python ClassName.method() qualified-call edges (#1446);
validate_extraction/build crash on non-hashable id (#1447); graphify update now
prunes a symbol removed from a surviving file without --force.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:53:53 +01:00
safishamsiandClaude Opus 4.8 6d9617a44f feat: zero-config work-memory adoption via skill + git hooks (#1441)
Make the self-improving loop "just work" once graphify is installed:

- Skill: the query reference now tells the agent to read
  graphify-out/reflections/LESSONS.md at the start of graph work (start from
  preferred sources, skip known dead ends, see prior corrections) and to record
  --outcome useful|dead_end|corrected (+ --correction) on save-result.
- Hooks: the post-commit and post-checkout rebuild bodies now auto-run reflect
  after _rebuild_code — best-effort, only when graphify-out/memory/ holds saved
  outcomes, and never fails the hook — so LESSONS.md refreshes on every rebuild
  without a manual `graphify reflect`.

Regenerated the per-host references/query.md and re-blessed expected/; all five
skillgen guards pass (check, audit-coverage, schema-singleton, monolith-roundtrip,
always-on-roundtrip). Verified end-to-end: install hook, save-result --outcome,
commit a code change -> hook rebuilds and writes LESSONS.md with the outcome.
Full suite 2383 passed; ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:50:07 +01:00
safishamsiandClaude Opus 4.8 89dd00f140 feat: self-improving work-memory — save-result outcomes + graphify reflect (#1441)
Adds the deterministic work-memory loop: `save-result --outcome
useful|dead_end|corrected [--correction]` records how a saved Q&A turned out, and
`graphify reflect` aggregates graphify-out/memory/ into a deterministic
reflections/LESSONS.md an agent loads next session.

Source nodes are scored, not counted: signed, recency-decayed (useful +,
dead_end/corrected -, configurable --half-life-days, default 30), so a fresh dead
end outweighs a stale useful. A node is "preferred" only once corroborated by
>=--min-corroboration distinct results (default 2); others are "tentative", and
mixed-signal nodes render once as "contested" (recency-wins). Source nodes are
matched to the graph by label OR id, and citations whose node no longer exists are
dropped, so a plain `graphify update` after deleting code clears stale lessons.
Deterministic, no LLM; bare save-result and existing behavior unchanged.

Rigorously verified end-to-end on real data: corroboration boundary, recency flip,
contested verdict, foreign/malformed memory docs, cold start, 300-doc scale +
byte-stable output, and the node-gate dropping deleted-code lessons after update.
Full suite 2383 passed; skillgen --check clean; ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:43:13 +01:00
safishamsiandClaude Opus 4.8 533859dc51 fix(update): file-aware shrink-guard so removed symbols prune without --force
`graphify update` after deleting a function left the stale node in graph.json.
The build correctly dropped it (#1116), but _check_shrink then refused to write
the smaller graph ("Refusing to overwrite — you may be missing chunk files"),
so the deletion never persisted without --force. That also starved the
work-memory node-existence gate, which relies on graph.json reflecting deletions.

The shrink-guard now takes the set of source files re-extracted this run
(rebuilt_sources). A net shrink is allowed when every lost node belongs to a
rebuilt source (a symbol genuinely removed) or a deleted file; it is still
refused when a node vanishes from a file we did NOT touch — the silent
failed/partial-extraction case the guard exists to catch.

The #1116 e2e test now asserts the prune happens with force=False (was force=True);
added two _check_shrink unit tests (allowed within rebuilt sources, refused
outside). Full suite 2339 passed; skillgen --check clean; ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:29:08 +01:00
safishamsiandClaude Opus 4.8 b448c16cbd docs(changelog): add #1447 entry (non-hashable id/endpoint crash fix)
The #1447 cherry-pick only touched build.py/validate.py + tests, so it
shipped without a CHANGELOG note. Add it under Unreleased.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 09:10:54 +01:00
safishamsiandClaude Opus 4.8 c390456c6c fix: resolve Python ClassName.method() qualified calls to class-method nodes (#1446)
Cross-class qualified static calls like `CustomerTaskActions.approve(...)` did
not produce an EXTRACTED `calls` edge. Two compounding causes:

1. The shared cross-file pass skips all member calls (the #543/#1219 god-node
   guard against bare `obj.method()` name collisions), and there was no Python
   receiver-based resolver to recover the qualified ones.
2. When the called method shared its name with an in-file node — e.g. a viewset
   action `approve()` delegating to a service `Service.approve()` — the in-file
   bare-name lookup matched the caller's own node (tgt == caller), so the call
   was silently dropped before any raw_call was recorded.

Fix: capture a simple-identifier receiver in the call walk (new
`call_accessor_object_field`, set to `object` for Python), defer capitalized-
receiver member calls to a new `_resolve_python_member_calls` pass (mirroring the
Swift resolver), and emit an EXTRACTED edge only when the receiver resolves to
exactly one class that owns the method (single-definition god-node guard).
Instance/module calls (`self.x()`, `obj.x()`, lowercase receivers) are unaffected.

Tests: cross-class resolution, the same-method-name collision shape from the
issue, instance-call non-over-connection, and the ambiguous-class guard.
Full suite 2337 passed; skillgen --check clean; ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 09:09:48 +01:00
dschwartzi 2c7cbb6530 Fix: validate_extraction crashes on non-hashable node id / edge endpoint
validate_extraction() is documented to return a list of error strings ("empty
list means valid"), but raised TypeError: unhashable type: 'list' when a node
id -- or an edge source/target -- was a non-hashable value such as a list. This
occurs in practice when an LLM extraction subagent emits malformed JSON like
{"id": ["foo", "bar"], ...}. Crash sites: the node_ids set comprehension and
the `edge[...] not in node_ids` membership tests.

Because build_from_json() validates at its start, a single malformed node
aborted the entire build, losing an otherwise-complete extraction of a large
corpus. build_from_json() itself would also raise (G.add_node(<list>) and the
`not in node_set` test) if the validator were bypassed.

- validate.py: build node_ids during the node pass, adding only hashable ids;
  report a non-hashable id/endpoint as an error string instead of crashing.
  All existing messages and the dangling-edge checks are preserved.
- build.py: skip dict nodes with a missing/non-hashable id and edges with
  non-hashable endpoints (stderr warning). Non-dict nodes are deliberately
  left to raise so the multigraph diagnostic still observes shape errors.
- tests: 3 cases in test_validate.py and 2 in test_build.py.
2026-06-24 08:54:11 +01:00
tpateeqandClaude Opus 4.8 ad6cb753c0 feat(install): add cross-framework agents platform (+ skills alias)
`graphify install --platform agents` installs the skill to the generic
Agent-Skills locations: the spec's user-global ~/.agents/skills (global) and
./.agents/skills (--project) — the directories `npx skills` and spec-compliant
frameworks read. `--platform skills` is an alias. Previously that user-global
location was only reachable as an accidental side effect of the gemini-on-Windows
branch. Bare `graphify install` is unchanged (still single-platform claude/windows).

The platform is registered in tools/skillgen/platforms.toml (split, mirroring
amp's agents-md body) and rendered through the skillgen drift/coverage guards.
Since it is a post-v8 platform with no own v8 body, its --audit-coverage baseline
is amp's v8 body (the body it re-homes). The rendered skill body is byte-identical
to amp's; only the on-demand hooks reference differs (its own `graphify agents
install` wording).

The `graphify agents install` / `graphify skills install` subcommand is the
amp-twin: it also wires an AGENTS.md always-on section, keeping it honest with the
hooks reference it points at. The `--platform agents` path stays skill-only,
exactly as amp's `--platform amp` does.

Also: `skill-agents.md` added to package-data, and the wheel-packaging guard now
covers every platform's skill body (not just references/always-on), so a missing
skill body fails CI instead of only breaking install for real users.

Closes #1405. Implements #1432.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 17:26:49 +01:00
safishamsiandClaude Opus 4.8 29fd98fd04 Release 0.8.46
Query perf, a skill graph-health gate, and a batch of install/extraction fixes:
- #1431 trigram query prefilter (faster, results unchanged)
- #1437 Step 4.5 graph-health gate + semantic-cache anchored on the scan root
- #1411 CUDA (.cu/.cuh) via the C++ extractor
- #1402 cross-file type-annotation refs no longer duplicate nodes
- #1403 hermes install -> %LOCALAPPDATA% on Windows
- #1409 no punctuation-only Obsidian/Canvas filenames
- #1413 opencode reminder backtick command-substitution fix
- #1428 graphify extract --cargo handles missing Cargo.toml
- #1429 prs.py F821 cleanup

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 13:21:38 +01:00
safishamsiandClaude Opus 4.8 87fe887919 Changelog for the #1431 query prefilter and #1437 health-gate/cache-anchor merges
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 12:58:16 +01:00
Mamadou BahandClaude Opus 4.8 e7ba16bfa3 skill: add Step 4.5 graph-health gate + anchor caches on the scan root
Two integrity improvements to the core skill runbook (rendered via skillgen):

1. Graph-health gate (new Step 4.5): runs diagnostics.diagnose_extraction
   read-only after build, before labeling, and surfaces dangling/missing/
   self-loop and same-endpoint-collapsed edges — the silent-corruption modes of
   incremental updates and AST/LLM id mismatches. Never aborts.
2. Anchor the AST and semantic caches on the scan root (root/cache_root=
   'INPUT_PATH') instead of the cwd, matching the CLI extract path
   (ast cache_root=out_root, check/save_semantic_cache(root=out_root)) and
   build_from_json/save_manifest (#1361 parity). Without this, running from a
   cwd != scan root cold-misses the cache and can split AST vs semantic caches.

Source edited in tools/skillgen/fragments/core/core.md; artifacts + expected/
regenerated via 'python -m tools.skillgen' (+ --bless). Full suite green
(2229 passed); skillgen + cache suites green (80 passed).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 12:47:02 +01:00
Paulo PintoandClaude Opus 4.8 53edd27e6a perf(serve): trigram candidate prefilter to cut O(N) query latency
_score_nodes and _find_node scan every node per query (O(nodes x terms)),
so query latency scales with total graph size regardless of where the
answer lives. Add a lazily-built character-trigram index (cached on the
graph object, auto-invalidated on hot-reload like _idf_cache) that narrows
each query to a small candidate superset before the unchanged scoring loop.

Results are byte-identical: the index is a pure candidate generator over
the exact fields the scorer reads (norm_label, label_tokens, nid,
source_file); a non-candidate node always scores 0, and IDF stays a
whole-graph statistic. _find_node candidates are returned in graph
iteration order so its exact/prefix/substring ordering, and matches[0],
stay unchanged.

A selectivity guard falls back to the full scan when a query term is too
short to trigram or its rarest trigram is still common (broad terms like
model/client), preserving a never-worse contract.

The index builds eagerly at load and before a reloaded graph is swapped
in, so neither the first query nor the first post-reload query pays the
one-time build cost. Storage format is unchanged (in-memory index only).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 12:46:51 +01:00
safishamsiandClaude Opus 4.8 a4d09aefd8 Install the hermes skill to %LOCALAPPDATA% on Windows (#1403)
graphify install --platform hermes always wrote the skill to ~/.hermes/skills,
the POSIX path. On Windows, Hermes scans %LOCALAPPDATA%\hermes\skills, so the
installed skill was never discovered. _platform_skill_destination now has a
hermes branch: Windows -> %LOCALAPPDATA%\hermes\skills, other OSes unchanged
(~/.hermes/skills). Pure path logic — no skillgen regeneration.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 00:18:47 +01:00
safishamsiandClaude Opus 4.8 0aeda15c10 Resolve cross-file type-annotation refs to a single node, not phantom duplicates (#1402)
A class defined once but referenced via type annotations in N other files appeared
as 1+N nodes — the extras carrying the referencing file's path (with extension)
baked into the id (e.g. pkg_a_py_thing). ensure_named_node's cross-file fallback
called add_node, which stamps the referencing file as source_file; that sourced
stub then collided in _disambiguate_colliding_node_ids (baking the .py path into
the id) and _rewire_unique_stub_nodes skipped it (a node with a source_file is
treated as a real definition, not a stub).

The fallback now emits a SOURCELESS stub (mirroring the inheritance-base path), so
disambiguation ignores it and the rewire collapses it onto the canonical
definition. The helper is duplicated across all six language extractors, so the
fix is applied to all six. Genuinely-defined duplicates (same name, different
files) still stay separate — only cross-file references collapse.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 00:17:59 +01:00
safishamsiandClaude Opus 4.8 739230e17a Add regression tests for punctuation-only Obsidian/Canvas filenames (#1409)
Cover the #1410 fix: to_obsidian and to_canvas must never emit a punctuation-only
filename (e.g. `@.md` from a `@/*` tsconfig paths key) — valid on disk but empty
once a downstream tool re-slugs on word chars (crashes `qmd update`). Both tests
exercise the public exporters and fail against the pre-fix safe_name().

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 23:15:59 +01:00
Luca ZanottiandClaude Opus 4.8 30cc4c0670 fix(export): never emit punctuation-only Obsidian filenames (e.g. @.md)
An all-punctuation node label (e.g. `@/*` from a tsconfig paths entry) survived
the unsafe-char strip in `to_obsidian`'s `safe_name()` as a bare `@`, producing
`@.md`. That filename is valid on disk but empty once a downstream tool re-slugs
on word chars — qmd's handelize() reduces "@" -> "" and raises, aborting the
entire `qmd update` (every collection on the machine stops reindexing).

Require at least one word char in the stem; otherwise fall back to "unnamed"
(the existing dedup handles collisions). Applied to both safe_name occurrences.

Fixes #1409

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 23:10:49 +01:00
DhruvTilva 0b96b61609 fix: resolve F821 undefined name 'nx' in prs.py 2026-06-22 22:57:19 +01:00
raylei50653andClaude Opus 4.8 dbce4532f4 Add CUDA (.cu/.cuh) support via the C++ extractor
CUDA is a C++ superset, so .cu/.cuh files parse cleanly with
tree-sitter-cpp (already a dependency). Two registrations wire it up:

- detect.py: add .cu/.cuh to CODE_EXTENSIONS so they're detected and
  watched (watch.py's _WATCHED_EXTENSIONS derives from CODE_EXTENSIONS).
- extract.py: route .cu/.cuh through extract_cpp in _DISPATCH, which
  also makes collect_files() pick them up (_EXTENSIONS = _DISPATCH.keys()).

Adds tests/fixtures/sample.cu (kernel + __device__/host functions +
struct + includes) and CUDA cases in test_languages.py covering kernel/
device function extraction, structs, includes, and host call edges.
Documents the new extensions in the README extension table and CHANGELOG.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:57:06 +01:00
WSHAPER 2323ce1937 fix(opencode): strip backticks from plugin reminder to prevent silent command substitution (#1413)
The opencode plugin template embedded the reminder string with backticks
around `graphify query "<question>"`. Because the plugin prepends
`echo "<reminder>" && <cmd>` to the user's bash command, those backticks
triggered bash command substitution: every grep/rg/find invocation silently
ran `graphify query "<question>"` and substituted its output
("No matching nodes found.") into the reminder text shown to the agent.

This both corrupted tool output with graphify noise, and actually spawned
a graphify process + loaded graph.json + ran a BFS traversal with the
literal token <question> on every search.

Fix: remove the backticks. Adds a guard comment in the template so future
editors don't reintroduce the bug, and a regression test that asserts the
reminder string contains no backticks and no $() constructs.
2026-06-22 22:54:03 +01:00
DhruvTilva aa06e10fa5 fix: catch OSError when Cargo.toml is missing during --cargo introspection 2026-06-22 22:54:03 +01:00
safishamsiandClaude Opus 4.8 5862bce5ca Release 0.8.45
Path-portability cluster + native-backend hyperedge prompt fix:
- #1417 portable manifest.json from the skill runbooks
- #1418 hyperedge source_file relativization
- #1419 GRAPH_REPORT.md header shows the scan root
- #1423 GRAPHIFY_OUT honoured end-to-end
- native-backend extraction prompt now requests hyperedges (#1430)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 22:32:52 +01:00
safishamsiandClaude Opus 4.8 aad3b47098 Request hyperedges in the native-backend extraction prompt (#1418 follow-up)
`graphify extract --backend <gemini|claude|claude-cli|openai|kimi|...>` produced
zero hyperedges for any corpus: llm._EXTRACTION_SYSTEM only showed
"hyperedges":[] in its output schema and never described what a hyperedge is, so
every model returned the empty array. Meanwhile the agent/skill path, whose
references/extraction-spec.md fully documents hyperedges ("3 or more nodes
participate together..."), produced them — the two prompts had drifted.

Bring the native prompt in line with the skill spec: add the hyperedge
instruction and a populated schema example. The parse/merge side already handled
hyperedges, so this is prompt-only. Verified with a real claude-cli run — a doc
that previously yielded 0 hyperedges now yields one, correctly relativized (#1418).

Adds two guard tests: the native prompt must request hyperedges with a populated
example, and it must share the skill spec's hyperedge wording so they can't drift
apart again.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 22:20:40 +01:00
safishamsiandClaude Opus 4.8 b8dc31f760 Honour GRAPHIFY_OUT end-to-end, not just in the path guards (#1423)
The GRAPHIFY_OUT override (custom output-dir name / absolute path, #686) was only
respected by some readers. `graphify extract` and several commands hardcoded the
literal "graphify-out", so `GRAPHIFY_OUT=custom-out graphify extract` still wrote
to graphify-out/ and downstream query/serve/update looked in the wrong place.

Resolve the output-dir name through graphify.paths everywhere it matters:
- new graphify.paths.out_path()/default_graph_json() helpers
- __main__: extract write dir, cluster-only/label, query/affected/benchmark
  defaults, save-result --memory-dir, uninstall --purge, cache-check
- detect: _MANIFEST_PATH, memory/ + converted/ dirs, and the scan-exclude (a
  renamed output dir is no longer re-ingested as source input)
- transcribe._TRANSCRIPTS_DIR; build_merge/serve/benchmark/prs graph-path defaults

Default behaviour is unchanged: with no env var everything still uses graphify-out/.
Verified end-to-end (extract -> cluster-only -> query under GRAPHIFY_OUT=custom-out
writes/reads custom-out/, no stray graphify-out/) and added a CLI regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 21:15:51 +01:00
safishamsiandClaude Opus 4.8 6954a28da8 Show the scan root in the GRAPH_REPORT.md header instead of '.' (#1419)
The split-skill runbook passed '.' as report.generate's root argument in
Steps 4 and 5, so `/graphify /some/path` produced a report titled
"# Graph Report - ." regardless of the scanned directory. It now passes
'INPUT_PATH' (the Aider/Devin monoliths were already correct). Display-only:
no path written to graph.json or manifest.json was affected. Regenerated +
blessed the split-skill artifacts.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:00:59 +01:00
safishamsiandClaude Opus 4.8 1f42a2da2b Write a portable manifest.json from the skill runbooks (#1417)
The skill runbooks called save_manifest(...) with no root=, so manifest keys
were stored as absolute paths (e.g. /Users/.../main.go). Cloning or moving the
repo then broke `graphify --update`: detect_incremental matched none of the
cached keys, so the entire corpus re-extracted (and the report showed ghost
nodes). The native `graphify extract`/`update` CLI already passed root=target;
the agent-executed runbooks did not.

All four runbook call sites now pass root='INPUT_PATH', relativizing manifest
keys to the scan root (portable forward-slash form, per save_manifest's #777
support): the lean-core skill.md Step 9, the shared --update reference, and the
Aider/Devin monoliths.

The monolith edit is registered as a new sanctioned change-class
(_is_manifest_root_fix_line) in the round-trip guard, mirroring how the #1392
runbook fixes were sanctioned. Regenerated + blessed all artifacts; added a
regression test asserting every shipped runbook threads root= into save_manifest.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:29:33 +01:00
safishamsiandClaude Opus 4.8 d168de999a Relativize hyperedge source_file and honour GRAPHIFY_OUT everywhere (#1418, #1423)
#1418: build_from_json relativized source_file on nodes and edges but stored
graph.hyperedges[] verbatim, so a semantic subagent's absolute path leaked into
graph.json. Relativize hyperedges in build_from_json (to_json has no root to
relativize against), mirroring the existing node/edge handling.

#1423: consolidate the GRAPHIFY_OUT output-dir name into a single graphify.paths
module (was duplicated in __main__, cache, watch) and route the path guards
through it — security.validate_graph_path's base=None discovery + fallback,
callflow_html's project-root resolution, and the post-commit/post-checkout hook
bodies (which now read the env var at hook-run time). A renamed output dir is no
longer validated against the wrong base or missed by the hook.

Tests: hyperedge relativization (test_hypergraph), GRAPHIFY_OUT discovery
(test_security), updated the hook-body contract assertion (test_hooks).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:02:29 +01:00
SafiandClaude Opus 4.8 5d053721ab Apply the #1392 runbook fixes to the Aider and Devin monolith skills
The monoliths are hand-maintained single files frozen against a pinned pristine-v8 blob by the round-trip guard, so they were excluded from the 0.8.44 #1392 batch. Evolve the guard from a positional zip (line-count-exact, single-line-class allowlist) to a multiset diff that classifies every added/removed line against documented sanctioned change-classes, so the multi-line fixes can land while any unsanctioned drift still fails. Add predicates for the four fix classes and broaden the enum/chunk-cleanup predicates to match both the v8 and rewritten forms.

Both monoliths now: thread directed=IS_DIRECTED through every build_from_json call (a --directed run no longer collapses reciprocal edges), scope semantic extraction to document/paper/image, unlink a stale .graphify_cached.json on a cache miss, and run Step 4's zero-node guard before any write with the report/analysis gated on to_json persisting the graph (#1392).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 16:17:49 +01:00
SafiandClaude Opus 4.8 dce54a007e Release 0.8.44
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 15:45:24 +01:00
SafiandClaude Opus 4.8 382b669481 Fix remaining #1392 skill bugs: --directed propagation, content-only semantic scope, cache staleness, video update, transcribe robustness
Closes the non-crash tier of #1392 in the Claude-path skill fragments:
- #6/#7: build_from_json/build_merge now take directed=IS_DIRECTED in Step 4, Step 5 rebuild, and the --update merge/diff, with prose telling the agent to substitute IS_DIRECTED like INPUT_PATH (a --directed run no longer silently rebuilds undirected and collapses reciprocal edges)
- #10: semantic extraction only flattens document/paper/image, not code (AST already covers code) so subagents stop re-reading every source file
- #12: .graphify_cached.json is deleted on a cache miss so Part C never merges a stale cache from a prior run
- #11: --update now transcribes changed video files and moves transcripts to documents before the semantic pipeline
- #4/#5/#23: transcribe writes via write_text (no shell redirect), uses GRAPHIFY_WHISPER_MODEL/PROMPT env, status to stderr
- #2/#3: add-watch and exports use $(cat graphify-out/.graphify_python) explicitly; MCP Desktop config documents the absolute interpreter path
- #21: extraction-spec example id namespaced (auth_session_validatetoken)
- #22: query term split keeps tokens >= 3 chars

aider/devin monoliths are pinned by the roundtrip invariant and excluded; their own Step 1 already instructs replacing python3 with the resolved interpreter.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 15:37:11 +01:00
SafiandClaude Opus 4.8 30fe8bab61 Fix crash/data-loss bugs in the generated skill runbooks (#1392)
Five fixes in the skillgen fragments (re-rendered): chunk paths now derive from
cwd to match where Part C globs (a non-cwd scan produced "no nodes"); the
code-only fast path writes an empty .graphify_semantic.json so Part C doesn't
FileNotFoundError; --cluster-only relies on the self-contained CLI instead of
re-running Steps 5-9 against deleted intermediate files; and Step 4 runs the
zero-node guard before any write and only writes GRAPH_REPORT.md / analysis when
to_json actually persisted the graph (honoring the #479 shrink-guard).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 15:19:07 +01:00
SafiandClaude Opus 4.8 7d07a24708 Don't Path()-coerce FileSlice units in the extract entry points (#1397, #1399)
The 0.8.43 str-path coercion (#1386) ran Path(f) over every item in
extract_files_direct, but extract_corpus_parallel feeds it FileSlice units from
the oversized-doc slicing (#1369), and Path(FileSlice) raises TypeError -- so
semantic extraction of any Markdown file larger than _FILE_CHAR_CAP crashed.
Coerce only non-Path/non-FileSlice entries. The #1386 tests used small files, so
slicing never ran; added a regression test with a file that actually slices.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #1238

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

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

Closes #1234, closes #1235

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

- New push_to_falkordb() in graphify/export.py mirrors push_to_neo4j; FalkorDB
  is OpenCypher-compatible so the MERGE/SET upsert queries are identical.
- export falkordb subcommand wired in graphify/__main__.py (cypher.txt when no
  --push, direct push otherwise). Auth is optional; target graph defaults to
  "graphify".
- falkordb optional extra in pyproject.toml (and in the all extra).
- Tests: CLI cypher generation (CI-safe) + real-FalkorDB integration tests that
  skip when no instance is reachable.
- README extras table + command reference and CHANGELOG updated.
2026-06-07 15:03:49 +03:00
Leon Aburime 3e8afc9192 docs: detail proposed node summary contents 2026-06-06 20:36:30 -07:00
Leon Aburime 1ad47ec05e docs: add RFC for file-level node summaries 2026-06-06 20:33:35 -07:00
755 changed files with 154810 additions and 19549 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# Code owners for graphify.
#
# Owners are automatically requested for review on pull requests that touch
# matching paths. This file is advisory review routing; it does not by itself
# block merges unless "Require review from Code Owners" is enabled in branch
# protection.
#
# See: https://docs.github.com/articles/about-code-owners
# Default owner for everything in the repo.
* @safishamsi
# Skill generation is roundtrip-sensitive (monolith sanctioned diffs); flag it.
/tools/skillgen/ @safishamsi
/graphify/skill*.md @safishamsi
/graphify/skills/ @safishamsi
# Release, security, and CI configuration.
/.github/workflows/ @safishamsi
/SECURITY.md @safishamsi
/RELEASING.md @safishamsi
+34
View File
@@ -0,0 +1,34 @@
labels: []
body:
- type: markdown
attributes:
value: |
Thanks for asking. Before posting, please check the
[docs](https://docs.graphify.com) and search existing
[discussions](https://github.com/Graphify-Labs/graphify/discussions)
and [issues](https://github.com/Graphify-Labs/graphify/issues) — your
question may already be answered. For real-time help, join the
[Discord](https://discord.gg/XDnKVpzdXB). If you have found a bug, please
open an issue instead so it can be tracked.
- type: textarea
id: question
attributes:
label: What are you trying to do?
description: Describe the goal and the question, not only the error.
validations:
required: true
- type: textarea
id: tried
attributes:
label: What have you tried?
description: Commands you ran, docs you read, and what happened.
validations:
required: false
- type: input
id: version
attributes:
label: graphify version and environment
description: Output of `graphify --version`, plus your OS and Python version.
placeholder: "graphify 0.9.70, macOS 15, Python 3.12"
validations:
required: false
+98
View File
@@ -0,0 +1,98 @@
name: Bug report
description: Report incorrect behavior, a crash, or a regression.
title: "[Bug]: "
labels:
- bug
body:
- type: markdown
attributes:
value: |
Please search existing issues first. Include the smallest reproducible example you can.
- type: checkboxes
id: checks
attributes:
label: Pre-flight checks
options:
- label: I have checked the Troubleshooting section in the README
required: true
- type: textarea
id: description
attributes:
label: What happened?
description: Describe the actual behavior and the behavior you expected.
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Steps to reproduce
description: Include commands, input files, and the smallest useful example.
render: shell
validations:
required: true
- type: textarea
id: output
attributes:
label: Error output or graph output
description: Paste the relevant traceback, diagnostic, or incorrect result.
render: text
validations:
required: true
- type: input
id: version
attributes:
label: Graphify version
placeholder: "e.g. 0.9.68"
- type: dropdown
id: os
attributes:
label: Operating System
options:
- macOS
- Linux
- Windows
- WSL
validations:
required: true
- type: dropdown
id: python
attributes:
label: Python Version
options:
- 3.10
- 3.11
- 3.12
- 3.13
validations:
required: true
- type: dropdown
id: install_method
attributes:
label: Installation Method
options:
- uv tool install (recommended)
- pipx
- pip
- built from source (git clone)
validations:
required: true
- type: textarea
id: environment
attributes:
label: Additional Environment Details
description: List any provider environment variables set (e.g., OPENAI_API_KEY) and whether a clean checkout reproduced the issue.
- type: textarea
id: additional
attributes:
label: Additional context
description: Add related files, screenshots, or links if they help explain the issue.
+14
View File
@@ -0,0 +1,14 @@
blank_issues_enabled: true
contact_links:
- name: Security policy
url: https://github.com/Graphify-Labs/graphify/security/policy
about: Please report vulnerabilities privately using the security policy.
- name: Discord community
url: https://discord.gg/XDnKVpzdXB
about: Join the Discord to ask questions and discuss ideas in real time.
- name: 📖 Documentation
url: https://docs.graphify.com
about: Check the docs (guides, command reference, integrations) before opening an issue.
- name: 🤝 Contributing guide
url: https://github.com/Graphify-Labs/graphify/blob/v8/CONTRIBUTING.md
about: Read the development and contribution guidelines before opening a pull request.
@@ -0,0 +1,73 @@
name: Feature request
description: Suggest an improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
body:
- type: markdown
attributes:
value: |
Please search existing issues first and describe the user problem before proposing an implementation.
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do that Graphify cannot do today?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the expected behavior, command, API, or workflow.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: What other approaches or workarounds did you consider?
- type: dropdown
id: area
attributes:
label: Area
options:
- Extraction or language support
- Graph building or querying
- CLI or installation
- Skills or assistant integrations
- Documentation
- Performance
- Security
- Developer experience or CI
validations:
required: true
- type: dropdown
id: pr
attributes:
label: Are you willing to submit a PR?
options:
- Yes, I can work on this
- Yes, but I will need guidance
- No, I just wanted to request it
validations:
required: true
- type: textarea
id: compatibility
attributes:
label: Compatibility / behavior impact
description: Does this affect node/edge IDs, cache semantics, graph.json schema, generated skills, MCP output, or incremental updates?
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional context
description: Add examples, links, or sample input where useful.
+39
View File
@@ -0,0 +1,39 @@
## What does this PR do?
<!-- Describe the problem and the change. Link the relevant issue when one exists. -->
## Type of change
- [ ] Bug fix
- [ ] New feature
- [ ] Documentation
- [ ] Tests or CI
- [ ] Refactor
- [ ] Security fix
## Verification & Invariants
<!-- What invariant does this code protect? How do you prove your change doesn't break it? What generated or persisted state could your change invalidate? -->
- [ ] **Read** the [CONTRIBUTING.md](../CONTRIBUTING.md) guide.
- [ ] **Reproduced** the issue and identified the invariant.
- [ ] Made the **smallest fix** necessary.
- [ ] Added a **regression test** (if bug fix) or isolated boundary test.
- [ ] Kept the PR description **synchronized** with the final implementation.
- [ ] Documented any **limitations / unsupported cases** explicitly.
## How was this tested?
<!-- List the commands you actually ran. Mention environment isolation if touching provider paths. -->
```text
```
## Graphify-specific checklist
- [ ] I updated generated skill artifacts (`uv run python -m tools.skillgen --bless`) when changing their source fragments.
- [ ] I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
- [ ] I reviewed changes for security implications (no unsafe interpolation into shell/Python).
- [ ] I confirmed no API keys or local-only graph data are included.
- [ ] (If applicable) I disclosed AI authorship in my commit messages.
+28 -1
View File
@@ -50,7 +50,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.12"]
python-version: ["3.10", "3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v6
@@ -77,3 +77,30 @@ jobs:
run: |
uv run --frozen graphify --help
uv run --frozen graphify install
security-scan:
# The dev deps include bandit and pip-audit. Run them in CI so a new
# HIGH-severity finding or vulnerable dependency is caught on the PR that
# introduces it, rather than at the next manual audit.
# Non-blocking for now (continue-on-error) to avoid breaking CI on
# pre-existing findings; remove continue-on-error after the initial
# cleanup pass.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Install uv
uses: astral-sh/setup-uv@v8.1.0
with:
python-version: "3.12"
- name: Install dependencies
run: uv sync --frozen
- name: bandit (static security analysis)
continue-on-error: true
run: uv run --frozen bandit -r graphify -ll
- name: pip-audit (dependency vulnerabilities)
continue-on-error: true
run: uv run --frozen pip-audit --strict
+55
View File
@@ -0,0 +1,55 @@
name: Publish to PyPI
# Publishes graphifyy to PyPI via OpenID Connect (trusted publishing) — no API
# token or password. Fires when a GitHub Release is published (i.e. after
# `gh release create ... --latest`), builds the sdist + wheel, guards that the
# package version matches the release tag, then uploads with an OIDC token.
#
# One-time PyPI setup (Manage project -> Publishing -> Add a GitHub publisher):
# Owner: Graphify-Labs
# Repository: graphify
# Workflow name: publish.yml
# Environment name: pypi
on:
release:
types: [published]
# Manual re-run escape hatch (still requires the release tag to be checked out).
workflow_dispatch:
permissions:
contents: read
jobs:
publish:
name: Build and publish graphifyy
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/project/graphifyy/
permissions:
id-token: write # REQUIRED: mint the OIDC token PyPI verifies. Nothing else.
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
- name: Build sdist + wheel
run: uv build --sdist --wheel
- name: Guard — package version must match the release tag
if: github.event_name == 'release'
run: |
VERSION=$(grep -m1 '^version = ' pyproject.toml | sed -E 's/^version = "(.*)"/\1/')
TAG="${GITHUB_REF_NAME#v}"
echo "pyproject version: $VERSION | release tag: $TAG"
if [ "$VERSION" != "$TAG" ]; then
echo "::error::pyproject version ($VERSION) does not match release tag ($TAG); refusing to publish."
exit 1
fi
- name: Twine metadata check
run: uvx twine check dist/*
- name: Publish to PyPI (trusted publishing)
uses: pypa/gh-action-pypi-publish@release/v1
+64
View File
@@ -0,0 +1,64 @@
name: Release graph asset
on:
release:
types: [published]
workflow_dispatch:
jobs:
build-graph:
runs-on: ubuntu-latest
permissions:
contents: write # needed to upload release assets
steps:
- uses: actions/checkout@v6
- name: Install uv
uses: astral-sh/setup-uv@v8.1.0
with:
python-version: "3.12"
- name: Install graphify
run: uv sync --frozen
- name: Build graph of graphify source (AST-only, no API cost)
# graphify/skills/ contains 126+ .md files that trigger the LLM pass.
# Temporarily ignore all .md files so extraction stays pure AST (no API key needed).
run: |
echo "*.md" >> .graphifyignore
echo "*.txt" >> .graphifyignore
uv run --frozen graphify extract graphify/ --out .
git checkout .graphifyignore 2>/dev/null || rm -f .graphifyignore
- name: Cluster, label communities and generate GRAPH_REPORT.md
# cluster-only writes GRAPH_REPORT.md and names communities (no LLM needed
# for basic numeric labels; --no-label skips LLM labeling entirely).
run: uv run --frozen graphify cluster-only . --no-label
- name: Generate HTML viewer
run: uv run --frozen graphify export html --graph graphify-out/graph.json
- name: Bundle release asset
run: |
mkdir -p dist-graph
cp graphify-out/graph.json dist-graph/
cp graphify-out/graph.html dist-graph/
[ -f graphify-out/GRAPH_REPORT.md ] && cp graphify-out/GRAPH_REPORT.md dist-graph/ || true
tar -czf graphify-self-graph.tar.gz -C dist-graph .
echo "Asset contents:"
tar -tzf graphify-self-graph.tar.gz
- name: Upload to GitHub release
if: github.event_name == 'release'
uses: softprops/action-gh-release@v2
with:
files: graphify-self-graph.tar.gz
- name: Upload as workflow artifact (for workflow_dispatch runs)
if: github.event_name == 'workflow_dispatch'
uses: actions/upload-artifact@v4
with:
name: graphify-self-graph
path: graphify-self-graph.tar.gz
retention-days: 7
+56
View File
@@ -0,0 +1,56 @@
name: Welcome and invite to Discord
# Posts a friendly comment when someone opens an issue or a pull request,
# pointing them to Discord (real-time) and GitHub Discussions (longer-form).
# pull_request_target is used so the token can comment on PRs from forks;
# the job only posts a comment and never checks out or runs PR code, so this
# is safe.
on:
issues:
types: [opened]
pull_request_target:
types: [opened]
permissions:
issues: write
pull-requests: write
jobs:
welcome:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const isPR = context.eventName === 'pull_request_target';
const payload = isPR ? context.payload.pull_request : context.payload.issue;
const author = payload.user.login;
const number = payload.number;
// Don't comment on bot-opened issues/PRs (dependabot, etc.).
if (author.endsWith('[bot]')) {
return;
}
const discord = 'https://discord.gg/XDnKVpzdXB';
const discussions = 'https://github.com/Graphify-Labs/graphify/discussions';
const body = isPR
? `Thanks for the pull request, @${author}. A maintainer will review it soon.\n\n`
+ `Want to talk it through while it is in review? Come join us on our [Discord server](${discord}). `
+ `For longer-form discussion there is also [GitHub Discussions](${discussions}).\n\n`
+ `A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, `
+ `and that the change keeps extraction deterministic.`
: `Thanks for opening this issue, @${author}. A maintainer will take a look soon.\n\n`
+ `If you would like to discuss it in real time, come say hi on our [Discord server](${discord}). `
+ `For longer-form questions and ideas there is also [GitHub Discussions](${discussions}).\n\n`
+ `To help us triage, please make sure the report includes what you expected, what actually happened, `
+ `and the steps (and a small sample) to reproduce it.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: number,
body,
});
+3
View File
@@ -37,3 +37,6 @@ scripts/llm.py
scripts/benchmark_kimi*.json
scripts/benchmark_kimi*.py
paper/
# macOS Finder metadata
.DS_Store
+1 -1
View File
@@ -3,6 +3,6 @@
This project has a graphify knowledge graph at graphify-out/.
Rules:
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
- When working on Graphify itself, use the repository's existing Graphify guidance. For codebase questions, prefer scoped graph queries where available; use the report for broad orientation. Do not use the graph as evidence when the task concerns the graph's correctness itself.
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
+39 -22
View File
@@ -5,31 +5,48 @@ graphify is a Claude Code skill backed by a Python library. The skill orchestrat
## Pipeline
```
detect() → extract() → build_graph() → cluster() → analyze() → report() → export()
detect() → extract() → build() → cluster() → analyze helpers → report.generate() → export.to_*()
```
Each stage is a single function in its own module. They communicate through plain Python dicts and NetworkX graphs - no shared state, no side effects outside `graphify-out/`.
Each stage lives in its own module and they communicate through plain Python dicts and NetworkX graphs. While designed to minimize shared state, some stages (like extractors) rely on ambient module-level state around the active scan root. Most stages are a single function; `analyze.py` and `export.py` are sets of sibling functions rather than one entry point.
## Module responsibilities
| Module | Function | Input → Output |
|--------|----------|----------------|
| `detect.py` | `collect_files(root)` | directory → `[Path]` filtered list |
| `extract.py` | `extract(path)` | file path → `{nodes, edges}` dict |
| `build.py` | `build_graph(extractions)` | list of extraction dicts → `nx.Graph` |
| `cluster.py` | `cluster(G)` | graph → graph with `community` attr on each node |
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
Signatures below are the real ones - `tests/test_architecture_doc.py` imports every symbol named here, so this table cannot drift from the code.
| Module | Entry point(s) | Input → Output |
|--------|----------------|----------------|
| `detect.py` | `detect(root)` | directory → scan summary dict: `files` grouped by category, plus `total_files`, `total_words`, `warning`, `scan_root`, … |
| `extract.py` | `extract(paths, *, root=None, ...)`, `collect_files(target)` | **list** of file paths → `{nodes, edges}` dict. `collect_files` expands a directory into that list, and lives here, not in `detect.py` |
| `build.py` | `build(extractions)`, `build_from_json(extraction)` | extraction dict(s) → `nx.Graph` |
| `cluster.py` | `cluster(G)` | graph → `{community_id: [node_id, ...]}` (the graph is not mutated) |
| `analyze.py` | `god_nodes(G)`, `surprising_connections(G)`, `suggest_questions(G, communities, community_labels)`, `find_import_cycles(G)`, `graph_diff(G_old, G_new)` | graph → one list/dict per analysis. There is no single `analyze()` entry point |
| `report.py` | `generate(G, communities, cohesion_scores, community_labels, ...)` | graph + analysis → GRAPH_REPORT.md string |
| `export.py` | `to_json`, `to_html`, `to_obsidian`, `to_svg`, `to_graphml`, `to_canvas`, `to_cypher` | graph → graph.json, graph.html, Obsidian vault, graph.svg, … one function per format |
| `wiki.py` | `to_wiki(G, communities, output_dir, ...)` | graph → one markdown article per community + `index.md` |
| `callflow_html.py` | `write_callflow_html(...)` | graphify-out files → Mermaid architecture/call-flow HTML |
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
| `security.py` | validation helpers | URL / path / label → validated or raises |
| `validate.py` | `validate_extraction(data)` | extraction dict → raises on schema errors |
| `serve.py` | `start_server(graph_path)` | graph file path → MCP stdio server |
| `watch.py` | `watch(root, flag_path)` | directory → writes flag file on change |
| `ingest.py` | `ingest(url, target_dir, ...)` | URL → file saved to corpus dir |
| `cache.py` | `check_semantic_cache(files, root)`, `save_semantic_cache(nodes, edges, ...)` | files → cached nodes / edges / hyperedges + the list of files still needing extraction |
| `security.py` | `validate_url`, `safe_fetch`, `validate_graph_path`, `sanitize_label` | URL / path / label → validated value, or raises |
| `validate.py` | `validate_extraction(data)`, `assert_valid(data)` | extraction dict → **list of schema error strings** (`validate_extraction` returns them; `assert_valid` raises) |
| `serve.py` | `serve(graph_path)`, `serve_http(graph_path, *, host, port, ...)` | graph file path → MCP stdio server / HTTP server |
| `watch.py` | `watch(watch_path, debounce=3.0)`, `check_update(watch_path)` | directory → rebuild on change; `check_update` reports whether a re-extraction is pending |
| `benchmark.py` | `run_benchmark(graph_path)` | graph file → corpus vs subgraph token comparison |
### Calling `extract()` from your own code
`extract()` takes a **list** of paths, and `root` is keyword-only and optional:
```python
from pathlib import Path
from graphify.extract import extract
paths = [Path("src/lib/content.ts"), Path("src/pages/index.astro")]
result = extract(paths, root=Path(".").resolve()) # pass root explicitly
```
Always pass `root`. Node ids and `source_file` values are derived relative to it; when it is omitted, `extract()` infers one from the paths you passed, which is the common parent of *that list* rather than your project root. A single-file call therefore anchors to that file's own directory, and ids can end up carrying path segments from the machine they were extracted on.
## Extraction output schema
Every extractor returns:
@@ -45,7 +62,7 @@ Every extractor returns:
}
```
`validate.py` enforces this schema before `build_graph()` consumes it.
`validate.py` enforces this schema before `build()` consumes it.
## Confidence labels
@@ -57,8 +74,8 @@ Every extractor returns:
## Adding a new language extractor
1. Add a `extract_<lang>(path: Path) -> dict` function in `extract.py` following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges).
2. Register the file suffix in `extract()` dispatch and `collect_files()`.
1. Add an `extract_<lang>(path: Path) -> dict` function following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges). New languages go in their own module under `graphify/extractors/` - see `graphify/extractors/MIGRATION.md`; `extract.py` re-exports them while the existing ones are ported out of it.
2. Register the file suffix in `extract()`'s dispatch table and in `collect_files()` (both in `extract.py`).
3. Add the suffix to `CODE_EXTENSIONS` in `detect.py` and `_WATCHED_EXTENSIONS` in `watch.py`.
4. Add the tree-sitter package to `pyproject.toml` dependencies.
5. Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py`.
@@ -70,7 +87,7 @@ All external input passes through `graphify/security.py` before use:
- URLs → `validate_url()` (http/https only) + `_NoFileRedirectHandler` (blocks file:// redirects)
- Fetched content → `safe_fetch()` / `safe_fetch_text()` (size cap, timeout)
- Graph file paths → `validate_graph_path()` (must resolve inside `graphify-out/`)
- Node labels → `sanitize_label()` (strips control chars, caps 256 chars, HTML-escapes)
- Node labels → `sanitize_label()` (strips control chars, caps 256 chars)
See `SECURITY.md` for the full threat model.
@@ -82,4 +99,4 @@ One test file per module under `tests/`. Run with:
pytest tests/ -q
```
All tests are pure unit tests - no network calls, no file system side effects outside `tmp_path`.
The test suite is designed to avoid network access and uncontrolled filesystem effects; most tests are isolated with temporary directories and environment fixtures.
+187
View File
@@ -0,0 +1,187 @@
# graphify Benchmarks
How graphify performs as conversational long-term memory and as a
code-intelligence layer, measured on an open harness with competing systems run
under identical conditions (same model, same budgets, same grader).
Last updated: 2026-07-05.
## Summary
graphify's deterministic graph plus hybrid retrieval has the best retrieval
recall on LOCOMO of any system tested, the best LOCOMO QA accuracy per dollar,
ties for the best LongMemEval score, and builds its index with zero LLM credits.
Every system was run on the same harness with one shared model (Kimi K2.6),
identical budgets, and a judge blind-validated against a second independent judge
(90.6% agreement, Cohen's kappa 0.81).
Highlights:
- LOCOMO retrieval recall@10 of 0.497, about 10x mem0 (0.048) and above BM25 (0.362).
- LOCOMO QA accuracy of 45.3%: +18 points over mem0, +14 over BM25, and within
4.4 points of supermemory at about a tenth of supermemory's ingest cost.
- LongMemEval-S of 76%, tied for best with dense RAG.
- Zero LLM credits to build the graph, and about 11x cheaper memory ingest than
supermemory ($1.40 vs $15.67).
## Results at a glance
| Suite | Dataset (n) | Metric | graphify | Field |
|---|---|---|---|---|
| Memory | LOCOMO (300) | QA accuracy | 45.3% | supermemory 49.7% (11x ingest cost), bm25 31.3%, mem0 27.3% |
| Memory | LOCOMO (300) | recall@10 | 0.497 | bm25 0.362, mem0 0.048 |
| Memory | LongMemEval-S (50) | QA accuracy | 76% | dense RAG 76%, hybrid 74%, mem0 70% |
| Cost | LOCOMO ingest | USD | ~$1.40 | supermemory $15.67, mem0 $3.48 |
| Cost | graph build | LLM credits | $0 | n/a |
## Harness
graphify's own harness. Competing systems (mem0, supermemory) are run as
adapters inside it, so every system sees the same model, token budget, and
grader.
```
ingest -> index -> search -> answer -> grade
(build) (store) (retrieve) (Kimi K2.6) (key-fact coverage)
```
- Memory suite (`memory/`): graphify's graph retrieval vs dedicated memory
systems (mem0, supermemory) and classic baselines (BM25, dense RAG,
hybrid RRF). mem0 and supermemory run self-hosted as adapters, wired through
a proxy so their LLM calls also use Kimi K2.6.
- Code suite (`crosstool/`): a fixed coding agent (Claude Opus 4.8, at most 14
turns, a grep/read/list floor plus one code-intelligence tool) answers graded
questions on ERPNext, a roughly 1M-LOC production repo
([frappe/erpnext](https://github.com/frappe/erpnext)), with a temporal
sub-suite of 689 weekly AST checkpoints from 2011 to 2026.
## Datasets
- LOCOMO (`locomo10.json`, n=300): multi-session conversational QA.
- LongMemEval-S (n=50, English subset): long-horizon conversational memory.
- ERPNext: a large real-world Python codebase for code intelligence.
LOCOMO and LongMemEval are the same academic datasets other memory systems
report on, so results are cross-referenceable. Datasets are not redistributed;
the harness documents the expected local layout.
## Judge and grading
Answers are graded by Kimi K2.6 against a gold set of atomic key facts a correct
answer must contain:
```
coverage = (covered + 0.5 * partial) / total
```
Every verdict cites a verbatim quote from the answer, so grades are auditable
rather than one opaque score.
Judge validation: the judge was blind-validated against a second, independent
judge on a sampled set at 90.6% agreement, Cohen's kappa 0.81 (substantial
agreement). Most published memory benchmarks disclose no judge validation at
all; we publish ours so the grading itself can be audited.
## Fairness rules
- One model for every LLM role: Kimi K2.6 via Moonshot.
- One shared local embedder where the system allows it: BGE-m3 (1024-d,
multilingual).
- Identical token budgets. Every run writes a spend ledger and respects
`--max-spend`.
- Graphs build AST-only with no LLM (an unset API key produces zero credits);
embeddings use a local deterministic model.
## Results: conversational memory
### LOCOMO (n=300)
Sorted by recall@10.
| System | QA accuracy | recall@10 | Ingest cost |
|---|---|---|---|
| **graphify** (graph-expand) | **45.3%** | **0.497** | ~$1.40 |
| hybrid RRF | 43.3% | 0.493 | $0 (shared index) |
| graphify (SurrealDB engine) | 43.3% | 0.485 | $0 (shared index) |
| dense RAG | 41.3% | 0.439 | $0 (shared index) |
| BM25 | 31.3% | 0.362 | $0 (shared index) |
| supermemory | 49.7% | 0.149* | $15.67 |
| mem0 | 27.3% | 0.048 | $3.48 |
Bold marks graphify's primary configuration, not the column maximum. Baselines
retrieve from the same harness-built index, so they incur no separate ingest
cost.
`*` Retrieval-recall is embedder-confounded: supermemory's self-host locks in
its own 768-d English-only embedder rather than the shared BGE-m3. The
QA-accuracy axis (a shared Kimi reader and judge over each system's hits) is the
clean comparison.
Reading: supermemory scores a few points higher on raw QA, but at about 11x the
ingest cost ($15.67 vs $1.40) and with about 3x worse retrieval recall. graphify
has the best retrieval recall on LOCOMO of any system tested, the best QA of the
systems on the shared embedder, and does it for about a tenth of supermemory's
cost. It retrieves the right memory about 10x more often than mem0 and answers
+18 points more accurately. A seed-only ablation (no graph expansion) still
scores 42.7% at $1.40 ingest, so most of the accuracy holds at the cheapest
setting.
### LongMemEval-S (n=50)
| System | QA accuracy | recall@10 |
|---|---|---|
| **graphify** (graph-expand) | **76%** | **0.844** |
| dense RAG | 76% | 0.848 |
| graphify (SurrealDB engine) | 74% | 0.833 |
| hybrid RRF | 74% | 0.822 |
| BM25 | 70% | 0.710 |
| mem0 | 70% | 0.344 |
graphify ties dense RAG for the best QA accuracy (76%); dense RAG edges it on
recall (0.848 vs 0.844). Both retrieve far more than mem0 (recall 0.344).
## Results: code intelligence
On ERPNext (a roughly 1M-LOC production repo), giving a fixed coding agent one
graphify tool lifts key-fact coverage across the graded question set (n=6) from
70.8% (a grep and read baseline) to 82.0%, at about 140K tokens per query.
graphify pays for itself in accuracy against searching raw files, and avoids the
context-stuffing anti-pattern of packing the whole repo into every turn (which
costs roughly 20x the tokens for lower coverage).
## Results: temporal (15 years of ERPNext)
689 weekly AST checkpoints, 2011 to 2026, built deterministically with no LLM.
| Checkpoint | Nodes | Edges | Files |
|---|---|---|---|
| 2011-06-08 | 3,069 | 2,900 | 1,032 |
| 2026-06-24 | 22,620 | 48,710 | 3,758 |
The graph grows about 7x in nodes and 17x in edges across the span. As the
codebase grows, plain lexical retrieval finds less of the answer while graph and
semantic retrieval scale with it, and the AST extraction itself stays stable.
## Cost and token economics
- Graph construction costs zero LLM credits. graphify extracts with tree-sitter
(deterministic, about 40 languages) and a local embedder, so building the
index uses no API tokens. Most memory and semantic-retrieval systems pay a
per-document LLM ingest cost.
- Memory ingest is about 11x cheaper: graphify's LOCOMO ingest runs around
$1.40 against supermemory's $15.67.
- Every number here is backed by a per-run spend ledger in the harness output.
## Reproducing
Set `MOONSHOT_API_KEY`. Datasets are fetched to the local layout documented in
the harness. Each run respects `--max-spend` and writes a spend ledger.
```bash
# Memory (LOCOMO). This invokes the SurrealDB-engine row (43.3%); the
# graph-expand headline (45.3%) is a separate adapter in the same harness.
python memory/runner.py --phase 3 --split locomo --n 300 \
--adapters graphify_v1_surreal --cn natural --workers 6 --max-spend 15
# Code cross-tool (ERPNext)
python crosstool/run.py --repo erpnext --max-spend <budget>
```
+1173 -1
View File
File diff suppressed because it is too large. Load diff
+73
View File
@@ -0,0 +1,73 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, including the GitHub repository, Discord server, and any other channels managed by Graphify Labs. It also applies when an individual is officially representing the community in public spaces.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers at safi@graphify.com, or by directly messaging a Community Leader on the [Graphify Discord server](https://discord.gg/XDnKVpzdXB).
All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html).
+151
View File
@@ -0,0 +1,151 @@
# Contributing to Graphify
Graphify is a graph-building system whose correctness depends on preserving provenance, deterministic extraction, and safe incremental updates. A contribution is not complete because the new code works on the happy path; it is complete when the relevant invariant is explicit, tested, and preserved across rebuilds.
## Before You Start
- Read [ARCHITECTURE.md](ARCHITECTURE.md)
- Read [SECURITY.md](SECURITY.md) when relevant
- Understand `v8` is the active development branch
- Use `graphify-out/GRAPH_REPORT.md` for repository orientation
## What We Value
1. **Preserve correctness, not merely successful execution**. A failed, partial, smaller, or differently keyed extraction must not overwrite valid persisted state or poison incremental caches.
2. **Preserve provenance; incidental richness is not evidence**. A real source-backed record must not lose to a richer sourceless stub. A location without a corresponding source file is not sufficient provenance.
3. **Keep deterministic extraction deterministic**. AST extraction, symbol identity, traversal order, merge behavior, and other structural passes must not depend on filesystem ordering, ambient environment state, network calls, or nondeterministic model output.
4. **Keep inference visibly separate from extracted fact**. Never turn uncertainty into false certainty just because a richer result looks better. Preserve the distinction between extracted fact, inference, and ambiguity.
5. **Prefer fail-closed behavior over guessed relationships**.
6. **Treat persistent graph/cache state as data that can be corrupted**.
7. **Make bug fixes prove the old failure with a regression test**. Demonstrate the old failure, not merely exercise the new code.
8. **Keep PRs narrow and reviewable**. Small, auditable diffs beat clever broad fixes.
9. **Document heuristic boundaries and unsupported cases**.
10. **Never hand-edit generated artifacts**. Edit the source fragment, run the generator, and run the corresponding verification checks.
11. **Do not let ambient environment state affect tests**. Tests must be deterministic with respect to the contributor's shell environment.
12. **Treat paths, source text, model output, URLs, and generated commands as untrusted**. Never construct shell commands or Python source by interpolating free text.
13. **Check cross-platform behavior when touching filesystem/process/install logic**. A change is not considered cross-platform-safe merely because it passes on Linux.
14. **Update documentation when behavior or invariants change**. Documentation is part of the behavior contract.
15. **Use Graphify itself to understand Graphify**, except when the graph is the thing being debugged.
## Repository Architecture
- **Pipeline**: `detect()` → `extract()` → `build()` → `cluster()` → `analyze()` → `report.generate()` → `export.to_*()`
- **Where extractors live**: `graphify/extractors/`
- **Generated skills vs source fragments**: Skill files in `graphify/` are generated from fragments in `tools/skillgen/`.
- **What is generated and what is authoritative**: `tools/skillgen/fragments/` is authoritative.
## Development Setup
```bash
# Fork and clone the repository
git clone https://github.com/<your-username>/graphify.git
cd graphify
git remote add upstream https://github.com/Graphify-Labs/graphify.git
git fetch upstream
git checkout -b my-feature-branch upstream/v8 # Always branch off upstream v8, never commit directly to v8
# Set up the environment
uv sync
uv run pre-commit install
# Run the test suite to confirm your setup
uv run pytest tests/ -q
# Run linters and type checkers before pushing
uv run ruff check .
uv run pyright
```
- **Python versions**: 3.10+
- **uv**: We use `uv` for dependency management.
## Working on the Codebase
- **Use graphify itself**: Before making non-trivial architectural changes, use `graphify query ...` to navigate the codebase rather than blind grepping. Do not use the graph as evidence when the task concerns the graph's own correctness.
- **Update graph after code changes**: `graphify update .`
- **Root/path invariants**: Paths resolve relative to the calling module or scan root.
- **Cache considerations**: Be aware of relative/absolute path caching across rebuilds.
- **Generated skill files**: Regenerate with `uv run python -m tools.skillgen --bless`. Never hand-edit the generated files directly.
- **Corpus boundaries**: Do not create a second interpretation of the corpus boundary. Reuse the existing detection/ignore semantics whenever another pass walks project files (e.g. `.graphifyignore`).
- **Cross-platform**: Windows portability is a first-class contribution concern. Path separators, symlinks, absolute/relative paths, hash seeds, and shell interpolation must work correctly on Windows.
## Making a Change
1. Find or create an issue
2. Reproduce
3. Identify invariant
4. Make smallest fix
5. Add regression test
6. Run targeted tests
7. Run full suite (`uv run pytest tests`)
8. Run lint/type checks (`uv run ruff check .`, `uv run pyright`)
9. Regenerate artifacts if you touched their sources (`uv run python -m tools.skillgen --bless`).
## Tests
- **pytest**: The primary test runner.
- **Fixture conventions**: New language extractors need fixtures under `tests/fixtures/` and tests in `tests/test_languages.py`.
- **Environment isolation**: Tests must not accidentally depend on the contributor's ambient environment. When writing backend/provider tests, explicitly isolate or clear environment variables (e.g., `OPENAI_API_KEY`, `OLLAMA_HOST`).
- **Deterministic tests**: Ensure tests don't rely on ambient state or ordering.
- **Regression-test expectations**: Test must fail on pre-fix and pass on post-fix.
## Language Extractors
- **Extractor module**: Defines logic for each language AST.
- **Dispatch table**: Registers the parser and language.
- **Tree-sitter dependency**: Use ASTs where possible.
- **Fixture**: Ensure comprehensive test cases in `tests/fixtures/`.
- **Cross-file resolution considerations**: Resolution stays local to AST paths.
## Generated Skills and Monoliths
- Source fragments are authoritative.
- Run skillgen (`uv run python -m tools.skillgen --bless`).
- Never casually edit generated artifacts.
- Sanctioned round-trip changes only.
- Preserve multiset checks.
## Data Integrity Rules
- **Zero-node guard**: Must run before writes.
- **Shrink guard**: Must not persist smaller corrupt graphs. (Note: forced writes can bypass this).
- `to_json` before report side effects.
- **Cache consistency**: Must be maintained across absolute/relative paths. (e.g., The Windows absolute-path issue taught us that earlier side effects that persist bad absolute-path entries into the semantic cache are still data loss, even if the final graph write passes the shrink guard).
- **Provenance**: Must be preserved.
- **Cross-file edges**: Must be preserved during incremental updates, even if node count is unchanged.
## Security
- Review [SECURITY.md](SECURITY.md).
- Any change touching generated skill instructions, shell commands, subprocesses, URL ingestion, path handling, prompts, or serialization must be reviewed as a security-sensitive change.
- Never interpolate untrusted content into shell/Python.
## Commit Messages
Use a conventional-commit prefix (e.g., `fix:`, `feat:`, `docs:`, `fix(extract):`) and make the subject describe the change. Explain why in the body when the change is non-trivial. Reference the relevant issue/PR.
- **AI Authorship Disclosure**: If an AI coding assistant materially contributed to the implementation, disclose it in the commit metadata according to the repository's authorship convention (e.g., `Co-Authored-By: Claude <noreply@anthropic.com>`). Do not attribute code to a model that did not contribute.
## Pull Requests
- One concern per PR.
- No unrelated changes.
- Describe problem / implementation / verification.
- List commands actually run.
- Document limitations / unsupported cases.
- Keep description synchronized with final implementation.
- Rebase/resolve conflicts before requesting final review.
## Issue Reports
### Bugs
Include exact version/commit, environment, minimal reproduction, expected vs actual, logs, graph/cache artifacts where relevant, and whether a clean checkout reproduced it.
### Feature Requests
Focus on the problem first, proposed behavior, alternatives, and compatibility considerations.
## Review Expectations
- Correctness, regression coverage, scope, determinism, provenance, security, and documentation.
## Release / Generated Artifacts
- **What gets regenerated**: Skill files via skillgen, HTML exports.
- **What should not be committed**: Local cache (`.graphify_cached.json`), generated node artifacts outside of the expected outputs.
## Getting Help
- **Discord**: Join the [Graphify Discord](https://discord.gg/XDnKVpzdXB) for questions and discussion.
- **Issues**: Search [existing issues](https://github.com/Graphify-Labs/graphify/issues) before opening a new one.
- **Discussions**: Use GitHub issues for bugs and feature requests, Discord for open-ended questions.
## Further Reading
- [README.md](README.md)
- [ARCHITECTURE.md](ARCHITECTURE.md)
- [SECURITY.md](SECURITY.md)
- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)
- [RELEASING.md](RELEASING.md) (maintainers)
+198 -17
View File
@@ -1,21 +1,202 @@
MIT License
Copyright (c) 2026 Safi Shamsi
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
1. Definitions.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Safi Shamsi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+8
View File
@@ -0,0 +1,8 @@
Graphify
Copyright 2026 Safi Shamsi and the Graphify contributors.
This product is licensed under the Apache License, Version 2.0 (see LICENSE).
Portions of this software were contributed under the MIT License prior to the
relicensing and remain available under those terms. The original MIT license
text is retained in LICENSE-MIT.
+322 -107
View File
@@ -1,37 +1,64 @@
<p align="center">
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="docs/translations/README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="docs/translations/README.fil-PH.md">Filipino</a>
<a href="https://trendshift.io/repositories/25296?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-25296" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/25296" alt="Graphify-Labs%2Fgraphify | Trendshift" width="250" height="55"/></a>
</p>
<div align="center">
<details><summary><b>Read this in other languages</b></summary>
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇷 <a href="docs/translations/README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="docs/translations/README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="docs/translations/README.fil-PH.md">Filipino</a> | 🇮🇱 <a href="docs/translations/README.he-IL.md">עברית</a>
</details>
</div>
<p align="center">
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-blue" alt="License: Apache-2.0"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
</p>
<p align="center">
<a href="https://star-history.com/#safishamsi/graphify&Date">
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
</a>
<b>Try the graphify platform free for 14 days: <a href="https://app.graphify.com/login">app.graphify.com</a></b>
</p>
Type `/graphify` in your AI coding assistant and it maps your entire project — code, docs, PDFs, images, videos — into a knowledge graph you can query instead of grepping through files.
Type `/graphify` in your AI coding assistant and it maps your entire project (code, docs, PDFs, images, videos) into a **knowledge graph** you can **query instead of grepping** through files.
Works in Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, Devin CLI, and Google Antigravity.
- **Code maps for free, fully local.** Code is parsed with tree-sitter AST: deterministic, no LLM, nothing leaves your machine. (Docs, PDFs, images and video use your assistant's model, or a configured API key, for a semantic pass.)
- **Every edge is explained.** Each connection is tagged `EXTRACTED` (explicit in the source) or `INFERRED` (resolved by graphify), so you can tell what was read directly from what was inferred.
- **Not a vector index.** No embeddings, no vector store: a real graph you traverse. Ask a question, trace the path between two things, or explain one concept.
> Want this always-on, updating in the background across your code, docs, and meetings rather than only on demand? That is what we are building at **[graphify.com](https://graphify.com)**, and early access is open now at **[app.graphify.com](https://app.graphify.com/login)**.
<p align="center">
<img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graph-hero.png" alt="graphify's interactive graph.html showing the FastAPI codebase as a force-directed knowledge graph with a legend of detected communities" width="900">
</p>
<p align="center">
<em>The FastAPI codebase mapped by graphify. Every node is a concept, colors are detected communities, and the whole thing is clickable in graph.html.</em>
</p>
**Get started** (30 seconds):
```bash
uv tool install graphifyy # install the CLI (or: pipx install graphifyy)
graphify install # register the skill with your AI assistant
```
Then, in your AI assistant:
```
/graphify .
```
That's it. You get three files:
That's it. You get **three files**:
```
graphify-out/
@@ -40,12 +67,68 @@ graphify-out/
└── graph.json the full graph — query it anytime without re-reading your files
```
For a readable architecture page with Mermaid call-flow diagrams, run:
**Works in** Claude Code, Cursor, Codex, Gemini CLI, GitHub Copilot, and 15+ more — [pick your platform](#install).
```bash
graphify export callflow-html
---
## See it in action
<p align="center">
<img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/demo-path.svg" alt="graphify path query: a terminal asks for the shortest path between FastAPI and ModelField, and the answer lights up hop by hop across the knowledge graph" width="900">
</p>
Once the graph is built you query it instead of reading files. Real output, graphify run on the FastAPI codebase shown above:
```text
$ graphify explain "APIRouter"
Node: APIRouter
Source: routing.py L2210
Community: 2
Degree: 47
Connections (47):
--> RequestValidationError [uses] [INFERRED]
--> Dependant [uses] [INFERRED]
--> .get() [method] [EXTRACTED]
<-- __init__.py [imports] [EXTRACTED]
...
$ graphify path "FastAPI" "ModelField"
Shortest path (3 hops):
FastAPI --uses--> DefaultPlaceholder <--references-- get_request_handler() --references--> ModelField
```
Every edge carries a **confidence tag** (`EXTRACTED` = explicit in the source, `INFERRED` = derived by resolution), so you can tell what was read directly from what was inferred. `graphify query "<question>"` returns a scoped subgraph for a plain-language question, and `graphify path A B` traces how any two things connect.
---
## What it does
What you get out of the box:
| Capability | What you get |
|---|---|
| **God nodes** | The most-connected concepts, so you see what everything flows through |
| **Communities** | The graph split into subsystems (Leiden), with LLM-free labels |
| **Cross-file links** | `calls` / `imports` / `inherits` / `mixes_in` resolved across ~40 languages via tree-sitter AST |
| **Query, path, explain** | Ask a question, trace the path between two things, or explain one concept, all against `graph.json` |
| **Rationale + doc refs** | `# NOTE:` / `# WHY:` comments and ADR/RFC citations become first-class nodes linked to the code |
| **Beyond code** | Docs, PDFs, images, and video/audio all map into the same graph |
| **Local-first** | Code is parsed locally with tree-sitter (no LLM, nothing leaves your machine); only the semantic pass over docs/media calls a backend, and only if you configure one |
---
## Benchmarks
| Benchmark | Metric | graphify | Field |
|---|---|---|---|
| LOCOMO (n=300) | recall@10 | **0.497** | mem0 0.048, supermemory 0.149 |
| LOCOMO (n=300) | QA accuracy | 45.3% | supermemory 49.7%, mem0 27.3% |
| LongMemEval-S (n=50) | QA accuracy | **76%** | tied with dense RAG |
| Graph build | LLM credits | **0** | per-token for most systems |
Every system ran on the same harness with the same model and budgets, scored by a judge blind-validated against a second judge (90.6% agreement, Cohen's kappa 0.81). Full per-system tables, the code-intelligence result, and reproduction commands: **[BENCHMARKS.md](./BENCHMARKS.md)**.
---
## Prerequisites
@@ -79,10 +162,12 @@ curl -LsSf https://astral.sh/uv/install.sh | sh
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
The official source repository is [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
**Step 1 — install the package:**
```bash
# Recommended (uv puts graphify on PATH automatically):
# Recommended (isolated env; if 'graphify' isn't found after, run: uv tool update-shell):
uv tool install graphifyy
# Alternatives:
@@ -115,18 +200,24 @@ for example `graphify claude install --project` or `graphify codex install --pro
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell.
> **`graphify: command not found`?** Use `uv tool install graphifyy` or `pipx install graphifyy` — both put the CLI on PATH automatically. With plain `pip`, add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify`.
> **`graphify: command not found`?** `uv tool install` / `pipx install` put the `graphify` command in their tool bin dir (`~/.local/bin`). If your shell can't find it right after install — common on a fresh macOS + zsh setup — that dir isn't on your `PATH` yet: run `uv tool update-shell` (or `pipx ensurepath`), then open a new terminal. With plain `pip`, add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify`.
> **Running with `uvx` / `uv tool run` instead of installing?** Name the package, not the command: `uvx --from graphifyy graphify install`. Plain `uvx graphify …` fails (`No solution found … no versions of graphify`) because `uv tool run` reads the first word as a *package*, and the package is `graphifyy` — the `graphify` command lives inside it.
> **Avoid `pip install` on Mac/Windows** if possible. The skill resolves Python at runtime from `graphify-out/.graphify_python`; if that points to a different environment than where `pip` installed the package, you'll get `ModuleNotFoundError: No module named 'graphify'`. `uv tool install` and `pipx install` isolate the package in their own env and avoid this entirely.
> **Git hooks and uv tool / pipx:** `graphify hook install` embeds the current interpreter path directly into the hook scripts at install time, so the post-commit hook fires correctly even in GUI git clients and CI runners where `~/.local/bin` is not on PATH. If you reinstall or upgrade graphify, re-run `graphify hook install` to refresh the embedded path.
### Pick your platform
> **Strict mode (Claude Code):** `graphify install --project --strict` makes the assistant actually use the graph. The default install *nudges* it to run `graphify query` before reading files; strict mode *blocks* the first raw source read of a session and redirects it to the graph, then reverts to the nudge (so it fires at most once per session and never gets stuck). Toggle at runtime with `GRAPHIFY_HOOK_STRICT=1`/`0`; the default install is unchanged (soft nudge).
<details>
<summary><b>Pick your platform</b> (20+ assistants, click to expand)</summary>
| Platform | Install command |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install --platform windows` |
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| Kilo Code | `graphify install --platform kilo` |
@@ -141,18 +232,23 @@ for example `graphify claude install --project` or `graphify codex install --pro
| Hermes | `graphify install --platform hermes` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Agent Skills (cross-framework) | `graphify install --platform agents` (alias `--platform skills`) |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify install --platform pi` |
| Cursor | `graphify cursor install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
> Codex users: also add `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as Claude Code. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support `PreToolUse` hooks, so AGENTS.md is the always-on mechanism.
`--platform agents` (alias `--platform skills`) targets the generic cross-framework [Agent-Skills](https://github.com/anthropics/skills) locations: the spec's user-global `~/.agents/skills/` (read by `npx skills` and spec-compliant frameworks) for a global install, and `./.agents/skills/` for a project (`--project`) install. The bare `graphify install` stays single-platform (Claude Code) by design — use the named `agents` platform when you want the skill discoverable by any framework that reads `.agents/skills`.
> Codex uses `$graphify` instead of `/graphify`.
### Optional extras
</details>
Install only what you need:
<details>
<summary><b>Optional extras</b> (install only what you need)</summary>
| Extra | What it adds | Install |
|---|---|---|
@@ -162,8 +258,9 @@ Install only what you need:
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` |
| `mcp` | MCP stdio server | `uv tool install "graphifyy[mcp]"` |
| `neo4j` | Neo4j push support | `uv tool install "graphifyy[neo4j]"` |
| `falkordb` | FalkorDB push support | `uv tool install "graphifyy[falkordb]"` |
| `svg` | SVG graph export | `uv tool install "graphifyy[svg]"` |
| `leiden` | Leiden community detection (Python < 3.13 only) | `uv tool install "graphifyy[leiden]"` |
| `leiden` | Leiden community detection (graspologic on Python < 3.13; native backend on 3.13+) | `uv tool install "graphifyy[leiden]"` |
| `ollama` | Ollama local inference | `uv tool install "graphifyy[ollama]"` |
| `openai` | OpenAI / OpenAI-compatible APIs | `uv tool install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
@@ -174,9 +271,15 @@ Install only what you need:
| `postgres` | Live PostgreSQL introspection (`--postgres DSN`) | `uv tool install "graphifyy[postgres]"` |
| `dm` | BYOND DreamMaker `.dm`/`.dme` AST extraction (may need a C compiler + `python3-dev` if no wheel matches your platform) | `uv tool install "graphifyy[dm]"` |
| `terraform` | Terraform / HCL `.tf`/`.tfvars`/`.hcl` AST extraction | `uv tool install "graphifyy[terraform]"` |
| `pascal` | Pascal / Delphi `.pas`/`.dpr`/`.dpk`/`.inc` AST extraction (more accurate `calls`/`inherits` edges; falls back to a regex extractor when absent) | `uv tool install "graphifyy[pascal]"` |
| `ocaml` | OCaml `.ml`/`.mli` AST extraction | `uv tool install "graphifyy[ocaml]"` |
| `commonlisp` | Common Lisp `.lisp`/`.cl`/`.lsp`/`.asd` AST extraction | `uv tool install "graphifyy[commonlisp]"` |
| `robot` | Robot Framework `.robot`/`.resource` extraction (suites, test cases, keywords, keyword-call and resource/library import edges) | `uv tool install "graphifyy[robot]"` |
| `chinese` | Chinese query segmentation (jieba) | `uv tool install "graphifyy[chinese]"` |
| `all` | Everything above | `uv tool install "graphifyy[all]"` |
</details>
---
## Make your assistant always use the graph
@@ -186,6 +289,7 @@ Run this once in your project after building a graph:
| Platform | Command |
|----------|---------|
| Claude Code | `graphify claude install` |
| CodeBuddy | `graphify codebuddy install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| Kilo Code | `graphify kilo install` |
@@ -201,21 +305,31 @@ Run this once in your project after building a graph:
| Hermes | `graphify hermes install` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Agent Skills (cross-framework) | `graphify agents install` (alias `graphify skills install`) |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify pi install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions — preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files. On platforms that support payload-bearing hooks (Claude Code, Gemini CLI), a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path. On the others (Codex, OpenCode, Cursor, etc.), the persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance. `GRAPH_REPORT.md` is still available for broad architecture review.
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions, preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files.
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path.
- **Instruction-file platforms** (Codex, OpenCode, Cursor, etc.): persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance.
`GRAPH_REPORT.md` is still available for broad architecture review.
**CodeBuddy** does the same two things as Claude Code: writes a `CODEBUDDY.md` section telling CodeBuddy to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs `PreToolUse` hooks (`.codebuddy/settings.json`) that fire before Bash search commands and file reads, nudging toward `graphify query` instead.
**Codex** writes to `AGENTS.md`, which is what actually carries the always-on graph guidance on this platform. `graphify codex install` also registers a `PreToolUse` hook in `.codex/hooks.json` (`graphify hook-check`), but that entry is deliberately a **no-op**: Codex Desktop rejects `hookSpecificOutput.additionalContext` on `PreToolUse`, so emitting a nudge there would break Bash tool calls. Unlike Claude Code, where the hook (`graphify hook-guard`) does the nudging, on Codex the hook fires and intentionally does nothing, and `AGENTS.md` is the always-on mechanism.
**Kilo Code** installs the Graphify skill to `~/.config/kilo/skills/graphify/SKILL.md` and a native `/graphify` command to `~/.config/kilo/command/graphify.md`. `graphify kilo install` also writes `AGENTS.md` plus a native `tool.execute.before` plugin (`.kilo/plugins/graphify.js` + `.kilo/kilo.json` or `.kilo/kilo.jsonc` registration) so Kilo gets the same always-on graph reminder behavior through native `.kilo` config.
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true`, so Cursor includes it in every conversation automatically, no hook needed.
To remove graphify from all platforms at once: `graphify uninstall` (add `--purge` to also delete `graphify-out/`). Or use the per-platform command (e.g. `graphify claude uninstall`).
---
**Kilo Code** installs the Graphify skill to `~/.config/kilo/skills/graphify/SKILL.md` and a native `/graphify` command to `~/.config/kilo/command/graphify.md`. `graphify kilo install` also writes `AGENTS.md` plus a native **`tool.execute.before` plugin** (`.kilo/plugins/graphify.js` + `.kilo/kilo.json` or `.kilo/kilo.jsonc` registration) so Kilo gets the same always-on graph reminder behavior through native `.kilo` config.
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
## What's in the report
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
@@ -230,11 +344,15 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| Type | Extensions |
|------|-----------|
| Code (28 tree-sitter grammars) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .csproj .fsproj .vbproj .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`) |
| Code (37 tree-sitter grammars) | `.py .ts .mts .cts .js .jsx .tsx .mjs .go .rs .java .c .cpp .cc .cxx .h .hpp .cu .cuh .metal .rb .cs .kt .kts .scala .php .swift .lua .luau .toc .zig .ps1 .psm1 .psd1 .ex .exs .m .mm .ml .mli .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .slnx .csproj .fsproj .vbproj .xaml .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`, `.ml`/`.mli` requires `uv tool install graphifyy[ocaml]`; `.mts`/`.cts` reuse the TypeScript grammar, `.cc`/`.cxx` and CUDA `.cu`/`.cuh` and Metal `.metal` reuse the C++ grammar) |
| 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]`) |
| OCaml | `.ml .mli` (requires `uv tool install graphifyy[ocaml]`) |
| Common Lisp | `.lisp .cl .lsp .asd` (requires `uv tool install graphifyy[commonlisp]`) |
| Robot Framework | `.robot .resource` (via the official `robot.api` parser, requires `uv tool install graphifyy[robot]`; suites, test cases, user keywords, keyword-call and Resource/Library/Variables import edges) |
| 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` |
@@ -242,7 +360,22 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| Video / Audio | `.mp4 .mov .mp3 .wav` and more (requires `uv tool install graphifyy[video]`) |
| YouTube / URLs | any video URL (requires `uv tool install graphifyy[video]`) |
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
Terraform module calls with a literal local `source` (`./...` or `../...`) link
to a directory module node through an `EXTRACTED` `module_source` edge. Each
directory node contains its scanned `.tf` files, so nested calls expose paths
such as environment → application → base → resource. Scan the common repository
root to include both callers and implementations. Paths resolve relative to the
calling module, and excluded or out-of-root files are never loaded implicitly.
Remote sources and source expressions are not resolved; `.tfvars`, generic
`.hcl`, and `.tf.json` files do not define module-source targets. References to
`module.app.output` still target the module call rather than its implementation's
output. The graph represents source configuration, not evaluated Terraform
instances. Incremental Terraform changes reconcile the scanned `.tf` corpus,
reusing cached syntax for unchanged files. After upgrading an existing graph,
run `graphify update .` once to regenerate Terraform IDs and topology.
Code is extracted **locally with no API calls** (AST via tree-sitter). Everything else goes through your AI assistant's model API.
Google Drive for desktop `.gdoc`, `.gsheet`, and `.gslides` files are shortcut
pointers, not document content. To include native Google Docs, Sheets, and Slides
@@ -279,7 +412,7 @@ graphify export callflow-html # Mermaid architecture/call-flow HTML (auto-r
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper and add it
/graphify add <youtube-url> # transcribe and add a video
graphify hook install # auto-rebuild on git commit
graphify hook install # auto-rebuild on commit + branch checkout (run `graphify update .` after `git pull` — see "Recommended workflow" below)
graphify merge-graphs a.json b.json # combine two graphs
graphify prs # PR dashboard: CI state, review status, worktree mapping
@@ -296,7 +429,9 @@ 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.
Pass `--no-gitignore` to `graphify extract` when git-ignored generated or transpiled code belongs in the graph. This disables `.gitignore` and `.git/info/exclude`; `.graphifyignore` still applies.
```
# .graphifyignore
@@ -314,21 +449,45 @@ dist/
## Team setup
`graphify-out/` is meant to be committed to git so everyone on the team starts with a map.
For users building a team graph, the `graphify-out/` directory is gitignored by default. If your team wants to share a graph, you should **explicitly force-add only the queryable products** so your teammates can consume them:
**Recommended `.gitignore` additions:**
```
graphify-out/cost.json # local only
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
*(Note: If you are contributing to the Graphify repository itself, do not commit your local `graphify-out/` at all unless it's a specific test fixture).*
**Recommended git commands to share a graph (you only need to force-add once; git will track future changes normally):**
```bash
git add -f graphify-out/graph.json
git add -f graphify-out/GRAPH_REPORT.md
# git add -f graphify-out/wiki/ # optional: if using the wiki export
# git add -f graphify-out/obsidian/ # optional: if using the Obsidian export
```
> `manifest.json` is now portable — keys are stored as relative paths and re-anchored on load, so committing it is safe and avoids a full rebuild on first checkout.
**Workflow:**
1. One person runs `/graphify .` and commits `graphify-out/`.
2. Everyone pulls — their assistant reads the graph immediately.
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost). This also sets up a git merge driver so `graph.json` is never left with conflict markers — two devs committing in parallel get their graphs union-merged automatically.
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
The remaining `graphify-out/` files stay machine-local and should **not** be force-added: `.graphify_root` and `.graphify_python` (absolute paths to this machine's scan root and interpreter), `.graphify_analysis.json`, the AST cache under `graphify-out/cache/`, and the `needs_update` flag. A teammate who pulls the shared `graph.json` can query it immediately; running `graphify update` re-anchors the committed `manifest.json` and rebuilds only what changed on their machine.
### Recommended workflow
Set this up once per clone. From then on, three of your normal git commands keep the graph current by themselves, and one keeps it in sync with your team:
| you do | graphify does |
|---|---|
| `graphify hook install` (once, right after cloning) | installs the hooks below, plus a merge driver so `graph.json` never shows conflict markers |
| `git commit` | rebuilds automatically — AST only, no API cost |
| `git checkout` / `git switch` (branches) | rebuilds automatically (a file-only `git checkout -- <path>` does not) |
| `git pull` / `git merge` | run `graphify update .` right after |
| `git push` | nothing to do |
The commit and branch-switch rebuilds run in the background and return immediately, so on a large repo the graph can lag the commit by a few seconds — step 5 covers the rare case where you query before it catches up.
**Step by step:**
1. Clone the repo and run `graphify hook install` once.
2. Commit and switch branches as normal — the graph stays current on its own.
3. After every `git pull` (or merge), run `graphify update .` to bring the graph in sync with what you just pulled. On a large or active repo, put it on autopilot with a pull alias:
```bash
git config --global alias.gpull '!git pull && graphify update .'
```
4. When docs or papers change, run `/graphify --update` to refresh those nodes too (code and docs update independently).
5. If a query ever seems to be missing something you just added, run `graphify update .` first, then ask again.
---
@@ -341,6 +500,7 @@ graphify query "what connects DigestAuth to Response?" --graph graphify-out/grap
# expose the graph as an MCP server (for repeated tool-call access)
python -m graphify.serve graphify-out/graph.json
python -m graphify.serve --graph graphify-out/graph.json # --graph flag also accepted
# register with Kimi Code:
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
@@ -389,8 +549,12 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
| Variable | Used for | When required |
|---|---|---|
| `ANTHROPIC_API_KEY` | Claude (Anthropic) backend | `--backend claude` |
| `ANTHROPIC_BASE_URL` | Anthropic-compatible endpoint URL (LiteLLM proxy, gateways, ...) | `--backend claude` (default: `https://api.anthropic.com`) |
| `ANTHROPIC_MODEL` | Model name for the Claude backend — for custom endpoints, use the model name/alias your server exposes | `--backend claude` (default: `claude-sonnet-4-6`) |
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Google Gemini backend | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` |
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` (local servers accept any non-empty value) |
| `OPENAI_BASE_URL` | OpenAI-compatible server URL (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (default: `https://api.openai.com/v1`) |
| `OPENAI_MODEL` | Model name for the OpenAI backend — for self-hosted servers, use the model name/alias your server exposes (check its `/v1/models` endpoint), e.g. `LFM2.5-8B-A1B-UD-Q4_K_XL` for llama.cpp | `--backend openai` (default: `gpt-4.1-mini`) |
| `DEEPSEEK_API_KEY` | DeepSeek backend | `--backend deepseek` |
| `MOONSHOT_API_KEY` | Kimi Code backend | `--backend kimi` |
| `OLLAMA_BASE_URL` | Ollama local inference URL | `--backend ollama` (default: `http://localhost:11434`) |
@@ -404,38 +568,59 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — standard credential chain | `--backend bedrock` (no API key, uses IAM) |
| `GRAPHIFY_MAX_WORKERS` | AST parallelism thread count | optional — also `--max-workers` flag |
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Raise output cap for dense corpora | optional — e.g. `32768` for large files |
| `GRAPHIFY_API_TIMEOUT` | Per-call timeout in seconds for HTTP, claude-cli, and Anthropic SDK backends (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_API_TIMEOUT` | Per-call timeout in seconds for HTTP, claude-cli, Anthropic SDK, and Bedrock backends (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_MAX_RETRIES` | How many times to retry a rate-limited (429) request before giving up (default: 6; honors `Retry-After`) | optional — raise for strict per-org limits (e.g. kimi); `0` disables |
| `GRAPHIFY_MAX_RETRY_DEPTH` | How deep a truncated chunk may be bisected and re-extracted (default: 3, so up to 8x sub-calls for one chunk) | optional — lower it to cap worst-case spend; `0` disables every retry (no bisection, no hollow-response retry), so a chunk costs exactly one call |
| `GRAPHIFY_FORCE` | Force graph rebuild even with fewer nodes | optional — also `--force` flag |
| `GRAPHIFY_GOOGLE_WORKSPACE` | Auto-enable Google Workspace export | optional — set to `1` |
| `GRAPHIFY_TRIAGE_BACKEND` | Backend for `graphify prs --triage` | optional — auto-detected from available keys |
| `GRAPHIFY_TRIAGE_MODEL` | Model override for triage | optional — e.g. `claude-opus-4-7` |
| `GRAPHIFY_QUERY_LOG` | Override query log path (default: `~/.cache/graphify-queries.log`) | optional — set to empty or `/dev/null` to silence |
| `GRAPHIFY_QUERY_LOG_DISABLE` | Set to `1` to disable query logging entirely | optional |
| `GRAPHIFY_QUERY_LOG_RESPONSES` | Set to `1` to also log full subgraph responses (off by default) | optional |
| `GRAPHIFY_QUERY_LOG_ENABLE` | Set to `1` to turn on the local query log at `~/.cache/graphify-queries.log` (records each query/path/explain question + corpus path). Off by default — nothing is written unless you opt in (#1797) | optional |
| `GRAPHIFY_QUERY_LOG` | Enable the query log and write it to this path instead of the default | optional — off unless this or `_ENABLE` is set |
| `GRAPHIFY_QUERY_LOG_DISABLE` | Set to `1` to force the query log off (wins over the enable vars) | optional |
| `GRAPHIFY_QUERY_LOG_RESPONSES` | When the log is enabled, also record full subgraph responses (off by default) | optional |
| `GRAPHIFY_NO_AUTO_REFRESH` | Set to `1` to stop the CLI from refreshing installed skills that are older than the package after an upgrade | optional — refresh is on by default |
| `GRAPHIFY_MAX_GRAPH_BYTES` | Override the 512 MiB graph.json size cap — e.g. `700MB`, `2GB`, or plain bytes | optional — useful for very large corpora |
| `GRAPHIFY_MAX_CONTEXTS` | Maximum number of non-default project graphs retained by one multi-project MCP server | optional — default: `8`; invalid values use `8`, and values below `1` use `1` |
| `GRAPHIFY_LLM_TEMPERATURE` | Override LLM temperature for semantic extraction — e.g. `0.7`, or `none` to omit | optional — auto-omitted for o1/o3/o4/gpt-5 reasoning models |
---
## Privacy
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine. A code-only corpus requires no API key — `graphify extract` runs fully offline.
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine. A code-only corpus requires no API key — `graphify extract` runs fully offline. On a mixed repo, add `--code-only` to index just the code and skip the docs/PDFs/images that would otherwise need an LLM.
- **Video / audio** — transcribed locally with faster-whisper. Nothing leaves your machine.
- **Docs, PDFs, images** — sent to your AI assistant for semantic extraction (via the `/graphify` skill, using whatever model your IDE session runs). Headless `graphify extract` requires `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), `DEEPSEEK_API_KEY` (DeepSeek), a running Ollama instance (`OLLAMA_BASE_URL`), AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM), or the `claude` CLI binary (Claude Code - no API key needed, uses your Claude subscription). The `--dedup-llm` flag uses the same key.
- **Data residency** — `graphify extract` auto-detects which provider to use based on which API key is set (priority: Gemini → Kimi → Claude → OpenAI → DeepSeek → Azure → Bedrock → Ollama). For code with data-residency requirements, use `--backend ollama` (fully local) or pass an explicit `--backend` flag. Kimi (`MOONSHOT_API_KEY`) routes to Moonshot AI servers in China.
- No telemetry, no usage tracking, no analytics.
- **No telemetry**, no usage tracking, no analytics.
- **Query logging** — every `graphify query`, `graphify path`, `graphify explain`, and MCP `query_graph` call is logged to `~/.cache/graphify-queries.log` in JSON Lines format (timestamp, question, corpus, nodes returned, duration). Full subgraph responses are **not** stored by default. Set `GRAPHIFY_QUERY_LOG_DISABLE=1` to opt out, or `GRAPHIFY_QUERY_LOG=/dev/null` to silence without disabling the code path.
---
## Troubleshooting
**`graphify: command not found` after `pip install graphifyy`**
pip installs scripts to a user bin directory that may not be on your PATH. Fix:
- macOS: add `~/Library/Python/3.x/bin` to your PATH in `~/.zshrc`
- Linux: add `~/.local/bin` to your PATH in `~/.bashrc`
- Or use `uv tool install graphifyy` / `pipx install graphifyy` — both manage PATH automatically.
**`graphify: command not found` after installing**
The CLI is installed but its bin directory isn't on your shell's `PATH`. Pick the fix for how you installed:
- **uv** (`uv tool install graphifyy`): the command lands in uv's tool bin dir (`~/.local/bin`), which a fresh macOS/zsh setup often doesn't have on `PATH`. Run `uv tool update-shell`, then open a new terminal. (Find the dir with `uv tool dir --bin`.)
- **pipx** (`pipx install graphifyy`): run `pipx ensurepath`, then open a new terminal.
- **pip** (`pip install graphifyy`): pip installs scripts to a user bin dir that may not be on `PATH` — add `~/Library/Python/3.x/bin` (macOS) or `~/.local/bin` (Linux) to your `PATH` in `~/.zshrc`/`~/.bashrc`, or just run `python -m graphify`.
**`uvx graphify …` or `uv tool run graphify …` fails to resolve `graphify`**
The PyPI package is `graphifyy`; `graphify` is only the command it provides. `uv tool run` treats the first word as a *package name*, so it looks for a package called `graphify` and reports `No solution found … no versions of graphify`. Name the package explicitly: `uvx --from graphifyy graphify install` (same as `uv tool run --from graphifyy graphify install`). Or `uv tool install graphifyy` once and then call `graphify` directly.
**`uv run --with graphifyy python -m graphify` silently runs an older install**
`uv run` uses your *system* Python, so if an older `graphifyy` also lives there (e.g. a past `pip install graphifyy`), Python can find that copy first on `sys.path` and `--with graphifyy` won't override it. It runs with no error, but you get the *old* version's behavior — e.g. env overrides like `OPENAI_BASE_URL` are silently ignored, so requests hit the default endpoint and fail with a 401 that looks like a bad key. The fingerprint is a `warning: skill is from graphify <newer>, package is <older>` line — that means a different install was loaded, not just a stale skill. Check which copy actually loaded:
```bash
python -c "import graphify; print(graphify.__file__)"
```
Then run the installed command directly (it uses the uv-managed copy), or drop the stale system copy:
```bash
uvx --from graphifyy graphify extract . --backend openai # names the package explicitly
pip uninstall graphifyy # or remove the old system install
```
**`python -m graphify` works but `graphify` command doesn't**
Your shell's PATH doesn't include the Python scripts directory. Use `uv` or `pipx` instead of plain `pip`.
Your shell's `PATH` doesn't include the bin directory the command was installed to. Prefer `uv tool install` / `pipx install` over plain `pip`, then run `uv tool update-shell` / `pipx ensurepath` and open a new terminal (see the install notes above).
**`/graphify .` causes "path not recognized" in PowerShell**
PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash) on Windows.
@@ -443,6 +628,9 @@ PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash)
**Graph has fewer nodes after `--update` or rebuild**
If a refactor deleted files, the old nodes linger. Pass `--force` (or set `GRAPHIFY_FORCE=1`) to overwrite even when the rebuild has fewer nodes.
**`extract` exits with "extraction was incomplete ... refusing to overwrite"**
When an extraction pass crashes or a walk can't fully read the corpus, the run would be smaller than a complete one, so `graphify extract` refuses to overwrite a larger existing graph with the partial result (protecting your `graph.json`). Fix the underlying failure and re-run, or pass `--allow-partial` to overwrite anyway.
**Graph has duplicate nodes for the same entity (ghost duplicates)**
Ghost duplicates (same symbol appearing twice — once from AST extraction with a source location, once from semantic extraction without) are now automatically merged at build time. If you see this in a graph built before v0.8.33, run a full re-extract to clean up:
```bash
@@ -455,6 +643,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
@@ -465,6 +661,13 @@ graphify query "..."
**`graph.json` has conflict markers after two devs commit at once**
Run `graphify hook install` — it sets up a git merge driver that union-merges `graph.json` automatically so conflicts never happen.
**Graph doesn't reflect a teammate's recent changes**
Run `graphify update .` right after `git pull` or any merge — see [Recommended workflow](#recommended-workflow). Commits and branch switches update the graph automatically via the installed hooks; syncing with a pull is the one step you run yourself. Fold it into a pull alias so it's one command either way:
```bash
git config --global alias.gpull '!git pull && graphify update .'
```
Confirm the hooks are active with `graphify hook status`; re-run `graphify hook install` after an interpreter upgrade/reinstall to refresh them.
**Extraction returns empty nodes/edges for docs or PDFs**
Docs, PDFs, and images require an LLM call — code-only corpora need no key. Check that your API key is set and the backend is correct:
```bash
@@ -472,10 +675,18 @@ ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
**Skill version mismatch warning in your IDE**
Your installed graphify version is different from the skill file. Update:
Your installed graphify version is different from the skill file. After an upgrade, the first `graphify` command refreshes every installed skill that is older than the package, on all platforms at once, and keeps a locally edited `SKILL.md` as `SKILL.md.bak`. Set `GRAPHIFY_NO_AUTO_REFRESH=1` to turn this off. A skill it can't refresh safely keeps the warning: one newer than the package, or a directory that two installers share (for example Copilot and `graphify vscode install`). Reinstall that platform by hand:
```bash
uv tool upgrade graphifyy
graphify install # overwrites the skill file
graphify install --platform <name> # overwrites the skill file
```
**Claude Code prompt cache invalidated after every `graphify extract`**
Graphify writes output files (`graph.json`, `graphify-out/`) into the workspace. If those paths aren't ignored, every write invalidates Claude Code's prompt cache, forcing a full re-upload at cache-write rates on the next turn. Add them to `.claudeignore`:
```text
# .claudeignore
graph.json
graphify-out/
```
---
@@ -486,16 +697,20 @@ graphify install # overwrites the skill file
/graphify # run on current directory
/graphify ./raw # run on a specific folder
/graphify ./raw --mode deep # more aggressive relationship extraction
graphify extract ./raw --code-only # index code only — local AST, no API key (skips docs/PDFs/images); an `extract` flag, not a skill flag
/graphify ./raw --update # re-extract only changed files
/graphify ./raw --directed # preserve edge direction
/graphify ./raw --cluster-only # rerun clustering on existing graph
/graphify ./raw --no-viz # skip HTML visualization
/graphify ./raw --obsidian # generate Obsidian vault
/graphify ./raw --obsidian --obsidian-dir ~/vault # write into an existing vault (never overwrites your own notes or .obsidian config)
/graphify ./raw --wiki # build agent-crawlable markdown wiki
/graphify ./raw --svg # export graph.svg
/graphify ./raw --graphml # export for Gephi / yEd
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687
/graphify ./raw --falkordb # generate cypher.txt for FalkorDB
/graphify ./raw --falkordb-push falkordb://localhost:6379
/graphify ./raw --watch # auto-sync as files change
/graphify ./raw --mcp # start MCP stdio server
@@ -508,6 +723,14 @@ graphify install # overwrites the skill file
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
graphify save-result --question "Q" --answer "A" --nodes Foo Bar --outcome useful # record how a Q&A turned out (work memory; outcome ∈ useful|dead_end|corrected)
graphify reflect # aggregate graphify-out/memory/ outcomes into reflections/LESSONS.md
graphify reflect --if-stale # no-op when LESSONS.md is already newer than every input (cheap to run each session)
graphify reflect --out docs/LESSONS.md # write the lessons doc somewhere else
graphify reflect --graph graphify-out/graph.json # group lessons by community + write the work-memory overlay (.graphify_learning.json)
# the overlay tags nodes preferred/tentative/contested (recency-weighted, with provenance);
# graphify explain / query then show a "Lesson:" hint, flagged "code changed — re-verify" when the source moved on
graphify uninstall # remove from all platforms in one shot
graphify uninstall --purge # also delete graphify-out/
graphify uninstall --project --platform codex # remove project-scoped install files only
@@ -519,6 +742,8 @@ graphify hook status
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codebuddy install # CODEBUDDY.md + PreToolUse hook (CodeBuddy)
graphify codebuddy uninstall
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify kilo install # native Kilo skill + /graphify command + AGENTS.md + .kilo plugin
@@ -543,6 +768,8 @@ graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
graphify hermes uninstall
graphify amp install # skill file (Amp)
graphify amp uninstall
graphify agents install # ~/.agents/skills/ + AGENTS.md (cross-framework; alias: graphify skills)
graphify agents uninstall
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
graphify kiro uninstall
graphify pi install # skill file (Pi coding agent)
@@ -556,6 +783,8 @@ graphify extract ./docs # headless LLM extraction for CI
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock, or claude-cli
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL) - no API key needed for loopback
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # any OpenAI-compatible server (llama.cpp, vLLM, LM Studio)
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # any Anthropic-compatible endpoint (LiteLLM proxy, gateways)
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # override KV-cache window (auto-sized by default)
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # unload model after each chunk (saves VRAM on small GPUs)
graphify extract ./docs --backend bedrock # AWS Bedrock via IAM - no API key, uses AWS credential chain
@@ -563,14 +792,18 @@ graphify extract ./docs --backend claude-cli # route through Claude Code CLI -
graphify extract ./docs --backend azure # Azure OpenAI (set AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT)
graphify extract ./docs --max-workers 16 # AST parallelism (also GRAPHIFY_MAX_WORKERS)
graphify extract --postgres "postgresql://user:pass@host/db" # introspect live PostgreSQL schema directly
graphify extract ./my-workspace --cargo # introspect Rust Cargo workspace dependencies directly
graphify extract ./docs --token-budget 30000 # smaller semantic chunks for local/small models
graphify extract ./docs --max-concurrency 2 # fewer parallel LLM calls (useful for local inference)
graphify extract ./docs --api-timeout 900 # longer HTTP timeout for slow local models (default 600s)
graphify extract ./docs --google-workspace # export .gdoc/.gsheet/.gslides via gws before extraction
graphify extract ./src --no-gitignore # include git-ignored source; still honor .graphifyignore
graphify extract ./docs --mode deep # richer semantic extraction via extended system prompt
graphify extract ./docs --no-cluster # raw extraction only, skip clustering
graphify extract ./docs --timing # print per-stage wall-clock timings to stderr (also works on cluster-only)
graphify extract ./docs --force # overwrite graph.json even if new graph has fewer nodes (use after refactors or to clear ghost duplicates)
graphify extract ./docs --dedup-llm # LLM tiebreaker for ambiguous entity pairs (uses same API key)
graphify extract ./src --no-dedup # skip entity dedup; on an incremental merge this also arms the shrink guard that refuses to drop untouched files' nodes
graphify extract ./docs --global --as myrepo # extract and register into the cross-project global graph
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # raise output cap for dense corpora
@@ -579,7 +812,7 @@ graphify export callflow-html --max-sections 8 # cap generated architecture
graphify export callflow-html --output docs/arch.html
graphify export callflow-html ./some-repo/graphify-out
graphify global add graphify-out/graph.json myrepo # register a project graph into ~/.graphify/global.json
graphify global add graphify-out/graph.json --as myrepo # register a project graph into ~/.graphify/global-graph.json
graphify global remove myrepo # remove a project from the global graph
graphify global list # show all registered repos + node/edge counts
graphify global path # print path to the global graph file
@@ -603,12 +836,14 @@ graphify update ./src --no-cluster # skip reclustering, write raw AST graph onl
graphify update ./src --force # overwrite even if new graph has fewer nodes
graphify cluster-only ./my-project
graphify cluster-only ./my-project --graph path/to/graph.json # custom graph location
graphify cluster-only ./my-project --max-concurrency 16 --batch-size 200 # parallel community labeling (large graphs)
graphify cluster-only ./my-project --resolution 1.5 # more, smaller communities
graphify cluster-only ./my-project --exclude-hubs 99 # exclude p99 degree nodes from partitioning
graphify cluster-only ./my-project --no-label # keep "Community N" placeholders
graphify cluster-only ./my-project --backend=gemini # backend for community naming
graphify cluster-only ./my-project --backend=gemini --model gemini-2.5-pro # specific model
graphify label ./my-project # (re)name communities with the configured backend
graphify label ./my-project --backend=openai # force a specific backend
graphify label ./my-project --backend=openai --model gpt-4o # force a specific backend and model
```
> **Community names:** inside an agent (Claude Code, Gemini CLI) the agent names communities itself. When you run the bare CLI, `cluster-only` auto-names them with the configured backend (built-in or custom OpenAI-compatible provider) — pass `--no-label` to keep `Community N`, or run `graphify label` to (re)generate names on demand.
@@ -617,69 +852,49 @@ graphify label ./my-project --backend=openai # force a specifi
## Learn more
- [docs.graphify.com](https://docs.graphify.com) — full documentation: guides, command reference, and integrations
- [How it works](docs/how-it-works.md) — the extraction pipeline, community detection, confidence scoring, benchmarks
- [ARCHITECTURE.md](ARCHITECTURE.md) — module breakdown, how to add a language
- [Optional integrations](docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
- [The Memory Layer](https://safishamsi.gumroad.com/l/qetvlo) — the book on the ideas behind graphify, the architecture end to end
---
## Built on graphify — Penpax
## graphify Enterprise
[**Penpax**](https://graphifylabs.ai) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working life: meetings, browser history, emails, files, and code, updating continuously in the background.
[**graphify Enterprise**](https://graphify.com/enterprise) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working context: meetings, files, docs, and code, updating continuously in the background.
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
Built for people and teams whose work lives across hundreds of conversations and documents they can never fully reconstruct.
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
**[Join the waitlist at graphify.com](https://graphify.com).** Free trial launching soon.
---
<details>
<summary>Contributing</summary>
## Contributing
### Development setup
Contributions are welcome. See **[CONTRIBUTING.md](CONTRIBUTING.md)** for the development setup, the test and CI-parity commands, the git workflow, and what makes a strong contribution (worked examples and extraction bug reports are the most useful). Architecture and how to add a language: [ARCHITECTURE.md](ARCHITECTURE.md).
The project uses [uv](https://docs.astral.sh/uv/) for dev workflow. Install it once, then:
New here? Say hi on [Discord](https://discord.gg/XDnKVpzdXB) or in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
```bash
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v8 # active development branch
---
# Create the project venv and install graphify + all extras + the dev group
# (pytest). uv installs the dev dependency group by default; pass --no-dev to
# skip it.
uv sync --all-extras
```
## Contributors
Verify the editable install:
```bash
uv run graphify --version
uv run python -c "import graphify; print(graphify.__file__)"
```
<a href="https://github.com/Graphify-Labs/graphify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=Graphify-Labs/graphify" alt="graphify contributors" />
</a>
### Running tests
Made with [contrib.rocks](https://contrib.rocks).
```bash
uv run pytest tests/ -q # run the full suite
uv run pytest tests/test_extract.py -q # one module
uv run pytest tests/ -q -k "python" # filter by name
```
---
> macOS note: the test suite includes both `sample.f90` and `sample.F90` fixtures. These collide on case-insensitive HFS+ / APFS file systems. Run on Linux or in a Docker container if you need to test both Fortran variants simultaneously.
## Community and links
### Git workflow
- Active development happens on the `v8` branch.
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
- Before opening a PR, run `uv run pytest tests/ -q` and confirm it passes.
- Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py` for any new language extractor.
### What to contribute
**Worked examples** are the most useful contribution. Run `/graphify` on a real corpus, save the output to `worked/{slug}/`, write an honest `review.md` covering what the graph got right and wrong, and open a PR.
**Extraction bugs** — open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or wrong.
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
</details>
<p align="center">
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
</p>
+49
View File
@@ -0,0 +1,49 @@
# Releasing graphify
Maintainer-facing release process. Contributors do not need this; see
[CONTRIBUTING.md](CONTRIBUTING.md) for how to propose changes.
graphify publishes to PyPI (package name `graphifyy`) automatically through
GitHub trusted publishing. There is no manual `twine` upload and no API token to
manage.
## Steps
1. **Bump the version.** Edit `version` in `pyproject.toml`.
2. **Update the changelog.** Add a dated section for the new version at the top of
`CHANGELOG.md`, crediting each landed PR and its author.
3. **Refresh the lock.** Run `uv lock` so `uv.lock` records the new version (and
any dependency changes).
4. **Test on both supported interpreters.** Run the full suite on Python 3.10 and
3.13:
```bash
uv run pytest
# and against a 3.13 environment, e.g.
uv run --python 3.13 pytest
```
5. **Commit and push `v8`.** Commit the version, changelog, and lock together,
then `git push origin v8`.
6. **Cut the GitHub release.** Tag the release off `v8`:
```bash
gh release create vX.Y.Z --repo Graphify-Labs/graphify --target v8 \
--title "vX.Y.Z" --notes-file <notes>
```
Publishing the release fires `publish.yml` on the `release-published` event,
which builds the wheel/sdist and uploads to PyPI via trusted publishing. Do
**not** run `twine` or pass a token.
7. **Verify the install** once PyPI has the new version (the JSON API updates
before the install index; use `--refresh`):
```bash
uvx --refresh --from graphifyy==X.Y.Z graphify --version
```
## Version numbering
Keep public versions contiguous. If a number was bumped locally but never
published to PyPI, reuse that number for the next release rather than leaving a
gap.
## Supported versions
Security fixes target only the latest released `0.9.x`. See
[SECURITY.md](SECURITY.md).
+8 -7
View File
@@ -4,8 +4,8 @@
| Version | Supported |
|---------|-----------|
| 0.3.x | Yes |
| < 0.3 | No |
| Latest 0.9.x | Yes |
| < 0.9 | No |
## Reporting a Vulnerability
@@ -18,11 +18,11 @@ Report security issues via GitHub's private vulnerability reporting, or email th
- Potential impact
- Suggested fix (if any)
We will acknowledge receipt within 48 hours and aim to release a fix within 7 days for critical issues.
We will acknowledge receipt as soon as possible and work with you to release a coordinated fix.
## Security Model
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis - only during `ingest` (explicit URL fetch by the user).
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. Its network boundaries are: AST/code extraction is local and deterministic; semantic extraction may send content to a configured model/backend; `ingest` uses explicit outbound fetch; HTTP MCP is an opt-in network listener.
### Threat Surface
@@ -32,16 +32,17 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
| XSS in graph HTML output | `security.sanitize_label()` strips control characters and caps at 256 chars. (Note: HTML escaping happens separately in the HTML exporter, not in `sanitize_label()`). |
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
| Prompt injection via source file content | During the semantic pass, source files are attacker-controlled text mixed into the LLM context. `_read_files()` in `llm.py` wraps every file in a hash-stamped `<untrusted_source path=... sha256=...>` delimiter block, the extraction system prompt instructs the model to treat that block as inert data and never as instructions, and `_neutralise_injection_sentinels()` defangs known chat-template/jailbreak tokens (`<\|im_start\|>`, `[INST]`, `<<SYS>>`, forged `</untrusted_source>`, etc.) before insertion. This is the table-stakes defense (issue #1210): it does not make injection impossible, but changes it from "works on first try" to "requires evasion." |
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
| Symlink traversal | `os.walk(..., followlinks=False)` is parameterized to avoid unchecked traversal where appropriate. |
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
### What graphify does NOT do
- Does not run a network listener (MCP server communicates over stdio only)
- Does not run a network listener by default (stdio transport); `--transport http` is opt-in, documented in the README, and binds to `127.0.0.1` unless `--host 0.0.0.0` is passed
- Does not execute code from source files (tree-sitter parses ASTs - no eval/exec)
- Does not use `shell=True` in any subprocess call
- Does not store credentials or API keys
+32
View File
@@ -0,0 +1,32 @@
# Getting help with graphify
Thanks for using graphify. Here is where to go, depending on what you need.
## Questions, ideas, and usage help
- **Docs:** [docs.graphify.com](https://docs.graphify.com) — guides, command reference, and integrations. Start here.
- **GitHub Discussions:** [Discussions](https://github.com/Graphify-Labs/graphify/discussions) for longer-form questions, ideas, and show-and-tell.
- **Discord:** [discord.gg/XDnKVpzdXB](https://discord.gg/XDnKVpzdXB) for real-time chat with the community and maintainers.
Please search the docs and existing discussions/issues before posting — your question may already be answered.
## Bug reports
Open a [bug report](https://github.com/Graphify-Labs/graphify/issues/new/choose). To help us reproduce it quickly, include:
- what you expected and what actually happened,
- the smallest input that reproduces it (a sample file or repo helps a lot),
- the relevant cache entry from `graphify-out/cache/` for an extraction bug,
- your OS, Python version, and `graphify --version`.
## Feature requests
Open a [feature request](https://github.com/Graphify-Labs/graphify/issues/new/choose) describing the problem you are trying to solve, not only the solution you have in mind.
## Security vulnerabilities
Do **not** open a public issue. Report privately via the [security policy](https://github.com/Graphify-Labs/graphify/security/policy). See [SECURITY.md](SECURITY.md).
## Contributing
Want to help? See [CONTRIBUTING.md](CONTRIBUTING.md). Worked examples and extraction bug reports are the most useful contributions.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 360" width="900" height="360" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" role="img" aria-label="graphify path query lighting up a knowledge graph"><defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0c1712"/><stop offset="1" stop-color="#0f1e18"/></linearGradient><radialGradient id="glow" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#62c4a2" stop-opacity="0.35"/><stop offset="1" stop-color="#62c4a2" stop-opacity="0"/></radialGradient></defs><rect x="1" y="1" width="898" height="358" rx="14" fill="url(#bg)" stroke="#20342b" stroke-width="1.5"/><line x1="336" y1="18" x2="336" y2="342" stroke="#1c2c25" stroke-width="1"/><circle cx="28" cy="30" r="4.5" fill="#ff5f56"/><circle cx="46" cy="30" r="4.5" fill="#ffbd2e"/><circle cx="64" cy="30" r="4.5" fill="#27c93f"/><text x="320" y="34" text-anchor="end" font-size="10" fill="#6f8a7f">graphify</text><text x="20" y="74" font-size="11" fill="#4db18f" font-weight="600">$</text><text x="33.2" y="74" font-size="11" fill="#c6d6ce" opacity="0">g<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.035;0.047;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="39.9" y="74" font-size="11" fill="#c6d6ce" opacity="0">r<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0408;0.0528;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="46.5" y="74" font-size="11" fill="#c6d6ce" opacity="0">a<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0466;0.0586;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="53.1" y="74" font-size="11" fill="#c6d6ce" opacity="0">p<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0524;0.0644;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="59.7" y="74" font-size="11" fill="#c6d6ce" opacity="0">h<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0582;0.0702;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="66.3" y="74" font-size="11" fill="#c6d6ce" opacity="0">i<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.064;0.076;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="73.0" y="74" font-size="11" fill="#c6d6ce" opacity="0">f<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0698;0.0818;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="79.6" y="74" font-size="11" fill="#c6d6ce" opacity="0">y<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0756;0.0876;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="92.8" y="74" font-size="11" fill="#c6d6ce" opacity="0">p<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0872;0.0992;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="99.4" y="74" font-size="11" fill="#c6d6ce" opacity="0">a<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.093;0.105;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="106.1" y="74" font-size="11" fill="#c6d6ce" opacity="0">t<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0988;0.1108;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="112.7" y="74" font-size="11" fill="#c6d6ce" opacity="0">h<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1046;0.1166;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="125.9" y="74" font-size="11" fill="#c6d6ce" opacity="0">"<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1162;0.1282;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="132.5" y="74" font-size="11" fill="#c6d6ce" opacity="0">F<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.122;0.134;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="139.2" y="74" font-size="11" fill="#c6d6ce" opacity="0">a<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1278;0.1398;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="145.8" y="74" font-size="11" fill="#c6d6ce" opacity="0">s<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1336;0.1456;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="152.4" y="74" font-size="11" fill="#c6d6ce" opacity="0">t<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1394;0.1514;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="159.0" y="74" font-size="11" fill="#c6d6ce" opacity="0">A<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1452;0.1572;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="165.6" y="74" font-size="11" fill="#c6d6ce" opacity="0">P<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.151;0.163;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="172.3" y="74" font-size="11" fill="#c6d6ce" opacity="0">I<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1568;0.1688;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="178.9" y="Line truncated

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 634 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 931 KiB

+3
View File
@@ -88,6 +88,9 @@ The output `graph.json` uses NetworkX's node-link format. Each node has:
- `file_type` — `code`, `document`, `paper`, `image`, `rationale`
- `source_file` — where it came from
See [RFC: file-level node summaries](node-summaries-rfc.md) for two proposed
ways to add compact optional summaries for AI navigation.
Each edge has:
- `source`, `target` — node IDs
- `relation` — verb phrase (e.g. `calls`, `imports`, `implements`, `semantically_similar_to`)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

+186
View File
@@ -0,0 +1,186 @@
# RFC: file-level node summaries
This RFC proposes an optional way for graphify to expose compact file-level
summaries for AI coding agents.
## Problem
`graph.json` gives agents graph structure, source files, node labels, and
relationships. That helps avoid reading an entire repository, but agents still
often need to inspect raw files just to answer a basic navigation question:
> What is this file or node responsible for?
A short summary near the graph node could reduce repeated file reads during
`graphify query`, `graphify explain`, MCP node lookup, and graph navigation.
## Goals
- Help agents choose relevant files with less context.
- Preserve graphify's offline, deterministic behavior by default.
- Keep the first implementation small and reviewable.
- Avoid adding long prose to `GRAPH_REPORT.md`.
- Leave room for a future opt-in LLM-generated summary backend.
## Non-goals
- Summarizing every function, method, or local symbol in the first version.
- Calling an LLM or remote API by default.
- Replacing `graphify explain`; summaries should make `explain` more useful.
- Turning `GRAPH_REPORT.md` into a full per-file index.
## Shared constraints for either option
- Start with file-level nodes only.
- Keep each summary bounded, for example one sentence or roughly 200-300
characters.
- Generate deterministic summaries first from existing local signal:
module docstrings, top comments, exported symbols, imports, relation counts,
and community/context data.
- Do not emit summaries by default until the storage model is agreed on.
- Display a summary in `graphify explain <node>` when one exists.
- Include summaries in `graphify serve` / MCP node lookup when one exists.
## Proposed summary contents
Each file-level summary should give an agent enough signal to decide whether to
inspect the file, without replacing the file or bloating graph output.
Recommended fields:
| Field | Why it helps agents |
| --- | --- |
| `summary` | One bounded sentence describing the file's responsibility. This is the main token-saving field. |
| `source_file` | Lets the agent jump to the right file without resolving a node ID manually. |
| `label` | Keeps the summary readable in CLI, MCP, and UI contexts. |
| `generated_by` | Distinguishes deterministic summaries from future LLM-generated summaries. |
| `summary_version` | Allows the format to evolve without guessing how an older summary was produced. |
Recommended signal inside the `summary` sentence:
| Signal | Why it belongs in the sentence |
| --- | --- |
| Module docstring or top comment | Usually the highest-quality human-authored purpose statement. |
| Exported classes/functions/symbols | Tells the agent what API surface the file provides. |
| Important imports or dependencies | Reveals whether the file belongs to auth, database, UI, CLI, test, etc. |
| Dominant graph relations | Shows whether the file mainly calls, imports, defines, contains, or references other nodes. |
| Community or nearby hub label | Gives architectural context without reading the whole community report. |
| Source location coverage when available | Helps distinguish a file-level summary from a symbol-level explanation. |
Example:
```json
{
"label": "extract.py",
"source_file": "graphify/extract.py",
"summary": "Extracts source files into graph nodes and relationships; defines language parsers and import/call extraction helpers.",
"generated_by": "deterministic",
"summary_version": 1
}
```
The summary should not include long call chains, full dependency lists, raw code,
or every symbol in the file. Those details already belong in the graph and can
be fetched through `graphify explain`, `graphify query`, or direct file reads
when needed.
## Option A: `summary` attribute in `graph.json`
Add an optional `summary` field to file-level nodes:
```json
{
"id": "graphify_extract",
"label": "extract.py",
"file_type": "code",
"source_file": "graphify/extract.py",
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
}
```
Possible user flow:
```bash
graphify . --summarize-nodes
graphify explain "extract.py"
```
Pros:
- Single artifact for graph consumers.
- Matches NetworkX node attributes and existing node metadata.
- Easy for `explain`, `serve`, visualizers, and MCP tools to consume.
- No sidecar freshness or node-ID join logic.
Cons:
- Adds text to the core graph artifact.
- Expands the graph schema surface.
- Consumers that dump all of `graph.json` into an LLM context would pay for all
summaries at once.
## Option B: sidecar `node-summaries.json`
Write summaries to a separate artifact keyed by node ID:
```json
{
"version": 1,
"generator": "deterministic",
"nodes": {
"graphify_extract": {
"label": "extract.py",
"source_file": "graphify/extract.py",
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
}
}
}
```
Possible user flow:
```bash
graphify summarize
graphify explain "extract.py"
```
Pros:
- Keeps `graph.json` lean and topology-focused.
- Makes summaries clearly optional.
- Can be regenerated independently.
- Provides a natural place for future generator metadata.
Cons:
- Adds a second artifact that consumers must discover and load.
- Introduces freshness and synchronization questions.
- Every consumer that wants summaries must join by node ID.
## Suggested first implementation once storage is chosen
1. Add deterministic file-level summary generation.
2. Store summaries using the selected option.
3. Surface summaries in `graphify explain`.
4. Surface summaries in `graphify serve` / MCP node lookup.
5. Add tests for default behavior, generated summaries, missing summaries, and
bounded summary length.
## Follow-up ideas
- Add opt-in LLM-generated summaries with explicit provider/backend selection.
- Extend summaries to class or module-level nodes if file-level summaries prove
useful.
- Allow `graphify query` to include summaries for returned nodes under a budget.
- Add cache/freshness metadata if summaries are generated separately from the
main graph.
## Questions for maintainers and users
1. Should graphify prefer one artifact (`graph.json`) or keep generated text in a
sidecar?
2. Should deterministic file-level summaries be generated during graph creation,
or only through an explicit command such as `graphify summarize`?
3. Is `summary` the right term, or would `synopsis` better communicate a short,
bounded description?
4. What summary length budget would be acceptable for large repositories?
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
<div dir="rtl">
@@ -79,7 +79,7 @@ pip install graphifyy && graphify install
<div dir="rtl">
> **الحزمة الرسمية:** اسم حزمة PyPI هو `graphifyy` (تثبيت بـ `pip install graphifyy`). الحزم الأخرى المسماة `graphify*` على PyPI ليست تابعة لهذا المشروع. المستودع الرسمي الوحيد هو [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **الحزمة الرسمية:** اسم حزمة PyPI هو `graphifyy` (تثبيت بـ `pip install graphifyy`). الحزم الأخرى المسماة `graphify*` على PyPI ليست تابعة لهذا المشروع. المستودع الرسمي الوحيد هو [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
### دعم المنصات
@@ -174,4 +174,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. استخراج دلال
</div>
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Oficiální balíček:** Balíček PyPI se jmenuje `graphifyy`. Jediné oficiální úložiště je [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Oficiální balíček:** Balíček PyPI se jmenuje `graphifyy`. Jediné oficiální úložiště je [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Použití
@@ -74,4 +74,4 @@ Kódové soubory jsou zpracovávány lokálně prostřednictvím tree-sitter AST
[**Penpax**](https://safishamsi.github.io/penpax.ai) je enterprise vrstva nad graphify. **Bezplatná zkušební verze brzy.** [Přidejte se na čekací listinu →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Officiel pakke:** PyPI-pakken hedder `graphifyy`. Det eneste officielle lager er [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Officiel pakke:** PyPI-pakken hedder `graphifyy`. Det eneste officielle lager er [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Brug
@@ -74,4 +74,4 @@ Kodefiler behandles lokalt via tree-sitter AST. Videoer transskriberes lokalt me
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oven på graphify. **Gratis prøveperiode kommer snart.** [Tilmeld dig ventelisten →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**Eine KI-Coding-Assistent-Skill.** Tippe `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro oder Google Antigravity — es liest deine Dateien, baut einen Wissensgraphen und gibt dir Struktur zurück, die du vorher nicht sehen konntest. Verstehe eine Codebasis schneller. Finde das „Warum" hinter Architekturentscheidungen.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Offizielles Paket:** Das PyPI-Paket heißt `graphifyy` (installieren mit `pip install graphifyy`). Andere Pakete mit Namen `graphify*` auf PyPI sind nicht mit diesem Projekt verbunden. Das einzige offizielle Repository ist [safishamsi/graphify](https://github.com/safishamsi/graphify). CLI und Skill-Befehl heißen weiterhin `graphify`.
> **Offizielles Paket:** Das PyPI-Paket heißt `graphifyy` (installieren mit `pip install graphifyy`). Andere Pakete mit Namen `graphify*` auf PyPI sind nicht mit diesem Projekt verbunden. Das einzige offizielle Repository ist [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify). CLI und Skill-Befehl heißen weiterhin `graphify`.
> **`graphify: command not found`?** Verwende `uv tool install graphifyy` (empfohlen) oder `pipx install graphifyy` — beide platzieren die CLI an einem verwalteten Ort, der automatisch im PATH ist. Mit einfachem `pip` musst du möglicherweise `~/.local/bin` (Linux) oder `~/Library/Python/3.x/bin` (Mac) zum PATH hinzufügen, oder `python -m graphify` verwenden.
@@ -177,4 +177,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantische Extraktion v
## Star-Verlauf
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Επίσημο πακέτο:** Το πακέτο PyPI ονομάζεται `graphifyy`. Το μοναδικό επίσημο αποθετήριο είναι το [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Επίσημο πακέτο:** Το πακέτο PyPI ονομάζεται `graphifyy`. Το μοναδικό επίσημο αποθετήριο είναι το [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Χρήση
@@ -74,4 +74,4 @@ graphify update ./src
Το [**Penpax**](https://safishamsi.github.io/penpax.ai) είναι το εταιρικό επίπεδο πάνω από το graphify. **Δωρεάν δοκιμή σύντομα.** [Εγγραφείτε στη λίστα αναμονής →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**Una habilidad para asistentes de código IA.** Escribe `/graphify` en Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro o Google Antigravity — lee tus archivos, construye un grafo de conocimiento y te devuelve estructura que no sabías que existía. Entiende una base de código más rápido. Encuentra el «por qué» detrás de las decisiones arquitectónicas.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Paquete oficial:** El paquete PyPI se llama `graphifyy` (instalar con `pip install graphifyy`). Otros paquetes llamados `graphify*` en PyPI no están afiliados con este proyecto. El único repositorio oficial es [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Paquete oficial:** El paquete PyPI se llama `graphifyy` (instalar con `pip install graphifyy`). Otros paquetes llamados `graphify*` en PyPI no están afiliados con este proyecto. El único repositorio oficial es [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
### Soporte de plataformas
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extracción semántica v
## Historial de estrellas
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+572
View File
@@ -0,0 +1,572 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇷 <a href="README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a>
</p>
<p align="center">
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
</p>
<div dir="rtl">
**یک مهارت برای دستیار کدنویسی هوش مصنوعی.** `/graphify` را در Claude Code، Codex، OpenCode، Kilo Code، Cursor، Gemini CLI، GitHub Copilot CLI، VS Code Copilot Chat، Aider، Amp، OpenClaw، Factory Droid، Trae، Hermes، Kimi Code، Kiro، Pi، Devin CLI یا Google Antigravity تایپ کنید — تمام پروژه‌تان را می‌خواند، یک گراف دانش می‌سازد، و ساختاری که نمی‌دانستید وجود دارد را به شما بازمی‌گرداند. کدبیس را سریع‌تر درک کنید. «چرا»ی پشت تصمیمات معماری را کشف کنید.
کاملاً چندوجهی. کد، PDF، مارک‌داون، اسکرین‌شات، نمودار، عکس وایت‌بورد، تصاویر به زبان‌های دیگر، یا فایل‌های ویدئو و صوتی بریزید — graphify مفاهیم و روابط را از همه آن‌ها استخراج کرده و در یک گراف به هم متصل می‌کند. ویدئوها به‌صورت محلی با Whisper رونویسی می‌شوند. ۳۶ زبان برنامه‌نویسی از طریق tree-sitter AST پشتیبانی می‌شوند.
> Andrej Karpathy یک پوشه `/raw` نگه می‌دارد که در آن مقالات، توییت‌ها، اسکرین‌شات‌ها و یادداشت‌ها می‌ریزد. graphify پاسخ آن مشکل است — **۷۱.۵ برابر** کمتر توکن در هر پرس‌وجو در مقایسه با خواندن فایل‌های خام، در طول جلسات پایدار، و صادق در مورد آنچه پیدا شده در برابر آنچه استنباط شده است.
</div>
```
/graphify .
```
<div dir="rtl">
همین. سه فایل دریافت می‌کنید:
</div>
```
graphify-out/
├── graph.html در هر مرورگری باز کنید — روی گره‌ها کلیک کنید، فیلتر کنید، جستجو کنید
├── GRAPH_REPORT.md نکات کلیدی: مفاهیم محوری، اتصالات شگفت‌انگیز، سؤالات پیشنهادی
└── graph.json گراف کامل — هر زمان بدون نیاز به بازخوانی فایل‌ها پرس‌وجو کنید
```
<div dir="rtl">
برای یک صفحه معماری خوانا با نمودارهای جریان فراخوانی Mermaid، اجرا کنید:
</div>
```bash
graphify export callflow-html
```
---
<div dir="rtl">
## پیش‌نیازها
</div>
| پیش‌نیاز | حداقل | بررسی | نصب |
|---|---|---|---|
| Python | ۳.۱۰+ | `python --version` | [python.org](https://www.python.org/downloads/) |
| uv *(پیشنهادی)* | هر نسخه | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| pipx *(جایگزین)* | هر نسخه | `pipx --version` | `pip install pipx` |
<div dir="rtl">
**نصب سریع macOS (Homebrew):**
</div>
```bash
brew install python@3.12 uv
```
<div dir="rtl">
**نصب سریع Windows:**
</div>
```powershell
winget install astral-sh.uv
```
<div dir="rtl">
**Ubuntu/Debian:**
</div>
```bash
sudo apt install python3.12 python3-pip pipx
# یا نصب uv:
curl -LsSf https://astral.sh/uv/install.sh | sh
```
---
<div dir="rtl">
## نصب
> **بسته رسمی:** بسته PyPI به نام `graphifyy` است (با دو y). سایر بسته‌های `graphify*` در PyPI وابسته به این پروژه نیستند. دستور CLI همچنان `graphify` است.
**مرحله ۱ — نصب بسته:**
</div>
```bash
# پیشنهادی (uv به‌طور خودکار graphify را در PATH قرار می‌دهد):
uv tool install graphifyy
# جایگزین‌ها:
pipx install graphifyy
pip install graphifyy # ممکن است نیاز به تنظیم PATH داشته باشد — یادداشت زیر را ببینید
```
<div dir="rtl">
**مرحله ۲ — ثبت مهارت در دستیار هوش مصنوعی:**
</div>
```bash
graphify install
```
<div dir="rtl">
همین. دستیار هوش مصنوعی‌تان را باز کنید و `/graphify .` تایپ کنید.
برای نصب مهارت دستیار در مخزن جاری به‌جای پروفایل کاربری، `--project` اضافه کنید:
</div>
```bash
graphify install --project
graphify install --project --platform codex
```
<div dir="rtl">
> **یادداشت PowerShell:** از `graphify .` استفاده کنید نه `/graphify .` — اسلش ابتدایی در PowerShell جداکننده مسیر است.
> **`graphify: command not found`؟** از `uv tool install graphifyy` یا `pipx install graphifyy` استفاده کنید — هر دو CLI را به‌طور خودکار در PATH قرار می‌دهند.
### انتخاب پلتفرم
</div>
| پلتفرم | دستور نصب |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install` (تشخیص خودکار) یا `graphify install --platform windows` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| Kilo Code | `graphify install --platform kilo` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify install --platform pi` |
| Cursor | `graphify cursor install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
<div dir="rtl">
### افزونه‌های اختیاری
فقط آنچه نیاز دارید نصب کنید:
</div>
| افزونه | چه چیزی اضافه می‌کند | نصب |
|---|---|---|
| `pdf` | استخراج PDF | `uv tool install "graphifyy[pdf]"` |
| `office` | پشتیبانی از `.docx` و `.xlsx` | `uv tool install "graphifyy[office]"` |
| `google` | رندرینگ Google Sheets | `uv tool install "graphifyy[google]"` |
| `video` | رونویسی ویدئو/صوت | `uv tool install "graphifyy[video]"` |
| `mcp` | سرور MCP stdio | `uv tool install "graphifyy[mcp]"` |
| `neo4j` | پشتیبانی از Neo4j | `uv tool install "graphifyy[neo4j]"` |
| `ollama` | استنتاج محلی Ollama | `uv tool install "graphifyy[ollama]"` |
| `openai` | OpenAI / APIهای سازگار با OpenAI | `uv tool install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
| `anthropic` | Anthropic Claude API | `uv tool install "graphifyy[anthropic]"` |
| `bedrock` | AWS Bedrock (از IAM استفاده می‌کند) | `uv tool install "graphifyy[bedrock]"` |
| `sql` | استخراج طرح SQL | `uv tool install "graphifyy[sql]"` |
| `all` | همه موارد بالا | `uv tool install "graphifyy[all]"` |
---
<div dir="rtl">
## دستیار را همیشه از گراف استفاده کنید
پس از ساخت گراف، یک بار در پروژه‌تان اجرا کنید:
</div>
| پلتفرم | دستور |
|----------|---------|
| Claude Code | `graphify claude install` |
| CodeBuddy | `graphify codebuddy install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| Kilo Code | `graphify kilo install` |
| GitHub Copilot CLI | `graphify copilot install` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify aider install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Amp | `graphify amp install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
<div dir="rtl">
این یک فایل پیکربندی کوچک می‌نویسد که به دستیارتان می‌گوید برای سؤالات مربوط به کدبیس، گراف دانش را مشورت بگیرد. برای حذف graphify از همه پلتفرم‌ها به یکباره: `graphify uninstall` (با `--purge` برای حذف `graphify-out/` نیز).
---
## محتوای گزارش
- **گره‌های اصلی** — پرارتباط‌ترین مفاهیم پروژه. همه چیز از این‌ها عبور می‌کند.
- **اتصالات شگفت‌انگیز** — پیوندهایی بین چیزهایی که در فایل‌ها یا ماژول‌های مختلف زندگی می‌کنند. بر اساس میزان غیرمنتظره بودن رتبه‌بندی شده.
- **«چرا»** — نظرات درون‌خطی (`# NOTE:`، `# WHY:`، `# HACK:`)، داک‌استرینگ‌ها و منطق طراحی از اسناد به‌عنوان گره‌های جداگانه مرتبط با کدی که توضیح می‌دهند استخراج می‌شوند.
- **سؤالات پیشنهادی** — ۴ تا ۵ سؤال که گراف به‌طور منحصربه‌فرد می‌تواند پاسخ دهد.
- **برچسب‌های اطمینان** — هر رابطه استنباط‌شده با `EXTRACTED`، `INFERRED` یا `AMBIGUOUS` علامت‌گذاری می‌شود. همیشه می‌دانید چه چیزی پیدا شده در برابر چه چیزی حدس زده شده.
---
## فایل‌های پشتیبانی‌شده
</div>
| نوع | پسوندها |
|------|-----------|
| کد (۳۶ دستور زبان tree-sitter) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .vue .svelte .dart` و بیشتر |
| اسناد | `.md .mdx .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (نیاز به `graphifyy[office]`) |
| PDF | `.pdf` |
| تصاویر | `.png .jpg .webp .gif` |
| ویدئو / صوت | `.mp4 .mov .mp3 .wav` و بیشتر (نیاز به `graphifyy[video]`) |
| YouTube / URLها | هر URL ویدئویی (نیاز به `graphifyy[video]`) |
<div dir="rtl">
کد به‌صورت محلی با tree-sitter بدون هیچ فراخوانی API استخراج می‌شود. بقیه از طریق API مدل دستیار هوش مصنوعی شما پردازش می‌شوند.
---
## دستورات رایج
</div>
```bash
/graphify . # ساخت گراف برای پوشه جاری
/graphify ./docs --update # فقط فایل‌های تغییریافته را مجدداً استخراج کن
/graphify . --cluster-only # خوشه‌بندی مجدد بدون استخراج مجدد
/graphify . --no-viz # فقط گزارش + JSON، بدون HTML
/graphify . --wiki # ساخت ویکی مارک‌داون از گراف
graphify export callflow-html # HTML معماری/جریان فراخوانی Mermaid
/graphify query "چه چیزی auth را به پایگاه داده متصل می‌کند؟"
/graphify path "UserService" "DatabasePool"
/graphify explain "RateLimiter"
/graphify add https://arxiv.org/abs/1706.03762 # یک مقاله را واکشی و اضافه کن
/graphify add <youtube-url> # رونویسی و اضافه کردن ویدئو
graphify hook install # بازسازی خودکار پس از هر commit
graphify merge-graphs a.json b.json # ترکیب دو گراف
graphify prs # داشبورد PR: وضعیت CI، بررسی، تأثیر گراف
graphify prs 42 # بررسی عمیق PR شماره ۴۲
graphify prs --triage # رتبه‌بندی صف بررسی با هوش مصنوعی
```
<div dir="rtl">
[مرجع کامل دستورات](#full-command-reference) را ببینید.
---
## نادیده گرفتن فایل‌ها
یک `.graphifyignore` در ریشه پروژه بسازید — همان سینتکس `.gitignore`، از جمله نفی با `!`.
**`.gitignore` به‌طور خودکار رعایت می‌شود.** اگر `.graphifyignore` در یک دایرکتوری وجود نداشته باشد، graphify به `.gitignore` آن دایرکتوری بازمی‌گردد.
</div>
```
# .graphifyignore
node_modules/
dist/
*.generated.py
# فقط src/ را ایندکس کن، بقیه را نادیده بگیر
*
!src/
!src/**
```
---
<div dir="rtl">
## تنظیمات تیمی
`graphify-out/` برای commit شدن در git طراحی شده تا همه در تیم با یک نقشه شروع کنند.
**افزودن‌های پیشنهادی به `.gitignore`:**
</div>
```
graphify-out/cost.json # فقط محلی
# graphify-out/cache/ # اختیاری: برای سرعت commit کنید، برای کوچک نگه داشتن repo حذف کنید
```
<div dir="rtl">
**جریان کار:**
۱. یک نفر `/graphify .` اجرا می‌کند و `graphify-out/` را commit می‌کند.
۲. همه pull می‌کنند — دستیارشان فوراً گراف را می‌خواند.
۳. `graphify hook install` را اجرا کنید تا پس از هر commit به‌طور خودکار بازسازی شود.
۴. وقتی اسناد یا مقالات تغییر کردند، `/graphify --update` اجرا کنید.
---
## استفاده مستقیم از گراف
</div>
```bash
# پرس‌وجو از گراف در ترمینال
graphify query "جریان احراز هویت را نشان بده"
graphify query "چه چیزی DigestAuth را به Response متصل می‌کند؟" --graph graphify-out/graph.json
# نمایش گراف به‌عنوان سرور MCP
python -m graphify.serve graphify-out/graph.json
# یا سرویس‌دهی از طریق HTTP برای دسترسی تیمی:
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
```
<div dir="rtl">
سرور MCP دسترسی ساختاریافته می‌دهد: `query_graph`، `get_node`، `get_neighbors`، `shortest_path`، `list_prs`، `get_pr_impact`، `triage_prs`.
---
## متغیرهای محیطی
اینها فقط برای **استخراج بدون نمایشگر / CI** (`graphify extract`) لازم هستند. هنگام اجرا از طریق مهارت `/graphify` داخل IDE، API مدل توسط جلسه IDE شما تأمین می‌شود.
</div>
| متغیر | استفاده | شرط لزوم |
|---|---|---|
| `ANTHROPIC_API_KEY` | بک‌اند Claude (Anthropic) | `--backend claude` |
| `GEMINI_API_KEY` یا `GOOGLE_API_KEY` | بک‌اند Google Gemini | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI یا APIهای سازگار | `--backend openai` |
| `DEEPSEEK_API_KEY` | بک‌اند DeepSeek | `--backend deepseek` |
| `MOONSHOT_API_KEY` | بک‌اند Kimi Code | `--backend kimi` |
| `OLLAMA_BASE_URL` | URL استنتاج محلی Ollama | `--backend ollama` |
| `AZURE_OPENAI_API_KEY` | بک‌اند Azure OpenAI | `--backend azure` |
| `GRAPHIFY_MAX_WORKERS` | تعداد thread های موازی AST | اختیاری |
| `GRAPHIFY_FORCE` | بازسازی اجباری گراف | اختیاری |
| `GRAPHIFY_QUERY_LOG_DISABLE` | برای غیرفعال کردن ثبت پرس‌وجو `1` تنظیم کنید | اختیاری |
---
<div dir="rtl">
## حریم خصوصی
- **فایل‌های کد** — به‌صورت محلی از طریق tree-sitter پردازش می‌شوند. هیچ چیزی دستگاه شما را ترک نمی‌کند.
- **ویدئو / صوت** — به‌صورت محلی با faster-whisper رونویسی می‌شوند. هیچ چیزی دستگاه شما را ترک نمی‌کند.
- **اسناد، PDF‌ها، تصاویر** — برای استخراج معنایی به API مدل دستیار هوش مصنوعی شما ارسال می‌شوند.
- بدون تله‌متری، بدون ردیابی استفاده، بدون آنالیتیکس.
---
## عیب‌یابی
**`graphify: command not found` پس از `pip install graphifyy`**
pip اسکریپت‌ها را در دایرکتوری bin کاربر نصب می‌کند که ممکن است در PATH نباشد:
- macOS: `~/Library/Python/3.x/bin` را به PATH در `~/.zshrc` اضافه کنید
- Linux: `~/.local/bin` را به PATH در `~/.bashrc` اضافه کنید
- یا از `uv tool install graphifyy` / `pipx install graphifyy` استفاده کنید.
**`/graphify .` در PowerShell "path not recognized" نشان می‌دهد**
PowerShell `/` ابتدایی را به‌عنوان جداکننده مسیر در نظر می‌گیرد. از `graphify .` (بدون اسلش) در Windows استفاده کنید.
**گراف پس از `--update` یا بازسازی گره کمتری دارد**
اگر یک refactor فایل‌ها را حذف کرده، گره‌های قدیمی باقی می‌مانند. `--force` (یا `GRAPHIFY_FORCE=1`) را پاس دهید:
</div>
```bash
graphify extract . --force
```
<div dir="rtl">
**استخراج برای اسناد یا PDF‌ها گره/یال خالی برمی‌گرداند**
اسناد، PDF‌ها و تصاویر به یک فراخوانی LLM نیاز دارند. بررسی کنید API key تنظیم شده و بک‌اند صحیح است:
</div>
```bash
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
---
<div dir="rtl">
## مرجع کامل دستورات
</div>
```
/graphify # اجرا روی دایرکتوری جاری
/graphify ./raw # اجرا روی پوشه مشخص
/graphify ./raw --mode deep # استخراج رابطه‌های عمیق‌تر
/graphify ./raw --update # فقط فایل‌های تغییریافته را مجدداً استخراج کن
/graphify ./raw --directed # حفظ جهت یال‌ها
/graphify ./raw --cluster-only # خوشه‌بندی مجدد روی گراف موجود
/graphify ./raw --no-viz # بدون HTML بصری‌سازی
/graphify ./raw --obsidian # تولید Obsidian vault
/graphify ./raw --wiki # ساخت ویکی مارک‌داون قابل خزیدن برای agent
/graphify ./raw --svg # خروجی graph.svg
/graphify ./raw --graphml # خروجی برای Gephi / yEd
/graphify ./raw --neo4j # تولید cypher.txt برای Neo4j
/graphify ./raw --watch # همگام‌سازی خودکار با تغییر فایل‌ها
/graphify ./raw --mcp # شروع سرور MCP stdio
/graphify add https://arxiv.org/abs/1706.03762
/graphify add <video-url>
/graphify query "چه چیزی attention را به optimizer متصل می‌کند؟"
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
graphify uninstall # حذف از همه پلتفرم‌ها
graphify uninstall --purge # همچنین graphify-out/ را حذف کن
graphify hook install # hook های post-commit + post-checkout
graphify hook uninstall
graphify hook status
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify codex install # AGENTS.md + PreToolUse hook (Codex)
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
graphify amp install # فایل مهارت (Amp)
graphify kiro install # .kiro/skills/ + .kiro/steering/ (Kiro)
graphify devin install # فایل مهارت + .windsurf/rules/ (Devin CLI)
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
graphify extract ./docs # استخراج بدون نمایشگر برای CI
graphify extract ./docs --backend gemini # بک‌اند صریح
graphify extract ./docs --backend ollama # Ollama محلی - بدون نیاز به API key
graphify extract ./docs --backend bedrock # AWS Bedrock از طریق IAM
graphify extract --postgres "postgresql://user:pass@host/db" # طرح PostgreSQL زنده
graphify prs # داشبورد PR
graphify prs 42 # بررسی عمیق PR شماره ۴۲
graphify prs --triage # رتبه‌بندی هوش مصنوعی
graphify prs --conflicts # PR هایی که جوامع گراف را به اشتراک می‌گذارند
graphify export callflow-html # HTML معماری/جریان فراخوانی
graphify merge-graphs a.json b.json --out merged.json
graphify --version
```
---
<div dir="rtl">
## بیشتر بدانید
- [نحوه عملکرد](../../docs/how-it-works.md) — پایپ‌لاین استخراج، تشخیص جامعه، امتیازدهی اطمینان، معیارها
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — تقسیم‌بندی ماژول‌ها، نحوه اضافه کردن زبان جدید
- [یکپارچه‌سازی‌های اختیاری](../../docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
---
## ساخته‌شده روی graphify — Penpax
[**Penpax**](https://graphify.com) لایه همیشه‌روشن ساخته‌شده روی graphify است — همان رویکرد گراف را بر کل زندگی کاری شما اعمال می‌کند: جلسات، تاریخچه مرورگر، ایمیل‌ها، فایل‌ها و کد، به‌صورت مداوم در پس‌زمینه به‌روزرسانی می‌شود.
ساخته‌شده برای کسانی که کارشان در صدها مکالمه و سند پراکنده است. بدون ابر، کاملاً روی دستگاه.
**آزمایش رایگان به‌زودی راه‌اندازی می‌شود.** [به لیست انتظار بپیوندید ←](https://graphify.com)
---
</div>
<details>
<summary>مشارکت در پروژه</summary>
<div dir="rtl">
### راه‌اندازی محیط توسعه
این پروژه از [uv](https://docs.astral.sh/uv/) برای جریان کار توسعه استفاده می‌کند. یک بار آن را نصب کنید، سپس:
</div>
```bash
git clone https://github.com/Graphify-Labs/graphify.git
cd graphify
git checkout v8 # شاخه توسعه فعال
uv sync --all-extras
```
<div dir="rtl">
### اجرای تست‌ها
</div>
```bash
uv run pytest tests/ -q # اجرای کل مجموعه
uv run pytest tests/test_extract.py -q # یک ماژول
```
<div dir="rtl">
### جریان کار Git
- توسعه فعال روی شاخه `v8` انجام می‌شود.
- سبک commit: `fix: <توضیح>` / `feat: <توضیح>` / `docs: <توضیح>`
- قبل از باز کردن PR، `uv run pytest tests/ -q` اجرا کنید و از موفقیت آن مطمئن شوید.
### چه چیزی مشارکت کنیم
**نمونه‌های کاری** مفیدترین نوع مشارکت هستند. `/graphify` را روی یک corpus واقعی اجرا کنید، خروجی را در `worked/{slug}/` ذخیره کنید، یک `review.md` صادقانه بنویسید که چه چیزهایی درست و نادرست بوده، و یک PR باز کنید.
**باگ‌های استخراج** — یک issue با فایل ورودی، آیتم کش (`graphify-out/cache/`) و آنچه اشتباه یا حذف شده باز کنید.
برای مسئولیت‌های ماژول و نحوه اضافه کردن زبان جدید [ARCHITECTURE.md](../../ARCHITECTURE.md) را ببینید.
</div>
</details>
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Virallinen paketti:** PyPI-paketti on nimeltään `graphifyy`. Ainoa virallinen repositorio on [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Virallinen paketti:** PyPI-paketti on nimeltään `graphifyy`. Ainoa virallinen repositorio on [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Käyttö
@@ -74,4 +74,4 @@ Kooditiedostot käsitellään paikallisesti tree-sitter AST:n kautta. Videot lit
[**Penpax**](https://safishamsi.github.io/penpax.ai) on graphifyn päälle rakennettu yritystaso. **Ilmainen kokeilujakso tulossa pian.** [Liity odotuslistalle →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Opisyal na package:** Ang PyPI package ay pinangalanang `graphifyy`. Ang tanging opisyal na repository ay [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Opisyal na package:** Ang PyPI package ay pinangalanang `graphifyy`. Ang tanging opisyal na repository ay [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Paggamit
@@ -72,6 +72,6 @@ Ang mga code file ay prinoseso nang lokal sa pamamagitan ng tree-sitter AST. Ang
## Binuo sa ibabaw ng graphify — Penpax
Ang [**Penpax**](https://graphifylabs.ai) ay ang enterprise layer sa ibabaw ng graphify. **Malapit nang magkaroon ng libreng trial.** [Sumali sa waitlist →](https://graphifylabs.ai)
Ang [**Penpax**](https://graphify.com) ay ang enterprise layer sa ibabaw ng graphify. **Malapit nang magkaroon ng libreng trial.** [Sumali sa waitlist →](https://graphify.com)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**Une compétence pour assistant de code IA.** Tapez `/graphify` dans Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — il lit vos fichiers, construit un graphe de connaissances et vous révèle une structure que vous ne voyiez pas auparavant. Comprenez une base de code plus rapidement. Trouvez le « pourquoi » derrière les décisions architecturales.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Package officiel :** Le package PyPI s'appelle `graphifyy` (installer avec `pip install graphifyy`). Les autres packages nommés `graphify*` sur PyPI ne sont pas affiliés à ce projet. Le seul dépôt officiel est [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Package officiel :** Le package PyPI s'appelle `graphifyy` (installer avec `pip install graphifyy`). Les autres packages nommés `graphify*` sur PyPI ne sont pas affiliés à ce projet. Le seul dépôt officiel est [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
### Support des plateformes
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extraction sémantique v
## Historique des étoiles
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+849
View File
@@ -0,0 +1,849 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇷 <a href="README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a> | 🇮🇱 <a href="README.he-IL.md">עברית</a>
</p>
<p align="center">
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
</p>
<p align="center">
<a href="https://star-history.com/#Graphify-Labs/graphify&Date">
<img src="https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date" alt="Star History Chart" width="370"/>
</a>
</p>
<div dir="rtl">
הקלידו `‎/graphify` בעוזר ה-AI לכתיבת קוד שלכם, והוא ימפה את הפרויקט כולו — קוד, מסמכים, קובצי PDF, תמונות, סרטונים — לגרף ידע שאפשר לשאול עליו שאלות, במקום לחפש בקבצים עם grep.
עובד ב-Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, Devin CLI ו-Google Antigravity.
</div>
```
/graphify .
```
<div dir="rtl">
זה הכול. מקבלים שלושה קבצים:
</div>
```
graphify-out/
├── graph.html נפתח בכל דפדפן — לחיצה על צמתים, סינון, חיפוש
├── GRAPH_REPORT.md עיקרי הדברים: מושגי מפתח, קשרים מפתיעים, שאלות מוצעות
└── graph.json הגרף המלא — אפשר לשאול עליו בכל רגע בלי לקרוא שוב את הקבצים
```
<div dir="rtl">
לדף ארכיטקטורה קריא עם דיאגרמות זרימת-קריאות ב-Mermaid, הריצו:
</div>
```bash
graphify export callflow-html
```
---
<div dir="rtl">
## דרישות מקדימות
| דרישה | מינימום | בדיקה | התקנה |
|---|---|---|---|
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
| uv *(מומלץ)* | כל גרסה | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| pipx *(חלופה)* | כל גרסה | `pipx --version` | `pip install pipx` |
**התקנה מהירה ב-macOS (עם Homebrew):**
</div>
```bash
brew install python@3.12 uv
```
<div dir="rtl">
**התקנה מהירה ב-Windows:**
</div>
```powershell
winget install astral-sh.uv
```
<div dir="rtl">
**Ubuntu/Debian:**
</div>
```bash
sudo apt install python3.12 python3-pip pipx
# או התקנת uv:
curl -LsSf https://astral.sh/uv/install.sh | sh
```
---
<div dir="rtl">
## התקנה
> **החבילה הרשמית:** חבילת ה-PyPI היא `graphifyy` (עם y כפולה). חבילות `graphify*` אחרות ב-PyPI אינן קשורות לפרויקט. פקודת ה-CLI היא עדיין `graphify`.
**שלב 1 — התקנת החבילה:**
</div>
```bash
# מומלץ (סביבה מבודדת; אם הפקודה 'graphify' לא נמצאת אחר כך, הריצו: uv tool update-shell):
uv tool install graphifyy
# חלופות:
pipx install graphifyy
pip install graphifyy # עשוי לדרוש הגדרת PATH — ראו הערה בהמשך
```
<div dir="rtl">
**שלב 2 — רישום המיומנות (skill) אצל עוזר ה-AI שלכם:**
</div>
```bash
graphify install
```
<div dir="rtl">
זהו. פתחו את עוזר ה-AI והקלידו `‎/graphify .`
כדי להתקין את המיומנות בתוך המאגר הנוכחי במקום בפרופיל המשתמש, הוסיפו `--project`:
</div>
```bash
graphify install --project
graphify install --project --platform codex
```
<div dir="rtl">
התקנה ברמת הפרויקט כותבת לתוך התיקייה הנוכחית, למשל `.claude/skills/graphify/SKILL.md` או `.agents/skills/graphify/SKILL.md` (בתוספת תיקיית `references/` שהמיומנות טוענת לפי הצורך), ומדפיסה רמז `git add` לקבצים שאפשר לבצע להם commit. פקודות פר-פלטפורמה שתומכות בהתקנה ברמת הפרויקט מקבלות את אותו דגל, למשל `graphify claude install --project` או `graphify codex install --project`.
> **הערת PowerShell:** השתמשו ב-`graphify .` ולא ב-`‎/graphify .` — הלוכסן המוביל הוא מפריד נתיבים ב-PowerShell.
> **‏`graphify: command not found`?** ‏`uv tool install` / `pipx install` מציבים את פקודת `graphify` בתיקיית הכלים שלהם (`~/.local/bin`). אם המעטפת (shell) לא מוצאת אותה מיד אחרי ההתקנה — נפוץ בהתקנת macOS + zsh טרייה — התיקייה הזו עדיין לא ב-`PATH`: הריצו `uv tool update-shell` (או `pipx ensurepath`) ופתחו טרמינל חדש. עם `pip` רגיל, הוסיפו את `~/.local/bin` (בלינוקס) או `~/Library/Python/3.x/bin` (במק) ל-PATH, או הריצו `python -m graphify`.
> **מריצים עם `uvx` / `uv tool run` בלי להתקין?** ציינו את שם החבילה, לא את שם הפקודה: `uvx --from graphifyy graphify install`. ‏`uvx graphify …` רגיל נכשל (`No solution found … no versions of graphify`) כי `uv tool run` קורא את המילה הראשונה כשם *חבילה*, והחבילה היא `graphifyy` — פקודת `graphify` נמצאת בתוכה.
> **הימנעו מ-`pip install` במק/Windows** אם אפשר. המיומנות מאתרת את Python בזמן ריצה מתוך `graphify-out/.graphify_python`; אם הוא מצביע על סביבה שונה מזו שבה `pip` התקין את החבילה, תקבלו `ModuleNotFoundError: No module named 'graphify'`. ‏`uv tool install` ו-`pipx install` מבודדים את החבילה בסביבה משלהם ונמנעים מהבעיה לחלוטין.
> **הוקים של Git עם uv tool / pipx:** ‏`graphify hook install` מטמיע את נתיב המפרש הנוכחי ישירות בסקריפטי ההוק בזמן ההתקנה, כך שהוק ה-post-commit יופעל כראוי גם בלקוחות Git גרפיים וב-CI שבהם `~/.local/bin` אינו ב-PATH. אם התקנתם מחדש או שדרגתם את graphify, הריצו שוב `graphify hook install` כדי לרענן את הנתיב המוטמע.
### בחרו את הפלטפורמה שלכם
| פלטפורמה | פקודת התקנה |
|----------|----------------|
| Claude Code (לינוקס/מק) | `graphify install` |
| Claude Code (Windows) | `graphify install` (זיהוי אוטומטי) או `graphify install --platform windows` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| Kilo Code | `graphify install --platform kilo` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Agent Skills (חוצה-פלטפורמות) | `graphify install --platform agents` (כינוי: `--platform skills`) |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify install --platform pi` |
| Cursor | `graphify cursor install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
משתמשי Codex צריכים גם `multi_agent = true` תחת `[features]` בקובץ `~/.codex/config.toml` לצורך חילוץ מקבילי. CodeBuddy משתמש באותו מנגנון Agent tool והוק PreToolUse כמו Claude Code. ‏Factory Droid משתמש בכלי `Task` לשיגור תת-סוכנים במקביל. OpenClaw ו-Aider משתמשים בחילוץ טורי (תמיכה בסוכנים מקביליים עדיין מוקדמת בפלטפורמות אלו). Trae משתמש ב-Agent tool לשיגור תת-סוכנים במקביל ו**אינו** תומך בהוקים מסוג PreToolUse — ‏AGENTS.md הוא המנגנון הקבוע שם.
`--platform agents` (כינוי: `--platform skills`) מכוון למיקומים הגנריים חוצי-הפלטפורמות של [Agent-Skills](https://github.com/anthropics/skills): ‏`~/.agents/skills/` הגלובלי של המשתמש (נקרא על ידי `npx skills` ומסגרות תואמות-מפרט) בהתקנה גלובלית, ו-`./.agents/skills/` בהתקנת פרויקט (`--project`). ‏`graphify install` החשוף נשאר חד-פלטפורמי (Claude Code) בכוונה — השתמשו בפלטפורמת `agents` כשתרצו שהמיומנות תהיה זמינה לכל מסגרת שקוראת `.agents/skills`.
> Codex משתמש ב-`‎$graphify` במקום `‎/graphify`.
### תוספים אופציונליים
התקינו רק מה שצריך:
| תוסף | מה הוא מוסיף | התקנה |
|---|---|---|
| `pdf` | חילוץ PDF | `uv tool install "graphifyy[pdf]"` |
| `office` | תמיכה ב-`.docx` ו-`.xlsx` | `uv tool install "graphifyy[office]"` |
| `google` | רינדור Google Sheets | `uv tool install "graphifyy[google]"` |
| `video` | תמלול וידאו/אודיו (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` |
| `mcp` | שרת MCP stdio | `uv tool install "graphifyy[mcp]"` |
| `neo4j` | דחיפה ל-Neo4j | `uv tool install "graphifyy[neo4j]"` |
| `falkordb` | דחיפה ל-FalkorDB | `uv tool install "graphifyy[falkordb]"` |
| `svg` | ייצוא גרף ל-SVG | `uv tool install "graphifyy[svg]"` |
| `leiden` | זיהוי קהילות Leiden ‏(graspologic ב-Python < 3.13; מנגנון native ב-3.13+) | `uv tool install "graphifyy[leiden]"` |
| `ollama` | הרצה מקומית עם Ollama | `uv tool install "graphifyy[ollama]"` |
| `openai` | OpenAI / ממשקי API תואמי-OpenAI | `uv tool install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
| `anthropic` | Anthropic Claude API ‏(`--backend claude`, משתמש ב-`ANTHROPIC_API_KEY`) | `uv tool install "graphifyy[anthropic]"` |
| `bedrock` | AWS Bedrock (משתמש ב-IAM, ללא מפתח API) | `uv tool install "graphifyy[bedrock]"` |
| `azure` | Azure OpenAI Service ‏(`--backend azure`, משתמש ב-`AZURE_OPENAI_API_KEY` + ‏`AZURE_OPENAI_ENDPOINT`) | `uv tool install "graphifyy[openai]"` |
| `sql` | חילוץ סכמות SQL | `uv tool install "graphifyy[sql]"` |
| `postgres` | אינטרוספקציה של PostgreSQL חי (`--postgres DSN`) | `uv tool install "graphifyy[postgres]"` |
| `dm` | חילוץ AST של BYOND DreamMaker ‏`.dm`/`.dme` (עשוי לדרוש קומפיילר C + ‏`python3-dev` אם אין wheel מתאים לפלטפורמה) | `uv tool install "graphifyy[dm]"` |
| `terraform` | חילוץ AST של Terraform / HCL ‏`.tf`/`.tfvars`/`.hcl` | `uv tool install "graphifyy[terraform]"` |
| `chinese` | פילוח שאילתות בסינית (jieba) | `uv tool install "graphifyy[chinese]"` |
| `all` | כל מה שלמעלה | `uv tool install "graphifyy[all]"` |
---
## גרמו לעוזר שלכם להשתמש בגרף תמיד
הריצו פעם אחת בפרויקט אחרי בניית גרף:
| פלטפורמה | פקודה |
|----------|---------|
| Claude Code | `graphify claude install` |
| CodeBuddy | `graphify codebuddy install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| Kilo Code | `graphify kilo install` |
| GitHub Copilot CLI | `graphify copilot install` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify aider install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Trae CN | `graphify trae-cn install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Hermes | `graphify hermes install` |
| Kimi Code | `graphify install --platform kimi` |
| Amp | `graphify amp install` |
| Agent Skills (חוצה-פלטפורמות) | `graphify agents install` (כינוי: `graphify skills install`) |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify pi install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
הפקודה כותבת קובץ תצורה קטן שמנחה את העוזר שלכם להתייעץ עם גרף הידע בשאלות על בסיס הקוד — ולהעדיף שאילתות ממוקדות כמו `graphify query "<שאלה>"` על פני קריאת הדוח המלא או grep על קבצים גולמיים. בפלטפורמות שתומכות בהוקים נושאי-מטען (Claude Code, ‏Gemini CLI), הוק מופעל אוטומטית לפני קריאות כלי בסגנון חיפוש (וב-Claude Code גם לפני קריאת קובצי מקור אחד-אחד דרך הכלים Read/Glob) ומכוון את העוזר לנתיב הגרף. באחרות (Codex, ‏OpenCode, ‏Cursor וכו'), קובצי ההנחיות הקבועים (`AGENTS.md`, ‏`.cursor/rules/` וכו') מספקים את אותה הנחיית "קודם הגרף". ‏`GRAPH_REPORT.md` עדיין זמין לסקירת ארכיטקטורה רחבה.
**CodeBuddy** עושה את אותם שני דברים כמו Claude Code: כותב קטע `CODEBUDDY.md` שמנחה את CodeBuddy לקרוא את `graphify-out/GRAPH_REPORT.md` לפני מענה על שאלות ארכיטקטורה, ומתקין **הוקים מסוג PreToolUse** ‏(`.codebuddy/settings.json`) שמופעלים לפני פקודות חיפוש ב-Bash וקריאת קבצים, ומכוונים ל-`graphify query` במקום.
**Codex** כותב ל-`AGENTS.md` וגם מתקין **הוק PreToolUse** ב-`.codex/hooks.json` שמופעל לפני כל קריאת כלי Bash — אותו מנגנון קבוע כמו ב-Claude Code.
להסרת graphify מכל הפלטפורמות בבת אחת: `graphify uninstall` (הוסיפו `--purge` כדי למחוק גם את `graphify-out/`). או השתמשו בפקודה הפר-פלטפורמית (למשל `graphify claude uninstall`).
---
**Kilo Code** מתקין את מיומנות Graphify ל-`~/.config/kilo/skills/graphify/SKILL.md` ופקודת `‎/graphify` נטיבית ל-`~/.config/kilo/command/graphify.md`. ‏`graphify kilo install` כותב גם `AGENTS.md` וגם **תוסף `tool.execute.before` נטיבי** (`.kilo/plugins/graphify.js` + רישום ב-`.kilo/kilo.json` או `.kilo/kilo.jsonc`) כך ש-Kilo מקבל את אותה התנהגות תזכורת-גרף קבועה דרך תצורת `.kilo` נטיבית.
**Cursor** כותב `.cursor/rules/graphify.mdc` עם `alwaysApply: true` — ‏Cursor מכליל אותו בכל שיחה אוטומטית, ללא צורך בהוק.
## מה יש בדוח
- **צומתי מפתח (God nodes)** — המושגים המקושרים ביותר בפרויקט. הכול עובר דרכם.
- **קשרים מפתיעים** — קישורים בין דברים שחיים בקבצים או מודולים שונים. מדורגים לפי מידת ההפתעה.
- **ה"למה"** — הערות בקוד (`# NOTE:`‏, `# WHY:`‏, `# HACK:`), ‏docstrings ורציונל עיצובי מהמסמכים מחולצים כצמתים נפרדים המקושרים לקוד שהם מסבירים.
- **שאלות מוצעות** — 4–5 שאלות שהגרף נמצא בעמדה ייחודית לענות עליהן.
- **תגי ביטחון** — כל קשר מוסק מסומן `EXTRACTED`‏, `INFERRED` או `AMBIGUOUS`. תמיד יודעים מה נמצא ומה נוחש.
---
## אילו קבצים הוא מטפל
| סוג | סיומות |
|------|-----------|
| קוד (36 דקדוקי tree-sitter) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .cu .cuh .metal .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .psm1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .slnx .csproj .fsproj .vbproj .xaml .razor .cshtml` ‏(`.dm`/`.dme` דורש `uv tool install graphifyy[dm]`; ‏CUDA ‏`.cu`/`.cuh` ו-Metal ‏`.metal` משתמשים בדקדוק C++) |
| Salesforce Apex | `.cls .trigger` (מבוסס regex; מחלקות, ממשקים, enums, מתודות, טריגרים, קשתות SOQL/DML) |
| Terraform / HCL | `.tf .tfvars .hcl` (דורש `uv tool install graphifyy[terraform]`) |
| תצורות MCP | `.mcp.json` ‏`mcp.json` ‏`mcp_servers.json` ‏`claude_desktop_config.json` — מחלץ צומתי שרתים, הפניות לחבילות, דרישות משתני סביבה |
| מניפסטים של חבילות | `apm.yml` ‏`pyproject.toml` ‏`go.mod` ‏`pom.xml` — צומת חבילה קנוני אחד לכל חבילה (לפי שם) בתוספת קשתות `depends_on`, כך שחבילה שמופנית מכמה מניפסטים היא מוקד (hub) יחיד |
| מסמכים | `.md .mdx .qmd .html .txt .rst .yaml .yml` (קישורי markdown ‏`[text](./other.md)` ו-`[[wikilinks]]` הופכים לקשתות `references` בין מסמכים) |
| Office | `.docx .xlsx` (דורש `uv tool install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` ‏(opt-in; דורש אימות `gws` ו-`--google-workspace`; ‏Sheets דורש `uv tool install graphifyy[google]`) |
| PDF | `.pdf` |
| תמונות | `.png .jpg .webp .gif` |
| וידאו / אודיו | `.mp4 .mov .mp3 .wav` ועוד (דורש `uv tool install graphifyy[video]`) |
| YouTube / כתובות URL | כל כתובת וידאו (דורש `uv tool install graphifyy[video]`) |
קוד מחולץ מקומית ללא קריאות API ‏(AST באמצעות tree-sitter). כל השאר עובר דרך ה-API של מודל עוזר ה-AI שלכם.
קובצי `.gdoc`‏, `.gsheet` ו-`.gslides` של Google Drive לשולחן העבודה הם קיצורי דרך, לא תוכן מסמכים. כדי לכלול מסמכי Google Docs, ‏Sheets ו-Slides נטיביים בחילוץ headless, התקינו ואמתו את [`gws` CLI](https://github.com/googleworkspace/cli), ואז הריצו:
</div>
```bash
uv tool install "graphifyy[google]" # נדרש לרינדור טבלאות Google Sheets
gws auth login -s drive
graphify extract ./docs --google-workspace
```
<div dir="rtl">
אפשר גם להגדיר `GRAPHIFY_GOOGLE_WORKSPACE=1`. ‏graphify מייצא קיצורי דרך אל `graphify-out/converted/` כקובצי Markdown נלווים, ואז מחלץ אותם.
---
## פקודות נפוצות
</div>
```bash
/graphify . # בניית גרף לתיקייה הנוכחית
/graphify ./docs --update # חילוץ מחדש של קבצים שהשתנו בלבד
/graphify . --cluster-only # הרצת אשכול מחדש בלי לחלץ מחדש
/graphify . --cluster-only --resolution 1.5 # קהילות מפורטות יותר
/graphify . --cluster-only --exclude-hubs 99 # הסתרת מוקדי-עזר מדירוג צומתי המפתח
/graphify . --no-viz # דילוג על ה-HTML, רק הדוח וה-JSON
/graphify . --wiki # בניית ויקי markdown מהגרף
graphify export callflow-html # ‏HTML ארכיטקטורה/זרימת-קריאות ב-Mermaid (מתחדש אוטומטית בכל commit אם ההוק מותקן)
/graphify query "מה מחבר את האימות למסד הנתונים?"
/graphify path "UserService" "DatabasePool"
/graphify explain "RateLimiter"
/graphify add https://arxiv.org/abs/1706.03762 # הבאת מאמר והוספתו
/graphify add <youtube-url> # תמלול והוספת סרטון
graphify hook install # בנייה מחדש אוטומטית בכל commit
graphify merge-graphs a.json b.json # מיזוג שני גרפים
graphify prs # לוח PR: מצב CI, סטטוס ביקורת, מיפוי worktree
graphify prs 42 # צלילה עמוקה ל-PR ‏#42 עם השפעת גרף
graphify prs --triage # ‏AI מדרג את תור הביקורות שלכם (משתמש ב-backend המוגדר)
graphify prs --conflicts # ‏PRs שחולקים קהילות גרף — סיכון בסדר המיזוג
```
<div dir="rtl">
ראו את [רשימת הפקודות המלאה](#רשימת-הפקודות-המלאה) בהמשך.
---
## התעלמות מקבצים
צרו קובץ `.graphifyignore` בשורש הפרויקט — אותו תחביר כמו `.gitignore`, כולל שלילה עם `!`.
**‏`.gitignore` נאכף אוטומטית.** ‏graphify קורא את ה-`.gitignore` בכל תיקייה. אם קיים גם `.graphifyignore`, השניים **ממוזגים** — תבניות `.graphifyignore` מוערכות אחרונות, כך שהן גוברות במקרה של התנגשות (כולל שלילות `!`). הוספת `.graphifyignore` רק מחריגה עוד; היא לעולם לא תחזיר קובץ שה-`.gitignore` כבר החריג. תחולת תת-תיקיות עובדת כמו ב-git — קובץ ignore משפיע רק על תת-העץ שלו.
</div>
```
# .graphifyignore
node_modules/
dist/
*.generated.py
# לאנדקס רק את src/, להתעלם מכל השאר
*
!src/
!src/**
```
<div dir="rtl">
---
## עבודת צוות
‏`graphify-out/` מיועד להיכנס ל-git כדי שכל חברי הצוות יתחילו עם מפה מוכנה.
**תוספות מומלצות ל-`.gitignore`:**
</div>
```
graphify-out/cost.json # מקומי בלבד
# graphify-out/cache/ # אופציונלי: commit למהירות, דילוג לשמירה על ריפו קטן
```
<div dir="rtl">
> ‏`manifest.json` הוא כעת נייד — המפתחות נשמרים כנתיבים יחסיים ומעוגנים מחדש בטעינה, כך שבטוח לבצע לו commit והדבר חוסך בנייה מלאה מחדש ב-checkout הראשון.
**תהליך העבודה:**
1. אחד מחברי הצוות מריץ `‎/graphify .` ומבצע commit ל-`graphify-out/`.
2. כולם מושכים — העוזר שלהם קורא את הגרף מיד.
3. הריצו `graphify hook install` לבנייה אוטומטית מחדש אחרי כל commit ‏(AST בלבד, ללא עלות API). זה גם מגדיר merge driver של git כך ש-`graph.json` לעולם לא יישאר עם סימוני קונפליקט — שני מפתחים שמבצעים commit במקביל מקבלים מיזוג-איחוד אוטומטי של הגרפים.
4. כשמסמכים או מאמרים משתנים, הריצו `‎/graphify --update` לרענון הצמתים הללו.
---
## שימוש ישיר בגרף
</div>
```bash
# שאילתת גרף מהטרמינל
graphify query "הצג את זרימת האימות"
graphify query "מה מחבר בין DigestAuth ל-Response?" --graph graphify-out/graph.json
# חשיפת הגרף כשרת MCP (לגישת כלים חוזרת)
python -m graphify.serve graphify-out/graph.json
python -m graphify.serve --graph graphify-out/graph.json # גם הדגל --graph מתקבל
# רישום ב-Kimi Code:
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
# או הגשה על HTTP כך שכל הצוות מצביע על URL אחד (בלי graphify מקומי):
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
```
<div dir="rtl">
שרת ה-MCP נותן לעוזר שלכם גישה מובנית: `query_graph`‏, `get_node`‏, `get_neighbors`‏, `shortest_path`‏, `list_prs`‏, `get_pr_impact`‏, `triage_prs`.
### שרת HTTP משותף
`--transport stdio` (ברירת המחדל) מריץ שרת מקומי אחד לכל מפתח. `--transport http` מגיש את אותם כלים על גבי MCP Streamable HTTP, כך שתהליך משותף אחד יכול לשרת את הגרף לכל הצוות — הלקוחות מכוונים את תצורת ה-MCP של ה-IDE אל `http://<host>:8080/mcp` במקום להריץ graphify מקומית.
| דגל | ברירת מחדל | תפקיד |
|---|---|---|
| `--transport {stdio,http}` | `stdio` | סוג התעבורה |
| `--host` | `127.0.0.1` | כתובת ההאזנה ל-HTTP (השתמשו ב-`0.0.0.0` לחשיפה מעבר ל-localhost) |
| `--port` | `8080` | פורט ההאזנה |
| `--api-key` | משתנה סביבה `GRAPHIFY_API_KEY` | דרישת `Authorization: Bearer <key>` (או `X-API-Key`) |
| `--path` | `/mcp` | נתיב העיגון ב-HTTP |
| `--json-response` | כבוי | החזרת JSON רגיל במקום זרמי SSE |
| `--stateless` | כבוי | ללא מצב פר-סשן (לפריסות מאוזנות-עומס / CI) |
| `--session-timeout` | `3600` | ניקוי סשנים לא פעילים אחרי N שניות (`0` מבטל) |
ברירת המחדל `127.0.0.1` היא loopback בלבד. הגדירו `--host 0.0.0.0` **וגם** `--api-key` יחד כשחושפים על מארח משותף. אפשר להריץ בקונטיינר:
</div>
```bash
docker build -t graphify .
docker run -p 8080:8080 -v "$(pwd)/graphify-out:/data" graphify \
/data/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
```
<div dir="rtl">
> **הערת WSL / לינוקס:** אובונטו מגיעה עם `python3`, לא `python`. השתמשו ב-venv כדי להימנע מהתנגשויות:
</div>
```bash
python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
```
<div dir="rtl">
---
## משתני סביבה
אלו נדרשים רק ל**חילוץ headless / CI** ‏(`graphify extract`). בהרצה דרך מיומנות `‎/graphify` בתוך ה-IDE, ה-API של המודל מסופק על ידי סשן ה-IDE — לא נדרשים מפתחות נוספים.
| משתנה | משמש עבור | מתי נדרש |
|---|---|---|
| `ANTHROPIC_API_KEY` | ‏backend של Claude ‏(Anthropic) | `--backend claude` |
| `ANTHROPIC_BASE_URL` | כתובת endpoint תואם-Anthropic ‏(פרוקסי LiteLLM, שערים, ...) | `--backend claude` (ברירת מחדל: `https://api.anthropic.com`) |
| `ANTHROPIC_MODEL` | שם המודל ל-backend של Claude — ל-endpoints מותאמים, השתמשו בשם/כינוי שהשרת שלכם חושף | `--backend claude` (ברירת מחדל: `claude-sonnet-4-6`) |
| `GEMINI_API_KEY` או `GOOGLE_API_KEY` | ‏backend של Google Gemini | `--backend gemini` |
| `OPENAI_API_KEY` | ‏OpenAI או ממשקים תואמי-OpenAI | `--backend openai` (שרתים מקומיים מקבלים כל ערך לא ריק) |
| `OPENAI_BASE_URL` | כתובת שרת תואם-OpenAI ‏(llama.cpp, ‏vLLM, ‏LM Studio, ...) | `--backend openai` (ברירת מחדל: `https://api.openai.com/v1`) |
| `OPENAI_MODEL` | שם המודל ל-backend של OpenAI — לשרתים בהרצה עצמית, השתמשו בשם/כינוי שהשרת חושף (בדקו את endpoint ה-`/v1/models` שלו) | `--backend openai` (ברירת מחדל: `gpt-4.1-mini`) |
| `DEEPSEEK_API_KEY` | ‏backend של DeepSeek | `--backend deepseek` |
| `MOONSHOT_API_KEY` | ‏backend של Kimi Code | `--backend kimi` |
| `OLLAMA_BASE_URL` | כתובת הרצה מקומית של Ollama | `--backend ollama` (ברירת מחדל: `http://localhost:11434`) |
| `OLLAMA_MODEL` | שם מודל Ollama | `--backend ollama` (ברירת מחדל: זיהוי אוטומטי) |
| `GRAPHIFY_OLLAMA_NUM_CTX` | דריסת גודל חלון ה-KV-cache של Ollama | אופציונלי — מותאם אוטומטית כברירת מחדל |
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | דקות להשארת מודל Ollama טעון | אופציונלי — ‏`0` לפריקה אחרי כל chunk |
| `AZURE_OPENAI_API_KEY` | ‏backend של Azure OpenAI Service | `--backend azure` |
| `AZURE_OPENAI_ENDPOINT` | כתובת ה-endpoint של משאב Azure | `--backend azure` (נדרש יחד עם מפתח ה-API) |
| `AZURE_OPENAI_API_VERSION` | דריסת גרסת ה-API של Azure | אופציונלי — ברירת מחדל `2024-12-01-preview` |
| `AZURE_OPENAI_DEPLOYMENT` או `GRAPHIFY_AZURE_MODEL` | שם הפריסה ב-Azure | אופציונלי — ברירת מחדל `gpt-4o` |
| `AWS_*` / `~/.aws/credentials` | ‏AWS Bedrock — שרשרת אישורים סטנדרטית | `--backend bedrock` (ללא מפתח API, משתמש ב-IAM) |
| `GRAPHIFY_MAX_WORKERS` | מספר threads למקביליות AST | אופציונלי — גם דגל `--max-workers` |
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | העלאת תקרת הפלט לקורפוסים צפופים | אופציונלי — למשל `32768` לקבצים גדולים |
| `GRAPHIFY_API_TIMEOUT` | ‏timeout לקריאה בשניות עבור HTTP, ‏claude-cli ו-Anthropic SDK ‏(ברירת מחדל: 600) | אופציונלי — גם דגל `--api-timeout` |
| `GRAPHIFY_MAX_RETRIES` | מספר ניסיונות חוזרים לבקשה שנחסמה בקצב (429) לפני ויתור (ברירת מחדל: 6; מכבד `Retry-After`) | אופציונלי — העלו למגבלות ארגוניות נוקשות; ‏`0` מבטל |
| `GRAPHIFY_FORCE` | כפיית בנייה מחדש של הגרף גם עם פחות צמתים | אופציונלי — גם דגל `--force` |
| `GRAPHIFY_GOOGLE_WORKSPACE` | הפעלה אוטומטית של ייצוא Google Workspace | אופציונלי — הגדירו `1` |
| `GRAPHIFY_TRIAGE_BACKEND` | ‏backend עבור `graphify prs --triage` | אופציונלי — מזוהה אוטומטית מהמפתחות הזמינים |
| `GRAPHIFY_TRIAGE_MODEL` | דריסת מודל לטריאז' | אופציונלי — למשל `claude-opus-4-7` |
| `GRAPHIFY_QUERY_LOG` | דריסת נתיב יומן השאילתות (ברירת מחדל: `~/.cache/graphify-queries.log`) | אופציונלי — ערך ריק או `/dev/null` להשתקה |
| `GRAPHIFY_QUERY_LOG_DISABLE` | הגדירו `1` לביטול מוחלט של יומן השאילתות | אופציונלי |
| `GRAPHIFY_QUERY_LOG_RESPONSES` | הגדירו `1` לרישום גם של תשובות תת-גרף מלאות (כבוי כברירת מחדל) | אופציונלי |
| `GRAPHIFY_MAX_GRAPH_BYTES` | דריסת תקרת הגודל של graph.json ‏(512 MiB) — למשל `700MB`, ‏`2GB` או בייטים | אופציונלי — שימושי לקורפוסים גדולים מאוד |
| `GRAPHIFY_LLM_TEMPERATURE` | דריסת טמפרטורת ה-LLM לחילוץ סמנטי — למשל `0.7`, או `none` להשמטה | אופציונלי — מושמט אוטומטית למודלי היסק o1/o3/o4/gpt-5 |
---
## פרטיות
- **קובצי קוד** — מעובדים מקומית עם tree-sitter. שום דבר לא עוזב את המחשב. קורפוס של קוד בלבד אינו דורש מפתח API — ‏`graphify extract` רץ לגמרי offline.
- **וידאו / אודיו** — מתומלל מקומית עם faster-whisper. שום דבר לא עוזב את המחשב.
- **מסמכים, PDF, תמונות** — נשלחים לעוזר ה-AI שלכם לחילוץ סמנטי (דרך מיומנות `‎/graphify`, עם המודל שסשן ה-IDE שלכם מריץ). ‏`graphify extract` בחילוץ headless דורש `GEMINI_API_KEY` / ‏`GOOGLE_API_KEY` ‏(Gemini), ‏`MOONSHOT_API_KEY` ‏(Kimi), ‏`ANTHROPIC_API_KEY` ‏(Claude), ‏`OPENAI_API_KEY` ‏(OpenAI), ‏`DEEPSEEK_API_KEY` ‏(DeepSeek), מופע Ollama רץ (`OLLAMA_BASE_URL`), אישורי AWS דרך שרשרת הספקים הסטנדרטית (Bedrock — ללא מפתח API, משתמש ב-IAM), או קובץ ההרצה `claude` ‏(Claude Code — ללא מפתח API, משתמש במנוי Claude שלכם). הדגל `--dedup-llm` משתמש באותו מפתח.
- **מיקום נתונים (Data residency)** — ‏`graphify extract` מזהה אוטומטית באיזה ספק להשתמש לפי המפתח שמוגדר (עדיפות: Gemini ‏→ Kimi ‏→ Claude ‏→ OpenAI ‏→ DeepSeek ‏→ Azure ‏→ Bedrock ‏→ Ollama). לקוד עם דרישות מיקום נתונים, השתמשו ב-`--backend ollama` (מקומי לחלוטין) או העבירו דגל `--backend` מפורש. ‏Kimi ‏(`MOONSHOT_API_KEY`) מנתב לשרתי Moonshot AI בסין.
- ללא טלמטריה, ללא מעקב שימוש, ללא אנליטיקה.
- **יומן שאילתות** — כל קריאת `graphify query`‏, `graphify path`‏, `graphify explain` ו-`query_graph` של MCP נרשמת ל-`~/.cache/graphify-queries.log` בפורמט JSON Lines ‏(חותמת זמן, שאלה, קורפוס, צמתים שהוחזרו, משך). תשובות תת-גרף מלאות **אינן** נשמרות כברירת מחדל. הגדירו `GRAPHIFY_QUERY_LOG_DISABLE=1` לביטול, או `GRAPHIFY_QUERY_LOG=/dev/null` להשתקה בלי לבטל את המנגנון.
---
## פתרון בעיות
**‏`graphify: command not found` אחרי ההתקנה**
ה-CLI מותקן אבל תיקיית ה-bin שלו אינה ב-`PATH` של המעטפת. בחרו את התיקון לפי אופן ההתקנה:
- **uv** ‏(`uv tool install graphifyy`): הפקודה מגיעה לתיקיית הכלים של uv ‏(`~/.local/bin`), שהתקנת macOS/zsh טרייה לרוב לא כוללת ב-`PATH`. הריצו `uv tool update-shell` ופתחו טרמינל חדש. (מצאו את התיקייה עם `uv tool dir --bin`.)
- **pipx** ‏(`pipx install graphifyy`): הריצו `pipx ensurepath` ופתחו טרמינל חדש.
- **pip** ‏(`pip install graphifyy`): ‏pip מתקין סקריפטים לתיקיית bin של המשתמש שאולי אינה ב-`PATH` — הוסיפו את `~/Library/Python/3.x/bin` ‏(macOS) או `~/.local/bin` ‏(לינוקס) ל-`PATH` ב-`~/.zshrc`/`~/.bashrc`, או פשוט הריצו `python -m graphify`.
**‏`uvx graphify …` או `uv tool run graphify …` לא מצליחים לפתור את `graphify`**
חבילת ה-PyPI היא `graphifyy`; ‏`graphify` הוא רק הפקודה שהיא מספקת. ‏`uv tool run` מתייחס למילה הראשונה כשם *חבילה*, מחפש חבילה בשם `graphify` ומדווח `No solution found … no versions of graphify`. ציינו את החבילה במפורש: `uvx --from graphifyy graphify install` (זהה ל-`uv tool run --from graphifyy graphify install`). או התקינו פעם אחת עם `uv tool install graphifyy` וקראו ל-`graphify` ישירות.
**‏`python -m graphify` עובד אבל פקודת `graphify` לא**
ה-`PATH` של המעטפת לא כולל את תיקיית ה-bin שאליה הותקנה הפקודה. העדיפו `uv tool install` / ‏`pipx install` על פני `pip` רגיל, ואז הריצו `uv tool update-shell` / ‏`pipx ensurepath` ופתחו טרמינל חדש (ראו הערות ההתקנה לעיל).
**‏`‎/graphify .` גורם ל-"path not recognized" ב-PowerShell**
‏PowerShell מתייחס ל-`/` מוביל כמפריד נתיבים. השתמשו ב-`graphify .` (בלי לוכסן) ב-Windows.
**לגרף יש פחות צמתים אחרי `--update` או בנייה מחדש**
אם refactor מחק קבצים, הצמתים הישנים נשארים. העבירו `--force` (או הגדירו `GRAPHIFY_FORCE=1`) לדריסה גם כשהבנייה החדשה קטנה יותר.
**לגרף יש צמתים כפולים לאותה ישות (ghost duplicates)**
כפילויות רפאים (אותו סימבול מופיע פעמיים — פעם מחילוץ AST עם מיקום מקור, ופעם מחילוץ סמנטי בלעדיו) ממוזגות כעת אוטומטית בזמן הבנייה. אם אתם רואים זאת בגרף שנבנה לפני v0.8.33, הריצו חילוץ מלא מחדש לניקוי:
</div>
```bash
graphify extract . --force
```
<div dir="rtl">
**‏Ollama נגמר לו ה-VRAM / חריגה מחלון ההקשר**
חלון ה-KV-cache מותאם אוטומטית אך עשוי להיות גדול מדי ל-GPU שלכם. הקטינו אותו:
</div>
```bash
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
```
<div dir="rtl">
**אזהרות `LLM returned invalid JSON` / ‏`Unterminated string`**
תשובת ה-JSON של המודל פגעה במגבלת אסימוני הפלט ונחתכה באמצע מחרוזת. ‏graphify מתאושש אוטומטית (הוא מפצל את ה-chunk ומחלץ מחדש את החצאים, ומסמך יחיד גדול מדי נחתך תחילה בגבולות כותרות/פסקאות כך שהקובץ כולו עדיין מכוסה), כך שהאזהרות רועשות אך אין אובדן נתונים. להפחתת התופעה, העלו את תקרת הפלט או הקטינו את פלט ה-chunk:
</div>
```bash
GRAPHIFY_MAX_OUTPUT_TOKENS=16384 graphify extract . --mode deep # הרמת התקרה
graphify extract . --mode deep --token-budget 4000 # קלטים קטנים יותר -> פלט קטן יותר
```
<div dir="rtl">
עם שער ענן כמו OpenRouter, העדיפו `--backend openai` (הגדירו `OPENAI_BASE_URL`) על פני שכבת ה-Ollama — זה נתיב תואם-OpenAI נקי יותר. אם למודל יש תקרת פלט משלו, הורדת `--token-budget` היא המנוף האמין.
**‏HTML של הגרף גדול מדי לפתיחה בדפדפן (מעל 5000 צמתים)**
דלגו על יצירת ה-HTML והשתמשו ב-JSON ישירות:
</div>
```bash
graphify cluster-only ./my-project --no-viz
graphify query "..."
```
<div dir="rtl">
**ל-`graph.json` יש סימוני קונפליקט אחרי ששני מפתחים ביצעו commit במקביל**
הריצו `graphify hook install` — הוא מגדיר merge driver של git שממזג-מאחד את `graph.json` אוטומטית כך שקונפליקטים לא קורים בכלל.
**החילוץ מחזיר צמתים/קשתות ריקים למסמכים או PDF**
מסמכים, PDF ותמונות דורשים קריאת LLM — קורפוסים של קוד בלבד אינם דורשים מפתח. ודאו שמפתח ה-API מוגדר וה-backend נכון:
</div>
```bash
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
<div dir="rtl">
**אזהרת חוסר התאמה בגרסת המיומנות ב-IDE**
גרסת graphify המותקנת שונה מקובץ המיומנות. עדכנו:
</div>
```bash
uv tool upgrade graphifyy
graphify install # דורס את קובץ המיומנות
```
<div dir="rtl">
---
## רשימת הפקודות המלאה
</div>
```
/graphify # הרצה על התיקייה הנוכחית
/graphify ./raw # הרצה על תיקייה מסוימת
/graphify ./raw --mode deep # חילוץ קשרים אגרסיבי יותר
/graphify ./raw --update # חילוץ מחדש של קבצים שהשתנו בלבד
/graphify ./raw --directed # שמירת כיוון הקשתות
/graphify ./raw --cluster-only # הרצת אשכול מחדש על גרף קיים
/graphify ./raw --no-viz # דילוג על ויזואליזציית HTML
/graphify ./raw --obsidian # יצירת כספת Obsidian
/graphify ./raw --obsidian --obsidian-dir ~/vault # כתיבה לכספת קיימת (לעולם לא דורס פתקים או תצורת .obsidian שלכם)
/graphify ./raw --wiki # בניית ויקי markdown שסוכנים יכולים לסרוק
/graphify ./raw --svg # ייצוא graph.svg
/graphify ./raw --graphml # ייצוא ל-Gephi / yEd
/graphify ./raw --neo4j # יצירת cypher.txt ל-Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687
/graphify ./raw --falkordb # יצירת cypher.txt ל-FalkorDB
/graphify ./raw --falkordb-push falkordb://localhost:6379
/graphify ./raw --watch # סנכרון אוטומטי כשקבצים משתנים
/graphify ./raw --mcp # הפעלת שרת MCP stdio
/graphify add https://arxiv.org/abs/1706.03762
/graphify add <video-url>
/graphify add https://... --author "Name" --contributor "Name"
/graphify query "מה מחבר את ה-attention לאופטימייזר?"
/graphify query "..." --dfs --budget 1500
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
graphify save-result --question "Q" --answer "A" --nodes Foo Bar --outcome useful # תיעוד תוצאת שאלה-תשובה (זיכרון עבודה; outcome ∈ useful|dead_end|corrected)
graphify reflect # איחוד תוצאות graphify-out/memory/ אל reflections/LESSONS.md
graphify reflect --if-stale # לא עושה דבר אם LESSONS.md כבר חדש מכל הקלטים (זול להרצה בכל סשן)
graphify reflect --out docs/LESSONS.md # כתיבת מסמך הלקחים למקום אחר
graphify reflect --graph graphify-out/graph.json # קיבוץ לקחים לפי קהילה + כתיבת שכבת זיכרון העבודה (.graphify_learning.json)
# השכבה מתייגת צמתים preferred/tentative/contested (משוקלל-עדכניות, עם מקור);
# graphify explain / query מציגים אז רמז "Lesson:", מסומן "code changed — re-verify" כשהמקור התקדם
graphify uninstall # הסרה מכל הפלטפורמות במכה אחת
graphify uninstall --purge # מחיקה גם של graphify-out/
graphify uninstall --project --platform codex # הסרת קובצי התקנה ברמת פרויקט בלבד
graphify hook install # הוקים של post-commit + post-checkout
graphify hook uninstall
graphify hook status
# הנחיות עוזר קבועות - פר פלטפורמה
graphify claude install # CLAUDE.md + הוק PreToolUse ‏(Claude Code)
graphify claude uninstall
graphify codebuddy install # CODEBUDDY.md + הוק PreToolUse ‏(CodeBuddy)
graphify codebuddy uninstall
graphify codex install # AGENTS.md + הוק PreToolUse ב-.codex/hooks.json ‏(Codex)
graphify opencode install # AGENTS.md + תוסף tool.execute.before ‏(OpenCode)
graphify kilo install # מיומנות Kilo נטיבית + פקודת /graphify + ‏AGENTS.md + תוסף .kilo
graphify kilo uninstall
graphify cursor install # .cursor/rules/graphify.mdc ‏(Cursor)
graphify cursor uninstall
graphify gemini install # GEMINI.md + הוק BeforeTool ‏(Gemini CLI)
graphify gemini uninstall
graphify copilot install # קובץ מיומנות (GitHub Copilot CLI)
graphify copilot uninstall
graphify aider install # AGENTS.md ‏(Aider)
graphify aider uninstall
graphify claw install # AGENTS.md ‏(OpenClaw)
graphify claw uninstall
graphify droid install # AGENTS.md ‏(Factory Droid)
graphify droid uninstall
graphify trae install # AGENTS.md ‏(Trae)
graphify trae uninstall
graphify trae-cn install # AGENTS.md ‏(Trae CN)
graphify trae-cn uninstall
graphify hermes install # AGENTS.md + ~/.hermes/skills/ ‏(Hermes)
graphify hermes uninstall
graphify amp install # קובץ מיומנות (Amp)
graphify amp uninstall
graphify agents install # ~/.agents/skills/ + AGENTS.md ‏(חוצה-פלטפורמות; כינוי: graphify skills)
graphify agents uninstall
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md ‏(Kiro IDE/CLI)
graphify kiro uninstall
graphify pi install # קובץ מיומנות (Pi coding agent)
graphify pi uninstall
graphify devin install # קובץ מיומנות + .windsurf/rules/graphify.md ‏(Devin CLI)
graphify devin uninstall
graphify antigravity install # .agents/rules + .agents/workflows ‏(Google Antigravity)
graphify antigravity uninstall
graphify extract ./docs # חילוץ LLM ‏headless ל-CI ‏(ללא IDE)
graphify extract ./docs --backend gemini # ‏backend מפורש: gemini, kimi, claude, openai, deepseek, ollama, bedrock או claude-cli
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # ‏Ollama מקומי (הגדירו OLLAMA_BASE_URL / OLLAMA_MODEL) - ללא מפתח API ל-loopback
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # כל שרת תואם-OpenAI ‏(llama.cpp, vLLM, LM Studio)
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # כל endpoint תואם-Anthropic ‏(פרוקסי LiteLLM, שערים)
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # דריסת חלון ה-KV-cache (מותאם אוטומטית כברירת מחדל)
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # פריקת המודל אחרי כל chunk (חוסך VRAM ב-GPU קטן)
graphify extract ./docs --backend bedrock # AWS Bedrock דרך IAM - ללא מפתח API, שרשרת אישורי AWS
graphify extract ./docs --backend claude-cli # ניתוב דרך Claude Code CLI - ללא מפתח API, דרך מנוי Claude שלכם
graphify extract ./docs --backend azure # Azure OpenAI (הגדירו AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT)
graphify extract ./docs --max-workers 16 # מקביליות AST ‏(גם GRAPHIFY_MAX_WORKERS)
graphify extract --postgres "postgresql://user:pass@host/db" # אינטרוספקציה ישירה של סכמת PostgreSQL חיה
graphify extract ./my-workspace --cargo # אינטרוספקציה ישירה של תלויות Cargo workspace ברוסט
graphify extract ./docs --token-budget 30000 # ‏chunks סמנטיים קטנים יותר למודלים מקומיים/קטנים
graphify extract ./docs --max-concurrency 2 # פחות קריאות LLM מקביליות (שימושי להרצה מקומית)
graphify extract ./docs --api-timeout 900 # ‏timeout ארוך יותר למודלים מקומיים איטיים (ברירת מחדל 600 שניות)
graphify extract ./docs --google-workspace # ייצוא .gdoc/.gsheet/.gslides דרך gws לפני החילוץ
graphify extract ./docs --mode deep # חילוץ סמנטי עשיר יותר עם system prompt מורחב
graphify extract ./docs --no-cluster # חילוץ גולמי בלבד, דילוג על אשכול
graphify extract ./docs --timing # הדפסת זמני ריצה פר-שלב ל-stderr ‏(עובד גם ב-cluster-only)
graphify extract ./docs --force # דריסת graph.json גם אם לגרף החדש פחות צמתים (אחרי refactors או לניקוי כפילויות רפאים)
graphify extract ./docs --dedup-llm # ‏LLM כמכריע לזוגות ישויות עמומים (משתמש באותו מפתח API)
graphify extract ./docs --global --as myrepo # חילוץ ורישום בגרף הגלובלי חוצה-הפרויקטים
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # הרמת תקרת הפלט לקורפוסים צפופים
graphify export callflow-html # graphify-out/<project>-callflow.html
graphify export callflow-html --max-sections 8 # הגבלת מספר קטעי הארכיטקטורה שנוצרים
graphify export callflow-html --output docs/arch.html
graphify export callflow-html ./some-repo/graphify-out
graphify global add graphify-out/graph.json --as myrepo # רישום גרף פרויקט אל ~/.graphify/global-graph.json
graphify global remove myrepo # הסרת פרויקט מהגרף הגלובלי
graphify global list # הצגת כל המאגרים הרשומים + ספירות צמתים/קשתות
graphify global path # הדפסת הנתיב לקובץ הגרף הגלובלי
graphify prs # לוח PR: ‏CI, ביקורת, worktree, השפעת גרף
graphify prs 42 # צלילה עמוקה ל-PR ‏#42
graphify prs --triage # דירוג טריאז' AI ‏(מזהה backend אוטומטית מהסביבה)
graphify prs --worktrees # מיפוי worktree ← branch ← PR
graphify prs --conflicts # ‏PRs שחולקים קהילות גרף (סיכון בסדר המיזוג)
graphify prs --base main # סינון ל-PRs שמכוונים ל-branch בסיס מסוים
graphify prs --repo owner/repo # הרצה מול מאגר GitHub אחר
GRAPHIFY_TRIAGE_BACKEND=kimi graphify prs --triage # ‏backend מסוים לטריאז'
graphify clone https://github.com/karpathy/nanoGPT
graphify merge-graphs a.json b.json --out merged.json
graphify --version # הדפסת הגרסה המותקנת
graphify watch ./src
graphify check-update ./src
graphify update ./src
graphify update ./src --no-cluster # דילוג על אשכול מחדש, כתיבת גרף AST גולמי בלבד
graphify update ./src --force # דריסה גם אם לגרף החדש פחות צמתים
graphify cluster-only ./my-project
graphify cluster-only ./my-project --graph path/to/graph.json # מיקום גרף מותאם
graphify cluster-only ./my-project --max-concurrency 16 --batch-size 200 # תיוג קהילות מקבילי (גרפים גדולים)
graphify cluster-only ./my-project --resolution 1.5 # יותר קהילות, קטנות יותר
graphify cluster-only ./my-project --exclude-hubs 99 # החרגת צומתי p99 מהחלוקה
graphify cluster-only ./my-project --no-label # השארת מצייני "Community N"
graphify cluster-only ./my-project --backend=gemini # ‏backend לשמות הקהילות
graphify cluster-only ./my-project --backend=gemini --model gemini-2.5-pro # מודל מסוים
graphify label ./my-project # מתן שמות (מחדש) לקהילות עם ה-backend המוגדר
graphify label ./my-project --backend=openai --model gpt-4o # כפיית backend ומודל מסוימים
```
<div dir="rtl">
> **שמות קהילות:** בתוך סוכן (Claude Code, ‏Gemini CLI) הסוכן נותן שמות לקהילות בעצמו. בהרצת ה-CLI החשוף, `cluster-only` נותן שמות אוטומטית עם ה-backend המוגדר (מובנה או ספק תואם-OpenAI מותאם) — העבירו `--no-label` להשארת `Community N`, או הריצו `graphify label` ליצירת שמות מחדש לפי דרישה.
---
## ללמוד עוד
- [איך זה עובד](../how-it-works.md) — צינור החילוץ, זיהוי קהילות, ניקוד ביטחון, מדדים
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — פירוק מודולים, איך מוסיפים שפה
- [אינטגרציות אופציונליות](../docker-mcp-sqlite.md) — ‏Docker MCP Toolkit + ‏SQLite
---
## נבנה על graphify — ‏Penpax
[**Penpax**](https://graphify.com) היא השכבה התמידית שנבנתה מעל graphify — היא מיישמת את אותה גישת גרף על כל חיי העבודה שלכם: פגישות, היסטוריית דפדפן, מיילים, קבצים וקוד, ומתעדכנת ברציפות ברקע.
נבנתה לאנשים שהעבודה שלהם מפוזרת על פני מאות שיחות ומסמכים שהם לעולם לא יוכלו לשחזר במלואם. ללא ענן, לגמרי על המכשיר.
**גרסת ניסיון חינמית תושק בקרוב.** [הצטרפו לרשימת ההמתנה ←](https://graphify.com)
---
<details>
<summary>תרומה לפרויקט</summary>
### הקמת סביבת פיתוח
הפרויקט משתמש ב-[uv](https://docs.astral.sh/uv/) לתהליך הפיתוח. התקינו אותו פעם אחת, ואז:
</div>
```bash
git clone https://github.com/Graphify-Labs/graphify.git
cd graphify
git checkout v8 # ‏branch הפיתוח הפעיל
# יצירת venv לפרויקט והתקנת graphify + כל התוספים + קבוצת dev
# ‏(pytest). ‏uv מתקין את קבוצת התלויות dev כברירת מחדל; העבירו --no-dev לדילוג.
uv sync --all-extras
```
<div dir="rtl">
אימות ההתקנה במצב עריכה:
</div>
```bash
uv run graphify --version
uv run python -c "import graphify; print(graphify.__file__)"
```
<div dir="rtl">
### הרצת בדיקות
</div>
```bash
uv run pytest tests/ -q # הרצת החבילה המלאה
uv run pytest tests/test_extract.py -q # מודול אחד
uv run pytest tests/ -q -k "python" # סינון לפי שם
```
<div dir="rtl">
> הערת macOS: חבילת הבדיקות כוללת גם `sample.f90` וגם `sample.F90`. אלו מתנגשים במערכות קבצים HFS+ / APFS שאינן רגישות לרישיות. הריצו בלינוקס או בקונטיינר Docker אם צריך לבדוק את שתי גרסאות ה-Fortran יחד.
### תהליך עבודה ב-Git
- הפיתוח הפעיל מתרחש ב-branch ‏`v8`.
- סגנון commit: ‏`fix: <description>` / ‏`feat: <description>` / ‏`docs: <description>`
- לפני פתיחת PR, הריצו `uv run pytest tests/ -q` וודאו שהוא עובר.
- הוסיפו קובץ fixture ל-`tests/fixtures/` ובדיקות ל-`tests/test_languages.py` לכל מחלץ שפה חדש.
### מה כדאי לתרום
**דוגמאות עבודה (worked examples)** הן התרומה השימושית ביותר. הריצו `‎/graphify` על קורפוס אמיתי, שמרו את הפלט ב-`worked/{slug}/`, כתבו `review.md` כן שמכסה מה הגרף קלע ומה פספס, ופתחו PR.
**באגים בחילוץ** — פתחו issue עם קובץ הקלט, רשומת ה-cache ‏(`graphify-out/cache/`) ומה חסר או שגוי.
ראו [ARCHITECTURE.md](../../ARCHITECTURE.md) לאחריות המודולים ואיך מוסיפים שפה.
</details>
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**एक AI कोडिंग असिस्टेंट स्किल।** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro या Google Antigravity में `/graphify` टाइप करें — यह आपकी फ़ाइलें पढ़ता है, एक नॉलेज ग्राफ बनाता है, और आपको वह संरचना वापस देता है जो आप नहीं जानते थे कि मौजूद है। कोडबेस को तेज़ी से समझें। आर्किटेक्चरल निर्णयों के पीछे का "क्यों" खोजें।
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **आधिकारिक पैकेज:** PyPI पैकेज का नाम `graphifyy` है (`pip install graphifyy` से इंस्टॉल करें)। PyPI पर `graphify*` नाम वाले अन्य पैकेज इस प्रोजेक्ट से संबद्ध नहीं हैं। एकमात्र आधिकारिक रिपॉजिटरी [safishamsi/graphify](https://github.com/safishamsi/graphify) है।
> **आधिकारिक पैकेज:** PyPI पैकेज का नाम `graphifyy` है (`pip install graphifyy` से इंस्टॉल करें)। PyPI पर `graphify*` नाम वाले अन्य पैकेज इस प्रोजेक्ट से संबद्ध नहीं हैं। एकमात्र आधिकारिक रिपॉजिटरी [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify) है।
### प्लेटफॉर्म समर्थन
@@ -140,4 +140,4 @@ graphify दस्तावेज़ों, papers और छवियों क
## Star इतिहास
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Hivatalos csomag:** A PyPI-csomag neve `graphifyy`. Az egyetlen hivatalos tároló a [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Hivatalos csomag:** A PyPI-csomag neve `graphifyy`. Az egyetlen hivatalos tároló a [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Használat
@@ -74,4 +74,4 @@ A kódfájlokat helyben dolgozza fel tree-sitter AST-n keresztül. A videókat h
A [**Penpax**](https://safishamsi.github.io/penpax.ai) a graphify feletti vállalati réteg. **Ingyenes próbaverzió hamarosan.** [Csatlakozzon a várólistához →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Paket resmi:** Paket PyPI bernama `graphifyy`. Satu-satunya repositori resmi adalah [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Paket resmi:** Paket PyPI bernama `graphifyy`. Satu-satunya repositori resmi adalah [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Penggunaan
@@ -74,4 +74,4 @@ File kode diproses secara lokal melalui tree-sitter AST. Video ditranskrip secar
[**Penpax**](https://safishamsi.github.io/penpax.ai) adalah lapisan enterprise di atas graphify. **Uji coba gratis segera hadir.** [Bergabunglah dengan daftar tunggu →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Pacchetto ufficiale:** Il pacchetto PyPI si chiama `graphifyy`. L'unico repository ufficiale è [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Pacchetto ufficiale:** Il pacchetto PyPI si chiama `graphifyy`. L'unico repository ufficiale è [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Utilizzo
@@ -75,4 +75,4 @@ I file di codice vengono elaborati localmente via tree-sitter AST. I video vengo
[**Penpax**](https://safishamsi.github.io/penpax.ai) è il livello enterprise su graphify. **Prova gratuita in arrivo.** [Unisciti alla lista d'attesa →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+6 -20
View File
@@ -1,8 +1,12 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![CI](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8)](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
@@ -101,24 +105,6 @@ Codex ユーザーは並列抽出のために `~/.codex/config.toml` の `[featu
こう考えてください:常時有効のフックはアシスタントに地図を与え、`/graphify` コマンドはその地図を正確にナビゲートさせます。
<details>
<summary>手動インストール(curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
`~/.claude/CLAUDE.md` に追加します:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 使い方
```
@@ -224,7 +210,7 @@ NetworkX + Leiden(graspologic) + tree-sitter + vis.js。意味的抽出は C
## スター履歴
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
<details>
<summary>コントリビューション</summary>
+6 -20
View File
@@ -1,8 +1,12 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![CI](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8)](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
@@ -137,24 +141,6 @@ python -m graphify.serve graphify-out/graph.json
이를 통해 어시스턴트가 `query_graph`, `get_node`, `get_neighbors`, `shortest_path` 같은 반복 쿼리에 구조화된 그래프 접근을 할 수 있습니다.
<details>
<summary>수동 설치 (curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
`~/.claude/CLAUDE.md`에 추가:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 사용법
```
@@ -268,7 +254,7 @@ graphify는 그래프 레이어입니다. 그 위에 [Penpax](https://safishamsi
## 스타 히스토리
[![Star History Chart](https://starchart.cc/safishamsi/graphify.svg)](https://starchart.cc/safishamsi/graphify)
[![Star History Chart](https://starchart.cc/Graphify-Labs/graphify.svg)](https://starchart.cc/Graphify-Labs/graphify)
<details>
<summary>기여하기</summary>
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Officieel pakket:** Het PyPI-pakket heet `graphifyy`. De enige officiële repository is [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Officieel pakket:** Het PyPI-pakket heet `graphifyy`. De enige officiële repository is [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Gebruik
@@ -74,4 +74,4 @@ Codebestanden worden lokaal verwerkt via tree-sitter AST. Video's lokaal getrans
[**Penpax**](https://safishamsi.github.io/penpax.ai) is de enterprise-laag boven op graphify. **Gratis proefversie binnenkort.** [Meld je aan voor de wachtlijst →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Offisiell pakke:** PyPI-pakken heter `graphifyy`. Det eneste offisielle depotet er [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Offisiell pakke:** PyPI-pakken heter `graphifyy`. Det eneste offisielle depotet er [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Bruk
@@ -74,4 +74,4 @@ Kodefiler behandles lokalt via tree-sitter AST. Videoer transkriberes lokalt med
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oppå graphify. **Gratis prøveperiode kommer snart.** [Bli med på ventelisten →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Oficjalny pakiet:** Pakiet PyPI nazywa się `graphifyy`. Jedyne oficjalne repozytorium to [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Oficjalny pakiet:** Pakiet PyPI nazywa się `graphifyy`. Jedyne oficjalne repozytorium to [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Użycie
@@ -75,4 +75,4 @@ Pliki kodu są przetwarzane lokalnie przez tree-sitter AST. Wideo transkrybowane
[**Penpax**](https://safishamsi.github.io/penpax.ai) to warstwa enterprise nad graphify. **Bezpłatna wersja próbna wkrótce.** [Dołącz do listy oczekujących →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**Uma habilidade para assistentes de código IA.** Digite `/graphify` no Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — ele lê seus arquivos, constrói um grafo de conhecimento e devolve a você estrutura que você não sabia que existia. Entenda uma base de código mais rapidamente. Encontre o "porquê" por trás das decisões arquiteturais.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Pacote oficial:** O pacote PyPI chama-se `graphifyy` (instalar com `pip install graphifyy`). Outros pacotes chamados `graphify*` no PyPI não são afiliados a este projeto. O único repositório oficial é [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Pacote oficial:** O pacote PyPI chama-se `graphifyy` (instalar com `pip install graphifyy`). Outros pacotes chamados `graphify*` no PyPI não são afiliados a este projeto. O único repositório oficial é [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
### Suporte a plataformas
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extração semântica vi
## Histórico de estrelas
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Pachet oficial:** Pachetul PyPI se numește `graphifyy`. Singurul depozit oficial este [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Pachet oficial:** Pachetul PyPI se numește `graphifyy`. Singurul depozit oficial este [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Utilizare
@@ -74,4 +74,4 @@ Fișierele de cod sunt procesate local prin tree-sitter AST. Videoclipurile sunt
[**Penpax**](https://safishamsi.github.io/penpax.ai) este stratul enterprise peste graphify. **Perioadă de probă gratuită în curând.** [Alăturați-vă listei de așteptare →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**Навык для AI-ассистента по написанию кода.** Введите `/graphify` в Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro или Google Antigravity — он прочитает ваши файлы, построит граф знаний и вернёт вам структуру, о существовании которой вы не подозревали. Понимайте кодовую базу быстрее. Находите «почему» за архитектурными решениями.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Официальный пакет:** Пакет PyPI называется `graphifyy` (установить через `pip install graphifyy`). Другие пакеты с именем `graphify*` на PyPI не связаны с этим проектом. Единственный официальный репозиторий — [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Официальный пакет:** Пакет PyPI называется `graphifyy` (установить через `pip install graphifyy`). Другие пакеты с именем `graphify*` на PyPI не связаны с этим проектом. Единственный официальный репозиторий — [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
### Поддержка платформ
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Семантическо
## История звёзд
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Officiellt paket:** PyPI-paketet heter `graphifyy`. Det enda officiella förrådet är [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Officiellt paket:** PyPI-paketet heter `graphifyy`. Det enda officiella förrådet är [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Användning
@@ -74,4 +74,4 @@ Kodfiler behandlas lokalt via tree-sitter AST. Videor transkriberas lokalt med f
[**Penpax**](https://safishamsi.github.io/penpax.ai) är enterprise-lagret ovanpå graphify. **Gratis provperiod kommer snart.** [Gå med i väntelistan →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **แพ็กเกจอย่างเป็นทางการ:** แพ็กเกจ PyPI ชื่อ `graphifyy` repository อย่างเป็นทางการเดียวคือ [safishamsi/graphify](https://github.com/safishamsi/graphify)
> **แพ็กเกจอย่างเป็นทางการ:** แพ็กเกจ PyPI ชื่อ `graphifyy` repository อย่างเป็นทางการเดียวคือ [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify)
## การใช้งาน
@@ -74,4 +74,4 @@ graphify update ./src
[**Penpax**](https://safishamsi.github.io/penpax.ai) คือชั้น enterprise เหนือ graphify **ทดลองใช้ฟรีเร็วๆ นี้** [เข้าร่วมรายชื่อรอ →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Resmi paket:** PyPI paketi `graphifyy` olarak adlandırılır. Tek resmi depo [safishamsi/graphify](https://github.com/safishamsi/graphify)'dir.
> **Resmi paket:** PyPI paketi `graphifyy` olarak adlandırılır. Tek resmi depo [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify)'dir.
## Kullanım
@@ -74,4 +74,4 @@ Kod dosyaları tree-sitter AST aracılığıyla yerel olarak işlenir. Videolar
[**Penpax**](https://safishamsi.github.io/penpax.ai), graphify üzerindeki kurumsal katmandır. **Ücretsiz deneme yakında.** [Bekleme listesine katılın →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+15 -9
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -9,17 +9,17 @@
<p align="center">
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://clickpy.clickhouse.com/dashboard/graphifyy"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsql-clickhouse.clickhouse.com%2F%3Fquery%3DSELECT%2520concat%2528toString%2528round%2528sum%2528count%2529%2F1000%2529%2529%2C%2520%2527k%2527%2529%2520AS%2520c%2520FROM%2520pypi.pypi_downloads%2520WHERE%2520project%253D%2527graphifyy%2527%2520FORMAT%2520JSON%26user%3Ddemo&query=%24.data%5B0%5D.c&label=downloads&color=blue" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
</p>
<p align="center">
<a href="https://star-history.com/#safishamsi/graphify&Date">
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
<a href="https://star-history.com/#Graphify-Labs/graphify&Date">
<img src="https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date" alt="Star History Chart" width="370"/>
</a>
</p>
@@ -326,8 +326,12 @@ MCP-сервер надає асистенту структурований до
| Змінна | Використання | Коли потрібна |
|---|---|---|
| `ANTHROPIC_API_KEY` | Backend Claude (Anthropic) | `--backend claude` |
| `ANTHROPIC_BASE_URL` | URL Anthropic-сумісного endpoint (LiteLLM proxy, шлюзи, ...) | `--backend claude` (типово: `https://api.anthropic.com`) |
| `ANTHROPIC_MODEL` | Назва моделі для backend Claude — для власних endpoint використовуйте назву/псевдонім моделі вашого сервера | `--backend claude` (типово: `claude-sonnet-4-6`) |
| `GEMINI_API_KEY` або `GOOGLE_API_KEY` | Backend Google Gemini | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI або OpenAI-сумісні API | `--backend openai` |
| `OPENAI_API_KEY` | OpenAI або OpenAI-сумісні API | `--backend openai` (локальні сервери приймають будь-яке непорожнє значення) |
| `OPENAI_BASE_URL` | URL OpenAI-сумісного сервера (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (типово: `https://api.openai.com/v1`) |
| `OPENAI_MODEL` | Назва моделі для backend OpenAI — для self-hosted серверів використовуйте назву/псевдонім моделі, яку надає ваш сервер (див. його endpoint `/v1/models`), напр. `LFM2.5-8B-A1B-UD-Q4_K_XL` для llama.cpp | `--backend openai` (типово: `gpt-4.1-mini`) |
| `DEEPSEEK_API_KEY` | Backend DeepSeek | `--backend deepseek` |
| `MOONSHOT_API_KEY` | Backend Kimi Code | `--backend kimi` |
| `OLLAMA_BASE_URL` | URL локального виводу Ollama | `--backend ollama` (типово: `http://localhost:11434`) |
@@ -463,6 +467,8 @@ graphify extract ./docs # headless LLM-витягуван
graphify extract ./docs --backend gemini # явний backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock або claude-cli
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # локальний Ollama (встановіть OLLAMA_BASE_URL / OLLAMA_MODEL) — без API-ключа для loopback
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # будь-який OpenAI-сумісний сервер (llama.cpp, vLLM, LM Studio)
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # будь-який Anthropic-сумісний endpoint (LiteLLM proxy, шлюзи)
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # перевизначити KV-кеш вікно (автоматично за замовчуванням)
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # вивантажити модель після кожного шматка (економить VRAM на малих GPU)
graphify extract ./docs --backend bedrock # AWS Bedrock через IAM — без API-ключа, використовує ланцюг облікових даних AWS
@@ -523,11 +529,11 @@ graphify cluster-only ./my-project --exclude-hubs 99 # виключи
## Побудовано на graphify — Penpax
[**Penpax**](https://graphifylabs.ai) — це завжди активний шар поверх graphify, він застосовує той самий графовий підхід до всього робочого життя: зустрічей, історії браузера, email-ів, файлів і коду, постійно оновлюючись у фоновому режимі.
[**Penpax**](https://graphify.com) — це завжди активний шар поверх graphify, він застосовує той самий графовий підхід до всього робочого життя: зустрічей, історії браузера, email-ів, файлів і коду, постійно оновлюючись у фоновому режимі.
Створений для людей, чия робота розкидана по сотнях розмов і документів, які неможливо повністю відтворити. Без хмари, повністю на пристрої.
**Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://graphifylabs.ai)
**Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://graphify.com)
---
@@ -539,7 +545,7 @@ graphify cluster-only ./my-project --exclude-hubs 99 # виключи
Клонуйте репо і встановіть у редагованому режимі:
```bash
git clone https://github.com/safishamsi/graphify.git
git clone https://github.com/Graphify-Labs/graphify.git
cd graphify
git checkout v8 # гілка активної розробки
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
</p>
**Sun'iy intellektga asoslangan kod yordamchilari uchun ko'nikma.** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro yoki Google Antigravity da `/graphify` deb yozing — u sizning fayllaringizni o'qiydi, bilim grafini quradi va siz bilmagan tuzilmani sizga qaytaradi. Kod bazasini tezroq tushuning. Arxitektura qarorlari ortidagi "nima uchun" savoliga javob toping.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Rasmiy paket:** PyPI dagi paket nomi `graphifyy` (`pip install graphifyy` orqali o'rnatiladi). PyPI dagi boshqa `graphify*` nomli paketlar bu loyiha bilan bog'liq emas. Yagona rasmiy repozitoriy — [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Rasmiy paket:** PyPI dagi paket nomi `graphifyy` (`pip install graphifyy` orqali o'rnatiladi). PyPI dagi boshqa `graphify*` nomli paketlar bu loyiha bilan bog'liq emas. Yagona rasmiy repozitoriy — [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
### Platforma qo'llab-quvvatlash
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantik chiqarish Claud
## Yulduzlar tarixi
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Gói chính thức:** Gói PyPI có tên là `graphifyy`. Kho lưu trữ chính thức duy nhất là [safishamsi/graphify](https://github.com/safishamsi/graphify).
> **Gói chính thức:** Gói PyPI có tên là `graphifyy`. Kho lưu trữ chính thức duy nhất là [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
## Sử dụng
@@ -74,4 +74,4 @@ Các tệp code được xử lý cục bộ qua tree-sitter AST. Video được
[**Penpax**](https://safishamsi.github.io/penpax.ai) là lớp doanh nghiệp trên graphify. **Dùng thử miễn phí sắp ra mắt.** [Tham gia danh sách chờ →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+12 -22
View File
@@ -1,11 +1,15 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![CI](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8)](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
**一个面向 AI 编码助手的技能。** 在 Claude Code、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
**一个面向 AI 编码助手的技能。** 在 Claude Code、CodeBuddy、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
@@ -33,7 +37,7 @@ graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件
## 安装
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[OpenClaw](https://openclaw.ai)、[Factory Droid](https://factory.ai) 或 [Trae](https://trae.ai)
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[CodeBuddy](https://codebuddy.ai)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[OpenClaw](https://openclaw.ai)、[Factory Droid](https://factory.ai) 或 [Trae](https://trae.ai)
```bash
pip install graphifyy && graphify install
@@ -46,6 +50,7 @@ pip install graphifyy && graphify install
| 平台 | 安装命令 |
|------|----------|
| Claude Code | `graphify install` |
| CodeBuddy | `graphify install --platform codebuddy` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| OpenClaw | `graphify install --platform claw` |
@@ -53,7 +58,7 @@ pip install graphifyy && graphify install
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。CodeBuddy 使用与 Claude Code 相同的 Agent 工具和 PreToolUse hook 机制。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
然后打开你的 AI 编码助手,输入:
@@ -68,6 +73,7 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
| 平台 | 命令 |
|------|------|
| Claude Code | `graphify claude install` |
| CodeBuddy | `graphify codebuddy install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| OpenClaw | `graphify claw install` |
@@ -81,6 +87,8 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
**CodeBuddy** 与 Claude Code 相同,也会做两件事:在 `CODEBUDDY.md` 中写入规则,并安装 **PreToolUse hook**(写入 `.codebuddy/settings.json`),在每次 `Glob` 和 `Grep` 前触发。
**Codex、OpenCode、OpenClaw、Factory Droid、Trae** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
@@ -93,24 +101,6 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
可以这样理解:常驻 hook 是先给助手一张地图,`/graphify` 这几个命令则是让它沿着地图精确导航。
<details>
<summary>手动安装(curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
把下面内容加到 `~/.claude/CLAUDE.md`:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 用法
```
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **官方套件:** PyPI 套件名稱為 `graphifyy`。唯一的官方儲存庫是 [safishamsi/graphify](https://github.com/safishamsi/graphify)。
> **官方套件:** PyPI 套件名稱為 `graphifyy`。唯一的官方儲存庫是 [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify)。
## 使用方式
@@ -74,4 +74,4 @@ graphify update ./src
[**Penpax**](https://safishamsi.github.io/penpax.ai) 是 graphify 之上的企業層。**免費試用即將推出。** [加入等待名單 →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
+2
View File
@@ -19,6 +19,8 @@ def __getattr__(name):
"to_svg": ("graphify.export", "to_svg"),
"to_canvas": ("graphify.export", "to_canvas"),
"to_wiki": ("graphify.wiki", "to_wiki"),
"reflect": ("graphify.reflect", "reflect"),
"save_query_result": ("graphify.ingest", "save_query_result"),
}
if name in _map:
import importlib
+623 -4107
View File
File diff suppressed because it is too large. Load diff
+107
View File
@@ -0,0 +1,107 @@
"""MinHash + band-LSH — datasketch-compatible drop-in (no scipy).
datasketch.lsh has `from scipy.integrate import quad` at module level.
scipy's array_api_compat layer then lazily loads numpy.testing, which calls
platform.machine() at import time to set test-skip decorator constants — and
that in turn spawns cmd.exe via subprocess, hanging for minutes under EDR
software in corporate Windows environments.
Covers the exact MinHash/MinHashLSH API surface used by dedup.py.
Hash family (Mersenne-prime permutations) and LSH band structure are
equivalent to datasketch so dedup quality is unchanged.
"""
from __future__ import annotations
import hashlib
import struct
import numpy as np
_MP = np.uint64((1 << 61) - 1) # Mersenne prime for the hash family
_MH = np.uint64(0xFFFF_FFFF) # mask to 32-bit values
# One (a, b) coefficient array per num_perm, shared across all instances.
_MH_COEFFS: dict[int, tuple[np.ndarray, np.ndarray]] = {}
def _mh_coeffs(num_perm: int) -> tuple[np.ndarray, np.ndarray]:
if num_perm not in _MH_COEFFS:
rng = np.random.RandomState(1)
a = rng.randint(1, int(_MP), num_perm, dtype=np.uint64)
b = rng.randint(0, int(_MP), num_perm, dtype=np.uint64)
_MH_COEFFS[num_perm] = (a, b)
return _MH_COEFFS[num_perm]
class MinHash:
"""MinHash sketch — same API as datasketch.MinHash for the subset used here."""
__slots__ = ("num_perm", "hashvalues", "_a", "_b")
def __init__(self, num_perm: int = 128) -> None:
self.num_perm = num_perm
self.hashvalues = np.full(num_perm, int(_MH), dtype=np.uint64)
self._a, self._b = _mh_coeffs(num_perm)
def update(self, v: bytes) -> None:
hv = np.uint64(struct.unpack("<I", hashlib.sha1(v).digest()[:4])[0])
phv = np.bitwise_and((self._a * hv + self._b) % _MP, _MH)
self.hashvalues = np.minimum(self.hashvalues, phv)
def _lsh_integrate(f, lo: float, hi: float, n: int = 128) -> float:
"""Numerical integration — replaces scipy.integrate.quad for LSH param search."""
h = (hi - lo) / n
return h * sum(f(lo + i * h) for i in range(n))
_LSH_PARAMS_CACHE: dict[tuple[float, int], tuple[int, int]] = {}
def _optimal_lsh_params(threshold: float, num_perm: int) -> tuple[int, int]:
"""Find (bands, rows) that minimise weighted FP+FN error, without scipy."""
key = (threshold, num_perm)
if key in _LSH_PARAMS_CACHE:
return _LSH_PARAMS_CACHE[key]
best_err, best = float("inf"), (1, 1)
for b in range(1, num_perm + 1):
for r in range(1, num_perm // b + 1):
fp = _lsh_integrate(
lambda s, _b=float(b), _r=float(r): 1 - (1 - s ** _r) ** _b,
0.0, threshold,
)
fn = _lsh_integrate(
lambda s, _b=float(b), _r=float(r): 1 - (1 - (1 - s ** _r) ** _b),
threshold, 1.0,
)
err = 0.5 * fp + 0.5 * fn
if err < best_err:
best_err, best = err, (b, r)
_LSH_PARAMS_CACHE[key] = best
return best
class MinHashLSH:
"""Band-hashing LSH — same API as datasketch.MinHashLSH for the subset used here."""
def __init__(self, threshold: float = 0.5, num_perm: int = 128) -> None:
self.b, self.r = _optimal_lsh_params(threshold, num_perm)
self._tables: list[dict[bytes, list[str]]] = [{} for _ in range(self.b)]
self._keys: set[str] = set()
def insert(self, key: str, minhash: MinHash) -> None:
if key in self._keys:
raise ValueError(f"Key {key!r} already exists in MinHashLSH")
self._keys.add(key)
hv = minhash.hashvalues
for i, table in enumerate(self._tables):
band = hv[i * self.r : (i + 1) * self.r].tobytes()
table.setdefault(band, []).append(key)
def query(self, minhash: MinHash) -> list[str]:
hv = minhash.hashvalues
candidates: set[str] = set()
for i, table in enumerate(self._tables):
band = hv[i * self.r : (i + 1) * self.r].tobytes()
candidates.update(table.get(band, []))
return list(candidates)
+173 -9
View File
@@ -4,15 +4,23 @@ from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import unicodedata
import networkx as nx
DEFAULT_AFFECTED_RELATIONS = (
"calls",
"indirect_call",
"references",
"imports",
"imports_from",
# `import('…')` — emitted by the Svelte/Astro/Vue rescue passes and (since
# #2575) by plain JS/TS too. Omitting it made every dynamic import
# invisible to blast-radius traversal even where the edge WAS in the
# graph, and dynamic import is precisely how codebases break require
# cycles, so the missing edges sat under the most load-bearing modules.
"dynamic_import",
"re_exports",
"inherits",
"extends",
@@ -20,6 +28,7 @@ DEFAULT_AFFECTED_RELATIONS = (
"uses",
"mixes_in",
"embeds",
"requires",
)
@@ -28,6 +37,11 @@ class AffectedHit:
node_id: str
depth: int
via_relation: str
# The traversed edge's location — the actual call/import/reference SITE in
# this node's file, not the node's own definition line (#BUG1). Defaults keep
# existing constructors/tests working; None falls back to the node's def line.
via_file: "str | None" = None
via_location: "str | None" = None
def _node_label(graph: nx.Graph, node_id: str) -> str:
@@ -43,28 +57,130 @@ def _format_location(data: dict) -> str:
return str(source_file)
def resolve_seed(graph: nx.Graph, query: str) -> str | None:
def _bare_name(label: str) -> str:
"""Lowercased label with the callable decoration (trailing "()") removed."""
label = _normalize_label(label)
return label[:-2] if label.endswith("()") else label
def _normalize_label(label: str) -> str:
return unicodedata.normalize("NFC", label).casefold()
def _as_repo_relative(query: str, root: Path | None = None) -> str:
"""Repo-relative form of a path query, for matching a stored `source_file`.
The graph stores repo-relative paths, so `./src/x.py` and
`/abs/repo/src/x.py` name the same file as `src/x.py` and yet matched
nothing. `affected` then printed an empty list and exited 0 — a blast-radius
tool answering "nothing depends on this" about a file with sixteen
dependents, and indistinguishable from a genuine zero or a typo.
An absolute path is anchored to `root` when given — the repo root derived
from the graph's own location — so a seed resolves regardless of the caller's
working directory (#2706: an absolute-path seed previously only matched when
cwd happened to be the analysed repo root, which no editor or script can
guarantee). `root` falls back to the current directory to preserve the prior
behaviour when a caller has no graph location to derive it from.
Non-path queries pass through unchanged: `Path("myFunc()").as_posix()` is
`"myFunc()"`, so label resolution is untouched. An absolute path rooted
outside `root` is left alone — no basename guessing.
"""
path = Path(query)
if path.is_absolute():
anchor = root if root is not None else Path.cwd()
try:
return path.relative_to(anchor).as_posix()
except ValueError:
# Rooted outside the repo: nothing here can make it repo-relative,
# so leave it alone rather than guess at a basename that would match
# some unrelated file with the same name.
return query
return path.as_posix()
def _prefer_file_node(
graph: nx.Graph,
node_ids: list[str],
query: str,
) -> str | None:
"""Return the file-level node when a source_file query matches many nodes."""
query_basename = _normalize_label(Path(query).name)
exact_file_nodes = [
node_id
for node_id in node_ids
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
and _normalize_label(str(graph.nodes[node_id].get("label", ""))) == query_basename
]
if len(exact_file_nodes) == 1:
return exact_file_nodes[0]
l1_nodes = [
node_id
for node_id in node_ids
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
]
if len(l1_nodes) == 1:
return l1_nodes[0]
basename_nodes = [
node_id
for node_id in node_ids
if _normalize_label(str(graph.nodes[node_id].get("label", ""))) == query_basename
]
if len(basename_nodes) == 1:
return basename_nodes[0]
return None
def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str | None:
# A trailing path separator must not change a source-file match — serve's
# _find_node tokenizes the path (which drops it), so strip it here for parity
# (otherwise `affected "src/x.ts/"` returned None while `explain` resolved it).
query = query.rstrip("/\\") or query
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]
# Callable labels are decorated ("name()"), so a bare "name" query falls
# through exact matching and then ties with any "name*" sibling in the
# contains pass. Match on the undecorated name before giving up.
query_bare = _bare_name(query_lower)
bare_name_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if _bare_name(str(data.get("label", ""))) == query_bare
]
if len(bare_name_matches) == 1:
return bare_name_matches[0]
# Compare paths in repo-relative form. Only this branch is path-shaped; the
# label branches above keep the query verbatim.
query_path = _normalize_label(_as_repo_relative(query, root))
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", ""))) in (query_lower, query_path)
]
if len(exact_source_matches) == 1:
return exact_source_matches[0]
if exact_source_matches:
preferred_file_node = _prefer_file_node(
graph, exact_source_matches, _as_repo_relative(query, root)
)
if preferred_file_node is not None:
return preferred_file_node
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]
@@ -83,6 +199,27 @@ def affected_nodes(
queue: deque[tuple[str, int]] = deque([(seed, 0)])
hits: list[AffectedHit] = []
# #1669: seed the reverse walk with the root's own member nodes (one outward
# `method`/`contains` hop). A caller can bind to a class's method node rather
# than the class node itself (e.g. `Service.call` resolves to the `def
# self.call` node, #1634), so those callers are unreachable from the class
# otherwise. The member nodes are seeds only (not reported as hits), and
# `method`/`contains` stay out of the general relation-filtered walk, so this
# adds no forward noise anywhere else.
if hasattr(graph, "out_edges"):
member_edges = graph.out_edges(seed, data=True)
else:
member_edges = (
(s, t, d) for s, t, d in graph.edges(data=True) if s == seed
)
for _s, member, data in member_edges:
if str(data.get("relation", "")) not in ("method", "contains"):
continue
member = str(member)
if member not in seen:
seen.add(member)
queue.append((member, 0))
while queue:
current, current_depth = queue.popleft()
if current_depth >= depth:
@@ -103,7 +240,15 @@ def affected_nodes(
if source in seen:
continue
seen.add(source)
hit = AffectedHit(source, current_depth + 1, relation)
# Carry the matched edge's location (taken from the SAME edge dict
# whose relation passed the filter, so relation and location stay
# consistent) — that is the call/import/reference site in `source`'s
# own file, which is where the user should click (#BUG1).
hit = AffectedHit(
source, current_depth + 1, relation,
via_file=str(data.get("source_file") or "") or None,
via_location=str(data.get("source_location") or "") or None,
)
hits.append(hit)
queue.append((source, current_depth + 1))
@@ -116,9 +261,10 @@ def format_affected(
*,
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
depth: int = 2,
root: Path | None = None,
) -> str:
relation_list = tuple(relations)
seed = resolve_seed(graph, query)
seed = resolve_seed(graph, query, root)
if seed is None:
return f"No unique node match for {query}"
@@ -134,8 +280,14 @@ def format_affected(
for hit in hits:
data = graph.nodes[hit.node_id]
if hit.via_location:
# The relation SITE in this node's file (call/import/reference line),
# labeled by [via_relation] so it's never mistaken for a def line.
location = f"{hit.via_file or data.get('source_file') or '-'}:{hit.via_location}"
else:
location = _format_location(data) # honest fallback: the node's own def line
lines.append(
f"- {_node_label(graph, hit.node_id)} [{hit.via_relation}] {_format_location(data)}"
f"- {_node_label(graph, hit.node_id)} [{hit.via_relation}] {location}"
)
return "\n".join(lines)
@@ -144,10 +296,22 @@ def load_graph(path: Path) -> nx.Graph:
import json
from networkx.readwrite import json_graph
raw = json.loads(path.read_text(encoding="utf-8"))
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
raise RuntimeError(
f"Cannot read graph file {path}: {exc}. "
"Re-run 'graphify extract' to regenerate it."
) from exc
# Force directed so stored caller→callee direction survives the round-trip;
# mirrors serve.py and __main__.py (#1174).
raw = {**raw, "directed": True}
# Normalize the edge key: graphify's `extract` output uses "edges" while
# networkx's node_link_data default is "links". Without this, an edges-keyed
# graph.json raises an uncaught KeyError: 'links' here — every other loader
# (__main__.py) already normalizes this (#738; same class as #1198).
if "links" not in raw and "edges" in raw:
raw = dict(raw, links=raw["edges"])
try:
return json_graph.node_link_graph(raw, edges="links")
except TypeError:
+1 -1
View File
@@ -2,7 +2,7 @@
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
When the user types `/graphify`, invoke the `skill` tool with `skill: "graphify"` before doing anything else.
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
Rules:
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
+76 -13
View File
@@ -13,21 +13,37 @@ _BUILTIN_NOISE_LABELS = frozenset({
"True", "False",
"MagicMock", "Mock", "AsyncMock", "NonCallableMock",
"NonCallableMagicMock", "PropertyMock", "patch", "sentinel",
# Python stdlib types commonly confused for project symbols
"Path", "Any", "Optional", "List", "Dict", "Set", "Tuple", "Union",
"Callable", "Type", "ClassVar", "Final", "Literal", "Protocol",
"Counter", "defaultdict", "OrderedDict", "datetime", "Enum",
"os", "sys", "re", "json", "io", "abc", "typing",
# Swift / Foundation / SwiftUI framework symbols and module imports that
# otherwise dominate god-node rankings on Swift codebases (#2147)
"Foundation", "SwiftUI", "UIKit", "AppKit", "Combine",
"String", "Int", "Double", "Float", "Bool", "Data", "URL", "Date", "UUID",
"Sendable", "Codable", "Decodable", "Encodable", "Equatable", "Hashable",
"Identifiable", "Comparable", "AnyObject", "Error", "LocalizedError",
"NSObject", "NSString", "NSError", "NSLock",
"View", "Color", "Font", "DispatchQueue",
})
# Language families — extensions sharing a runtime can legitimately call each other
_LANG_FAMILY: dict[str, str] = {
**{e: "python" for e in (".py", ".pyw")},
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
**{e: "js" for e in (".js", ".jsx", ".mjs", ".cjs", ".ejs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte")},
**{e: "go" for e in (".go",)},
**{e: "rust" for e in (".rs",)},
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
**{e: "ruby" for e in (".rb",)},
**{e: "ruby" for e in (".rb", ".rake")},
**{e: "swift" for e in (".swift",)},
**{e: "dotnet" for e in (".cs",)},
**{e: "dotnet" for e in (".cs", ".vb")},
**{e: "php" for e in (".php",)},
**{e: "r" for e in (".r",)},
**{e: "cobol" for e in (".cbl", ".cob", ".cobol", ".cpy")},
**{e: "solidity" for e in (".sol",)},
**{e: "erlang" for e in (".erl", ".hrl", ".escript")},
}
@@ -59,11 +75,12 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
label = attrs.get("label", "")
if not label:
return False
# File-level hub: label matches the actual source filename (not just any label ending in .py)
# File-level hub: label matches the actual source filename — bare basename OR
# the directory-qualified form the #2032 disambiguation pass may assign.
source_file = attrs.get("source_file", "")
if source_file:
from pathlib import Path as _Path
if label == _Path(source_file).name:
from graphify.build import _is_file_node_label
if _is_file_node_label(label, source_file):
return True
# Method stub: AST extractor labels methods as '.method_name()'
if label.startswith(".") and label.endswith("()"):
@@ -92,16 +109,31 @@ def _is_json_key_node(G: nx.Graph, node_id: str) -> bool:
return label in _JSON_NOISE_LABELS
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
def god_nodes(G: nx.Graph, top_n: int = 10,
exclude_hubs_percentile: float | None = None) -> list[dict]:
"""Return the top_n most-connected real entities - the core abstractions.
File-level hub nodes are excluded: they accumulate import/contains edges
mechanically and don't represent meaningful architectural abstractions.
``exclude_hubs_percentile`` (0-100) suppresses nodes whose degree exceeds
that percentile of the graph's degree distribution, using the same
threshold computation ``cluster()`` applies (#3205) - so the one setting
suppresses utility hubs in the ranking AND in community resolution,
instead of only the latter. ``None`` keeps the historical ranking.
"""
degree = dict(G.degree())
hub_threshold: float | None = None
if exclude_hubs_percentile is not None:
degrees = sorted(degree.values())
if degrees:
idx = max(0, int(len(degrees) * exclude_hubs_percentile / 100) - 1)
hub_threshold = degrees[idx]
sorted_nodes = sorted(degree.items(), key=lambda x: x[1], reverse=True)
result = []
for node_id, deg in sorted_nodes:
if hub_threshold is not None and deg > hub_threshold:
continue
if _is_file_node(G, node_id) or _is_concept_node(G, node_id) or _is_json_key_node(G, node_id):
continue
if G.nodes[node_id].get("label", "") in _BUILTIN_NOISE_LABELS:
@@ -182,8 +214,19 @@ def _file_category(path: str) -> str:
def _top_level_dir(path: str) -> str:
"""Return the first path component - used to detect cross-repo edges."""
return path.split("/")[0] if "/" in path else path
"""Return the first path component - used to detect cross-repo edges.
A path with no "/" is a file at the scan root, so its top-level directory
is the root itself ("."), not the filename: otherwise every pair of
root-level files would look like it crosses repos/directories. "." keeps
root files distinct from an absolute path outside the root, whose first
component is "". Backslashes and a leading "./" are normalised first,
since a graph.json loaded without build_from_json can still carry them.
"""
path = path.replace("\\", "/")
while path.startswith("./"):
path = path[2:]
return path.split("/")[0] if "/" in path else "."
def _surprise_score(
@@ -231,8 +274,12 @@ def _surprise_score(
score += 2
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
# 3. Cross-repo bonus - different top-level directory
if _top_level_dir(u_source) != _top_level_dir(v_source) and not _suppress_structural:
# 3. Cross-repo bonus - different top-level directory. merge-graphs /
# global add keep source_file repo-relative and tag nodes with `repo`, so
# the repo is part of the key (absent on a single-repo graph).
top_u = (G.nodes[u].get("repo"), _top_level_dir(u_source))
top_v = (G.nodes[v].get("repo"), _top_level_dir(v_source))
if top_u != top_v and not _suppress_structural:
score += 2
reasons.append("connects across different repos/directories")
@@ -499,7 +546,10 @@ def suggest_questions(
# 4. Isolated or weakly-connected nodes → exploration questions
isolated = [
n for n in G.nodes()
if G.degree(n) <= 1 and not _is_file_node(G, n) and not _is_concept_node(G, n)
if G.degree(n) <= 1
and not _is_file_node(G, n)
and not _is_concept_node(G, n)
and G.nodes[n].get("file_type") != "rationale"
]
if isolated:
labels = [G.nodes[n].get("label", n) for n in isolated[:3]]
@@ -658,6 +708,16 @@ def find_import_cycles(
if rel not in ("imports_from", "re_exports"):
continue
# Deferred `import(...)` edges are real dependencies but do not form a
# hard file-level cycle, so they are excluded from cycle detection (#1241).
if data.get("deferred"):
continue
# Type-only imports/re-exports (`import type` / `export type ... from`)
# are erased at compile time - a cycle that closes through one cannot
# exist at runtime (#3123). The edge itself stays in the graph.
if data.get("type_only"):
continue
src_file_attr = data.get("source_file", "")
if not isinstance(src_file_attr, str) or not src_file_attr:
continue
@@ -686,8 +746,11 @@ def find_import_cycles(
return []
# Step 2: Find simple cycles, bounded by length.
# Pass length_bound so networkx prunes during enumeration rather than
# enumerating all elementary cycles and post-filtering — avoids exponential
# blowup on dense graphs with many long cycles (#1196).
cycles: list[list[str]] = []
for cycle in nx.simple_cycles(file_graph):
for cycle in nx.simple_cycles(file_graph, length_bound=max_cycle_length):
if len(cycle) <= max_cycle_length:
cycles.append(cycle)
if len(cycles) >= top_n * 10:
+9 -12
View File
@@ -1,13 +1,11 @@
"""Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach."""
from __future__ import annotations
import json
import sys
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.build import edge_data
from graphify.serve import _query_terms
from graphify.paths import default_graph_json as _default_graph_json
_CHARS_PER_TOKEN = 4 # standard approximation
@@ -41,7 +39,7 @@ def _query_subgraph_tokens(G: nx.Graph, question: str, depth: int = 3) -> int:
terms = _query_terms(question)
scored = []
for nid, data in G.nodes(data=True):
label = data.get("label", "").lower()
label = (data.get("label") or "").lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
@@ -85,7 +83,7 @@ _SAMPLE_QUESTIONS = [
def run_benchmark(
graph_path: str = "graphify-out/graph.json",
graph_path: str | None = None,
corpus_words: int | None = None,
questions: list[str] | None = None,
) -> dict:
@@ -98,13 +96,12 @@ def run_benchmark(
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
"""
from graphify.security import check_graph_file_size_cap
check_graph_file_size_cap(Path(graph_path))
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
try:
G = json_graph.node_link_graph(data, edges="links")
except TypeError:
G = json_graph.node_link_graph(data)
graph_path = graph_path or _default_graph_json()
# Size-cap check + links/edges normalization + node-link parse. A raw
# --no-cluster graph stores edges under "edges" and used to KeyError
# here (#2212).
from graphify.paths import load_node_link_graph
G = load_node_link_graph(graph_path)
if corpus_words is None:
# Rough estimate: each node label is ~3 words, plus source context
+2100 -128
View File
File diff suppressed because it is too large. Load diff
+1472 -107
View File
File diff suppressed because it is too large. Load diff
+45 -14
View File
@@ -30,6 +30,8 @@ from collections import Counter, defaultdict
from datetime import datetime, timezone
from html import escape
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME
# ──────────────────────────────────────────────
# 1. CSS template (fixed, project-agnostic)
@@ -225,12 +227,22 @@ def _node_link_payload(data: dict) -> tuple[list, list] | None:
return None
try:
from networkx.readwrite import json_graph
# Shared loader normalizes the raw writer's "edges" key to "links"
# before parsing; without it an edges-keyed payload raised
# KeyError: 'links' and this function silently returned None even
# though the shape check above accepts "edges" (#2212).
from graphify.paths import load_node_link_graph
try:
graph = json_graph.node_link_graph(data, edges="links")
except TypeError:
graph = json_graph.node_link_graph(data)
# Force directed/multigraph so the stored caller->callee direction and
# parallel edges survive the round-trip; mirrors affected.py,
# serve.py and cli.py (#1174) and the directed-view fix for
# path/shortest_path (#2487, #2309). graph.json is written with
# "directed": false for backward compatibility, so without this
# networkx returns an undirected Graph and edge orientation becomes
# arbitrary -- which silently swaps the Caller and Callee columns of
# the call table and drops parallel edges. The _src/_tgt override
# below still wins on legacy marker files.
graph = load_node_link_graph({**data, "directed": True, "multigraph": True})
except Exception:
return None
@@ -404,7 +416,7 @@ def infer_project_name(graph_path: str, meta: dict) -> str:
if meta.get("project_name"):
return meta["project_name"]
path = Path(graph_path).resolve()
if path.parent.name == "graphify-out" and len(path.parents) > 1:
if path.parent.name == GRAPHIFY_OUT_NAME and len(path.parents) > 1:
return path.parents[1].name
return path.parent.name or "Project"
@@ -419,9 +431,9 @@ def resolve_graphify_paths(args) -> dict:
elif (base / "graph.json").exists():
graphify_out = base
else:
graphify_out = base / "graphify-out"
graphify_out = base / GRAPHIFY_OUT
project_root = graphify_out.parent if graphify_out.name == "graphify-out" else base
project_root = graphify_out.parent if graphify_out.name == GRAPHIFY_OUT_NAME else base
graph = Path(args.graph).expanduser() if args.graph else graphify_out / "graph.json"
report = Path(args.report).expanduser() if args.report else graphify_out / "GRAPH_REPORT.md"
labels = Path(args.labels).expanduser() if args.labels else graphify_out / ".graphify_labels.json"
@@ -1204,19 +1216,38 @@ def format_node_refs(node_ids: set, node_by_id: dict, lang: str, empty_text: str
return "<br>".join(parts)
def generate_call_table_rows(nodes: list, section_edges: list, lang: str) -> str:
"""Generate call table row scaffolding for a section's nodes."""
def generate_call_table_rows(
nodes: list,
section_edges: list,
lang: str,
all_edges: list | None = None,
all_nodes: list | None = None,
) -> str:
"""Generate call table row scaffolding for a section's nodes.
The Caller/Callee columns make a claim about the whole graph ("External
entry / no inbound edge"), so they must be computed from the whole graph.
Built from ``section_edges`` alone they only see edges whose *both*
endpoints sit in this section, so a node called from anywhere else is
mislabelled an entry point. Section coverage makes that the common case
rather than a corner case: only ``max_sections`` communities are rendered,
so most callers are not in any rendered section at all.
``all_edges``/``all_nodes`` are the full graph; ``all_nodes`` also lets
out-of-section callers render as labels instead of raw node ids. Both
default to None, preserving the previous behaviour for other callers.
"""
if not nodes:
return ""
# Build source/target lookup from edges
node_by_id = {n.get("id"): n for n in nodes}
node_by_id = {n.get("id"): n for n in (all_nodes or nodes)}
callers = defaultdict(set)
callees = defaultdict(set)
for e in section_edges:
for e in (all_edges if all_edges is not None else section_edges):
src = e.get("source", "")
tgt = e.get("target", "")
if e.get("relation") in ("calls", "imports", "imports_from", "uses", "method"):
if e.get("relation") in ("calls", "imports", "imports_from", "uses", "method", "indirect_call"):
callers[tgt].add(src)
callees[src].add(tgt)
@@ -1740,7 +1771,7 @@ def write_callflow_html(
<th style="width:20%">{callee_header}</th>
<th style="width:20%">{desc_header}</th>
</tr>
{generate_call_table_rows(sec_nodes, sec_edges, lang)}
{generate_call_table_rows(sec_nodes, sec_edges, lang, edges, nodes)}
</table>
{generate_section_cards(sec, sec_nodes, sec_edges, lang)}
+166
View File
@@ -0,0 +1,166 @@
"""Cargo manifest introspection for workspace-internal crate dependencies."""
from __future__ import annotations
import os
from pathlib import Path
from typing import Any
_CONFIDENCE_EXTRACTED = "EXTRACTED"
_MAX_DISCOVERY_DEPTH = 2
def _load_toml(path: Path) -> dict[str, Any]:
try:
import tomllib # type: ignore[import-not-found]
except ModuleNotFoundError:
try:
import tomli as tomllib # type: ignore[import-not-found,no-redef]
except ModuleNotFoundError:
raise ImportError(
"--cargo on Python 3.10 needs tomli. Install with: pip install tomli"
) from None
with path.open("rb") as manifest:
return tomllib.load(manifest)
def _discover_root_manifest(root: Path) -> Path | None:
"""Find a Cargo.toml under *root* when none sits directly at the root.
A bounded-depth search rather than an unbounded walk: a Tauri app's
crate lives in src-tauri/, a polyglot repo's in rust/ or crates/, but
going arbitrarily deep risks matching a vendored or example manifest
nested well inside an unrelated dependency (#3678). Reuses the same
noise-directory pruning the AST scanner already applies (venvs, caches,
node_modules, build output) so those never get searched into. A
genuinely ambiguous layout with more than one candidate at the same
depth is resolved by sorted path order rather than guessed at; the
caller is free to point --cargo at a subdirectory directly for a repo
where that is not the right answer.
"""
from graphify.detect import _is_noise_dir
found: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
current = Path(dirpath)
depth = len(current.relative_to(root).parts)
if depth > 0 and "Cargo.toml" in filenames:
found.append(current / "Cargo.toml")
if depth >= _MAX_DISCOVERY_DEPTH:
dirnames[:] = []
continue
dirnames[:] = [d for d in dirnames if not _is_noise_dir(d, current)]
if not found:
return None
return sorted(found)[0]
def _member_manifest_paths(root: Path, root_data: dict[str, Any]) -> list[Path]:
paths: list[Path] = []
if isinstance(root_data.get("package"), dict):
paths.append(root / "Cargo.toml")
workspace = root_data.get("workspace")
members = workspace.get("members", []) if isinstance(workspace, dict) else []
if not isinstance(members, list):
return paths
for pattern in members:
if not isinstance(pattern, str):
continue
for member in sorted(root.glob(pattern)):
manifest = member / "Cargo.toml"
if manifest.is_file() and manifest not in paths:
paths.append(manifest)
return paths
def introspect_cargo(root: str | Path) -> dict[str, Any]:
"""Return crate nodes and internal dependency edges from Cargo manifests."""
root_path = Path(root).resolve()
root_manifest = root_path / "Cargo.toml"
if not root_manifest.is_file():
discovered = _discover_root_manifest(root_path)
if discovered is not None:
root_manifest = discovered
root_data = _load_toml(root_manifest)
workspace = root_data.get("workspace")
workspace_dependencies = workspace.get("dependencies", {}) if isinstance(workspace, dict) else {}
if not isinstance(workspace_dependencies, dict):
workspace_dependencies = {}
# Workspace members are resolved relative to the manifest's OWN
# directory, not necessarily root_path (#3678: the manifest can live in
# a discovered subdirectory, e.g. src-tauri/).
manifests = _member_manifest_paths(root_manifest.parent, root_data)
crates: dict[str, tuple[str, Path, dict[str, Any]]] = {}
for manifest in manifests:
data = root_data if manifest == root_manifest else _load_toml(manifest)
package = data.get("package")
if not isinstance(package, dict):
continue
name = package.get("name")
if isinstance(name, str):
crates[name] = (f"crate:{name}", manifest, data)
nodes = [
{
"id": crate_id,
"label": name,
"source_file": manifest.relative_to(root_path).as_posix(),
"source_location": "L1",
}
for name, (crate_id, manifest, _data) in sorted(crates.items())
]
edges: list[dict[str, Any]] = []
for source_name, (source_id, manifest, data) in sorted(crates.items()):
dependencies = data.get("dependencies", {})
if not isinstance(dependencies, dict):
continue
source_file = manifest.relative_to(root_path).as_posix()
for dep_key, spec in sorted(dependencies.items()):
inherited = isinstance(spec, dict) and "workspace" in spec
if inherited:
if spec["workspace"] is not True:
continue
spec = workspace_dependencies.get(dep_key)
if not isinstance(spec, dict) or not isinstance(spec.get("path"), str):
continue
# Cargo lets a dep table entry rename the crate via `package = "..."`:
# db = { path = "../storage", package = "internal-storage" }
# The key `db` is the name used in `use db::…;`; the actual crate
# published under `[package].name = "internal-storage"` is what
# `crates` is keyed by. Without honoring `package`, every renamed
# workspace-internal dep silently drops its edge (#1858).
real_name = dep_key
if isinstance(spec, dict):
pkg_override = spec.get("package")
if isinstance(pkg_override, str) and pkg_override:
real_name = pkg_override
target = crates.get(real_name)
if target is None:
continue
if inherited:
# Shared paths are relative to the workspace root, not the member.
# A matching name alone cannot prove a registry/git dep is local.
inherited_manifest = (root_path / spec["path"] / "Cargo.toml").resolve()
if inherited_manifest != target[1].resolve():
continue
edges.append(
{
"source": source_id,
"target": target[0],
"relation": "crate_depends_on",
"context": "cargo_dependency",
"weight": 1.0,
"confidence": _CONFIDENCE_EXTRACTED,
"source_file": source_file,
"source_location": "L1",
}
)
return {"nodes": nodes, "edges": edges}
+4864
View File
File diff suppressed because it is too large. Load diff
+188 -7
View File
@@ -19,11 +19,95 @@ def _suppress_output():
return contextlib.redirect_stdout(io.StringIO())
def _native_leiden(stable: nx.Graph, resolution: float) -> dict[str, int] | None:
"""Call graspologic_native.leiden() directly, bypassing graspologic's own
package import.
graspologic.partition.leiden() is a thin wrapper around exactly this
native (Rust) call. Importing the *package* — as opposed to the native
extension module it depends on — pulls in graspologic.layouts, which
imports umap, which imports pynndescent, which numba-JIT-compiles at
import time for a layout algorithm this function never calls: measured
at 7-19s of one-time import cost against a ~1s native call and a ~1.4s
full round trip (conversion + call + map-back) — see the "third update"
in GRAPHIFY_BUILD_PERF.md for the measurements this is based on.
Returns None (the caller falls through to the graspologic.partition.leiden
path, then to the networkx Louvain fallback) if graspologic_native isn't
installed, or if `stable` isn't the plain undirected, non-multigraph
input leiden actually supports — the same shape check
graspologic.partition.leiden itself makes before calling the same native
function.
"""
try:
import graspologic_native as gn
except ImportError:
return None
if stable.is_directed() or stable.is_multigraph():
return None
# graspologic_native identifies nodes by their string form; two DISTINCT
# node objects that happen to stringify the same way would silently merge
# under it (this is exactly what graspologic.partition.leiden's own
# _IdentityMapper guards against). Graphify's own node IDs are already
# unique strings by construction — extractors/resolution.py's
# _disambiguate_colliding_node_ids salts any two distinct nodes that would
# otherwise share a string id before the graph is ever built — so this is
# a defensive check on an assumption that should never actually trip, not
# an expected path. One pass over the nodes, cheaper than an
# _IdentityMapper-style dict-store-per-edge-endpoint.
id_to_node: dict[str, object] = {}
for node in stable.nodes():
key = str(node)
existing = id_to_node.get(key)
if existing is not None and existing != node:
return None # let graspologic.partition.leiden's own check handle/raise on this
id_to_node[key] = node
edges = [
(str(u), str(v), float(attrs.get("weight", 1.0)))
for u, v, attrs in stable.edges(data=True)
]
try:
old_stderr = sys.stderr
try:
sys.stderr = io.StringIO()
with _suppress_output():
_quality, native_partitions = gn.leiden(
edges=edges,
starting_communities=None,
resolution=resolution,
randomness=0.001,
iterations=1,
use_modularity=True,
seed=42,
trials=1,
)
finally:
sys.stderr = old_stderr
except Exception:
return None
partition = {
id_to_node[node_id]: community
for node_id, community in native_partitions.items()
}
next_community = max(partition.values(), default=-1) + 1
for node in stable.nodes():
if node not in partition:
partition[node] = next_community
next_community += 1
return partition
def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
"""Run community detection. Returns {node_id: community_id}.
Tries Leiden (graspologic) first — best quality.
Falls back to Louvain (built into networkx) if graspologic is not installed.
Tries Leiden (graspologic_native directly, then graspologic) first — best
quality. Falls back to Louvain (built into networkx) if neither is
installed.
resolution > 1.0 → more, smaller communities.
resolution < 1.0 → fewer, larger communities.
@@ -33,17 +117,31 @@ def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
"""
stable = nx.Graph()
stable.add_nodes_from(sorted(G.nodes(), key=str))
# Canonicalise the endpoint pair before sorting. On an undirected graph the
# (u, v) orientation each edge is yielded with comes from adjacency
# iteration, which follows CPython's per-process string-hash order - so the
# SAME edge appears as (A, B) in one run and (B, A) in the next. Sorting on
# the raw pair therefore does not canonicalise anything: the edge lands in a
# different position, `stable` is built in a different insertion order, and
# Louvain - order-sensitive even with a fixed seed - can return a different
# grouping. Measured on a 914-node graph: identical input, identical
# first-pass partition, but the cohesion-split pass produced 70 communities
# under PYTHONHASHSEED=1 and 69 under =2. Sorting the pair itself removes
# the dependency; for nx.Graph the orientation carries no meaning anyway.
edge_rows = sorted(
G.edges(data=True),
key=lambda row: (
str(row[0]),
str(row[1]),
*sorted((str(row[0]), str(row[1]))),
json.dumps(row[2], sort_keys=True, ensure_ascii=False, default=str),
),
)
for src, tgt, attrs in edge_rows:
stable.add_edge(src, tgt, **attrs)
native_result = _native_leiden(stable, resolution)
if native_result is not None:
return native_result
try:
from graspologic.partition import leiden
lsig = inspect.signature(leiden).parameters
@@ -83,6 +181,54 @@ _COHESION_SPLIT_THRESHOLD = 0.05 # re-split communities with cohesion below this
_COHESION_SPLIT_MIN_SIZE = 50 # only cohesion-split if community has at least this many nodes
def label_communities_by_hub(
G: nx.Graph, communities: dict[int, list[str]]
) -> dict[int, str]:
"""Deterministic, LLM-free community labels: name each community after its
highest-degree member — the structural hub — so a report reads ``auth`` /
``log_action`` instead of ``Community 70``. Degree is measured on the full graph
``G``; ties break by node id for run-to-run stability. A community whose members
are all absent from ``G`` falls back to ``Community {cid}``.
Used as the default (no-backend) labeler; an LLM naming pass, when configured,
overrides these with richer names.
"""
labels: dict[int, str] = {}
for cid, members in communities.items():
present = [n for n in members if n in G]
if not present:
labels[cid] = f"Community {cid}"
continue
# highest degree wins; ties broken by node id (ascending) for determinism
hub = min(present, key=lambda n: (-G.degree(n), str(n)))
name = str(G.nodes[hub].get("label") or hub).strip()
if name.endswith("()"):
name = name[:-2]
labels[cid] = name or f"Community {cid}"
return labels
def community_member_sigs(communities: dict[int, list[str]]) -> dict[int, str]:
"""Per-community membership fingerprints: ``{cid: sha256(sorted member ids)}``.
Persisted next to ``.graphify_labels.json`` so a later ``cluster-only`` can tell
which communities actually changed since labeling. A cid whose members no longer
hash the same is a different community — reusing its old (LLM) label there is the
"stale label after re-scoping" bug this guards against. Deterministic; independent
of cid index, node order, and machine.
"""
import hashlib
sigs: dict[int, str] = {}
for cid, members in communities.items():
h = hashlib.sha256()
for nid in sorted(str(n) for n in members):
h.update(nid.encode("utf-8", "replace"))
h.update(b"\x00")
sigs[cid] = h.hexdigest()[:16]
return sigs
def cluster(
G: nx.Graph,
resolution: float = 1.0,
@@ -101,8 +247,9 @@ def cluster(
<1.0 = fewer larger communities. Default 1.0.
exclude_hubs_percentile: if set (0-100), nodes whose degree exceeds this
percentile are excluded from partitioning and reattached to their
majority-vote neighbour community afterwards. Useful for staging/utility
super-hubs that inflate god-node rankings (#919).
majority-vote neighbour community afterwards. Nodes whose only
neighbours are excluded hubs follow them, by the same vote. Useful for
staging/utility super-hubs that inflate god-node rankings (#919).
"""
if G.number_of_nodes() == 0:
return {}
@@ -126,6 +273,21 @@ def cluster(
excluded = hub_nodes
isolates = [n for n in G.nodes() if G.degree(n) == 0 and n not in excluded]
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0 and n not in excluded]
# A node whose only neighbours are excluded hubs is isolated in the
# partitioned subgraph purely because of the exclusion. Hold it out of the
# partition and place it with its hub(s) below, instead of letting it come
# back as a singleton cut off from the only node it connects to.
stranded: list[str] = []
if hub_nodes:
# A self-loop is not a neighbour: judge a node by its other neighbours.
stranded = [
n for n in connected_nodes
if (nbs := [nb for nb in G.neighbors(n) if nb != n])
and all(nb in hub_nodes for nb in nbs)
]
if stranded:
_stranded = set(stranded)
connected_nodes = [n for n in connected_nodes if n not in _stranded]
connected = G.subgraph(connected_nodes)
raw: dict[int, list[str]] = {}
@@ -157,6 +319,18 @@ def cluster(
raw[next_cid] = [hub]
node_community[hub] = next_cid
next_cid += 1
# Every neighbour of a stranded node is a hub, and every hub is placed
# by now, so the same majority vote always has a winner.
for node in sorted(stranded, key=str):
votes = {}
for nb in G.neighbors(node):
if nb == node:
continue
cid = node_community[nb]
votes[cid] = votes.get(cid, 0) + 1
best = min(votes, key=lambda c: (-votes[c], c))
raw[best].append(node)
node_community[node] = best
# Split oversized communities
max_size = max(_MIN_SPLIT_SIZE, int(G.number_of_nodes() * _MAX_COMMUNITY_FRACTION))
@@ -212,7 +386,14 @@ def cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
if n <= 1:
return 1.0
subgraph = G.subgraph(community_nodes)
actual = subgraph.number_of_edges()
# Exclude self-loops. ``build_from_json`` deliberately keeps recursive
# ``calls`` self-edges ("real program structure rather than
# import-resolution artifacts"), but ``possible`` below counts distinct
# node PAIRS only, so a self-loop adds to the numerator without adding to
# the denominator and pushes the ratio past 1.0 -- a two-node community
# holding one recursive function scores 2.0. Drop them so numerator and
# denominator measure the same thing.
actual = subgraph.number_of_edges() - nx.number_of_selfloops(subgraph)
possible = n * (n - 1) / 2
return actual / possible if possible > 0 else 0.0
+247
View File
@@ -0,0 +1,247 @@
"""Finish member calls that cross a repository boundary in a merged graph (#3152).
A single-repo build can only bind ``obj.method()`` when the receiver's type is
declared in that same build. When the type lives in another repository the
resolver holds the receiver type and drops the call anyway, so ``graph.json`` —
the only artifact ``merge-graphs`` and ``global add`` consume — records nothing,
and no merge-time pass can recover what was never written down. A two-repo call
graph was therefore missing exactly the edges that make it a call graph: eight
edges when the code sits in one corpus, seven after merging the same code from
two repos.
The resolvers now park those calls on the caller node as
``metadata.unresolved_calls`` entries (names only, no node ids — see
``_park_unresolved_member_call``). This pass reads them back after the graphs are
composed and emits the ``calls`` edge when the receiver's type resolves to
exactly one declaration in another repo, keeping the single-definition guard the
single-repo resolvers use: an ambiguous name still fabricates nothing.
Edges only, no node merging or renaming, so the pass composes with the prefixing
and pruning already in place. Every edge it adds is tagged, and it clears its own
previous output before recomputing: ``global add`` composes one repo at a time
and revisits the same pairs on every add, and recomputing from the parked entries
keeps the result identical whether three repos arrived together or one at a time.
"""
from __future__ import annotations
import os
from collections import defaultdict
from typing import TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover - typing only
import networkx as nx
CROSS_REPO_CALL_MARKER = "_cross_repo_call"
UNRESOLVED_CALLS_KEY = "unresolved_calls"
# A parked entry names the language it was written in, and the declaration that
# answers it must be written in the same one: without this a Java `Greeter` binds
# just as happily to a Python class of the same name in another repo. Extend this
# map when another extractor starts parking calls.
_LANG_SUFFIXES: dict[str, frozenset[str]] = {
"cpp": frozenset({".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx", ".h", ".cu", ".cuh"}),
"csharp": frozenset({".cs"}),
"java": frozenset({".java"}),
"swift": frozenset({".swift"}),
}
# A declaration owns its members through a `method` edge, except in C++, where an
# in-class declaration (`void bar();` in a header) is modelled as a field and
# carries `defines` instead. `method` wins when both name the same member.
_MEMBER_RELATIONS = ("defines", "method")
def _key(label: object) -> str:
"""Normalize a node label or a parked name to its bare identifier.
Type labels are plain (``Greeter``) while method labels carry the extractor's
decoration (``.greet()``). Case is preserved: every language that parks calls
here is case-sensitive, and folding case would let `greeter` answer for
`Greeter`.
"""
return str(label or "").strip().removeprefix(".").removesuffix("()")
def _suffix(source_file: object) -> str:
return os.path.splitext(str(source_file or ""))[1].lower()
def _parked_entries(data: dict) -> list[dict]:
metadata = data.get("metadata")
if not isinstance(metadata, dict):
return []
parked = metadata.get(UNRESOLVED_CALLS_KEY)
if not isinstance(parked, list):
return []
return [entry for entry in parked if isinstance(entry, dict)]
def _drop_previous_output(merged: "nx.Graph") -> None:
"""Clear the edges this pass added on an earlier run.
Recompute-from-scratch is what makes an incremental ``global add`` agree with
a single ``merge-graphs`` of the same inputs, and it is also how a repo whose
types moved stops answering for calls it no longer owns.
"""
stale = [(u, v) for u, v, data in merged.edges(data=True)
if data.get(CROSS_REPO_CALL_MARKER)]
merged.remove_edges_from(stale)
def _index_declarations(merged: "nx.Graph") -> tuple[dict[str, list[str]], set[str]]:
"""Index sourced type declarations by bare name. Returns (index, id set)."""
by_name: dict[str, list[str]] = defaultdict(list)
type_ids: set[str] = set()
for node, data in merged.nodes(data=True):
if not data.get("_callable_class") or not data.get("source_file"):
continue
if not data.get("repo"):
continue
name = _key(data.get("label"))
if not name:
continue
by_name[name].append(node)
type_ids.add(node)
return by_name, type_ids
def _index_members(
merged: "nx.Graph", type_ids: set[str]
) -> dict[str, dict[tuple[str, str], list[str]]]:
"""Index each declaration's members by relation, then by name.
The merged graph is undirected, and a ``method`` edge carries no reliable
direction once composed, so the owner is identified as the endpoint that is a
type declaration. A nested declaration puts a type on both ends; that pair is
skipped rather than guessed at.
Kept per relation rather than pooled: ``defines`` covers fields as well as
C++'s in-class member declarations, so only a language that needs it may look
there, and only when no ``method`` of that name exists.
"""
by_relation: dict[str, dict[tuple[str, str], list[str]]] = {
relation: defaultdict(list) for relation in _MEMBER_RELATIONS
}
for u, v, data in merged.edges(data=True):
relation = data.get("relation")
if relation not in by_relation:
continue
if u in type_ids and v not in type_ids:
owner, member = u, v
elif v in type_ids and u not in type_ids:
owner, member = v, u
else:
continue
name = _key(merged.nodes[member].get("label"))
if name:
by_relation[relation][(owner, name)].append(member)
return by_relation
def _member_relations(lang: str) -> tuple[str, ...]:
"""Which owner→member relations may answer a call parked by ``lang``.
Only C++ models an in-class declaration (``void bar();`` in a header) as a
field, so only a C++ entry may fall back to ``defines``; for every other
language a ``defines`` target is a field, and a field cannot answer a call.
"""
return ("method", "defines") if lang == "cpp" else ("method",)
def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
"""Emit `calls` edges for parked member calls another repo answers.
Returns the number of edges added. Idempotent: the pass drops its own earlier
output first, so re-merging or adding a repo twice cannot duplicate an edge.
"""
_drop_previous_output(merged)
parked_nodes = [(node, data) for node, data in merged.nodes(data=True)
if _parked_entries(data)]
if not parked_nodes:
return 0
by_name, type_ids = _index_declarations(merged)
if not by_name:
return 0
members_by_relation = _index_members(merged, type_ids)
# C# parked calls need the same namespace/using visibility check as C# type
# references. Without it, an unresolved third-party receiver such as
# `FluentValidation.IValidator` can bind to an unrelated `IValidator` that
# happens to be declared in one merged repository (#3360). Build this only
# when needed; the other parked languages use their existing suffix guard.
csharp_resolver = None
if any(
str(entry.get("lang") or "") == "csharp"
for _, data in parked_nodes
for entry in _parked_entries(data)
):
from graphify.extractors.csharp import CsharpNameResolver
resolver_nodes = [dict(data, id=node) for node, data in merged.nodes(data=True)]
resolver_edges = [
dict(data, source=source, target=target)
for source, target, data in merged.edges(data=True)
]
csharp_resolver = CsharpNameResolver(resolver_nodes, resolver_edges)
added = 0
for caller, caller_data in parked_nodes:
caller_repo = caller_data.get("repo")
if not caller_repo:
# Without a repo tag "another repo" has no meaning, and this pass
# deliberately never re-decides a call inside one repo.
continue
for entry in _parked_entries(caller_data):
lang = str(entry.get("lang") or "")
suffixes = _LANG_SUFFIXES.get(lang)
receiver_type = _key(entry.get("receiver_type"))
callee = _key(entry.get("callee"))
if not suffixes or not receiver_type or not callee:
continue
candidates = [
node for node in by_name.get(receiver_type, [])
if merged.nodes[node].get("repo") != caller_repo
and _suffix(merged.nodes[node].get("source_file")) in suffixes
]
if len(candidates) != 1:
# The same guard the single-repo resolvers apply: two repos
# declaring the same name is an ambiguity, not a hit.
continue
if lang == "csharp":
# Reuse the extractor's authoritative C# visibility rules. A
# candidate is valid only when the caller's namespace, using,
# or alias resolves this exact receiver name to that node.
resolved, _decisive = csharp_resolver.resolve_type_name(
receiver_type,
dict(caller_data, id=caller),
str(caller_data.get("source_file") or ""),
)
if resolved != candidates[0]:
continue
targets: list[str] = []
for relation in _member_relations(lang):
targets = members_by_relation[relation].get((candidates[0], callee), [])
if targets:
break
if len(targets) != 1:
continue
target = targets[0]
if target == caller or merged.has_edge(caller, target):
continue
merged.add_edge(
caller,
target,
relation="calls",
context="cross_repo",
confidence="INFERRED",
confidence_score=0.8,
source_file=str(caller_data.get("source_file") or ""),
source_location=entry.get("line"),
weight=1.0,
_src=caller,
_tgt=target,
**{CROSS_REPO_CALL_MARKER: True},
)
added += 1
return added
+75
View File
@@ -0,0 +1,75 @@
"""Join the same declared type across repositories in a merged graph (#3007).
`merge-graphs` prefixes every node id with its repo tag, so a contract type that
two services both declare arrives as two unconnected nodes. In a message-bus
codebase that is exactly where the interesting hop lives: the producer references
`SyncProductUpsertToSearchEvent` in one repo, the consumer implements
`IConsumer<SyncProductUpsertToSearchEvent>` in the other, and the merged graph has
no way to get from one to the other even though both sides name the same type.
This pass adds a `same_type_as` edge between type declarations that share both a
namespace and a name and come from different repos. Requiring the namespace keeps
it to types that were declared identically rather than two classes that merely
picked the same short name: on a pair of .NET services with 1440 and 262 declared
types, the namespace-plus-name match produced 7 pairs, all of them the shared
`EventManager.Models.*Event` contracts, and nothing else.
Edges only, no node merging. Two repos can hold copies of a contract that have
drifted, and collapsing them would hide that; a link lets a traversal cross while
each side keeps its own members, file and provenance.
"""
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover - typing only
import networkx as nx
SHARED_TYPE_RELATION = "same_type_as"
def link_shared_type_declarations(merged: "nx.Graph") -> int:
"""Link identically declared types across repos. Returns the edge count added.
A candidate node is a sourced type declaration carrying a namespace and a
repo tag. A group qualifies when its members span at least two repos, and
every pair inside a qualifying group gets one edge. Groups are the handful of
types two repos genuinely share, so the pairwise walk stays small.
"""
by_declaration: dict[tuple[str, str], list[str]] = defaultdict(list)
for node, data in merged.nodes(data=True):
if not data.get("_callable_class") or not data.get("source_file"):
continue
namespace = str((data.get("metadata") or {}).get("namespace") or "")
label = str(data.get("label") or "")
if not namespace or not label or not data.get("repo"):
continue
by_declaration[(namespace, label)].append(node)
added = 0
for (namespace, label), nodes in by_declaration.items():
if len(nodes) < 2:
continue
if len({merged.nodes[n].get("repo") for n in nodes}) < 2:
continue
for index, left in enumerate(nodes):
for right in nodes[index + 1:]:
if merged.nodes[left].get("repo") == merged.nodes[right].get("repo"):
continue
if merged.has_edge(left, right):
continue
merged.add_edge(
left,
right,
relation=SHARED_TYPE_RELATION,
context="cross_repo",
confidence="INFERRED",
confidence_score=0.9,
source_file=str(merged.nodes[left].get("source_file") or ""),
weight=1.0,
_src=left,
_tgt=right,
)
added += 1
return added
+154
View File
@@ -0,0 +1,154 @@
"""Member-level interface dispatch for C# (#3003).
A C# call through a constructor-injected dependency lands on the interface's
method node, because that is what the call site names: `_report.Build()` where
`_report` is an `IReport` resolves to `IReport.Build()`. The implementing
`Report.Build()` is a separate node, and nothing joins the two, so a directed
walk stops at the interface and every chain through an injected dependency is
cut at that point. On a Scrutor-scanned .NET service where every dependency is
an interface, that is most chains.
This resolver runs after all files are extracted, with the merged corpus
available, and links the interface's method to the implementing method:
ireport_ireport_build --dispatches_to--> report_report_build
It only fires when the interface has exactly one implementer and that
implementer owns exactly one method of the same name, the single-owner guard
`resolve_pascal_inherited_calls` and `resolve_ruby_member_calls` already use.
Walking `implements` to the one type that can serve the call mirrors what the
runtime does; guessing among several implementers would not, so anything
ambiguous is left alone.
The join is per method rather than per call site, so one edge reconnects every
call that reaches the interface method. Confidence is `INFERRED`: the target is
forced once there is a single implementer, but the source text never names it.
"""
from __future__ import annotations
_CSHARP_SUFFIXES = (".cs",)
DISPATCH_RELATION = "dispatches_to"
def _is_csharp(node: dict | None) -> bool:
"""True when the node is a declaration that lives in a C# file.
Every end of a dispatch pair has to pass this. `implements` is resolved by
name, so in a mixed corpus a Java class declaring `implements IReport` binds
to a C# `IReport` when that is the only node with the name, and linking a C#
interface member to a Java method would be a wrong edge rather than a missing
one. A non-C# implementation of a C# interface, from VB or a Razor component,
is a real thing, but claiming it needs its own extractor evidence.
"""
if not node:
return False
source_file = node.get("source_file")
return bool(source_file) and str(source_file).endswith(_CSHARP_SUFFIXES)
def _method_label(node: dict) -> str:
"""Return a method node's bare name, for matching.
Case is kept: C# is case sensitive, and an implementing member must spell the
interface member exactly, so folding case could only pair a declaration with
a member that does not implement it.
The name is cut at the first parenthesis rather than by stripping a trailing
`()`. Today the C# extractor labels every method `.Name()`, so the two are the
same, but the pair match is keyed on this string and a label that ever carried
a signature would silently stop matching instead of failing visibly.
"""
label = str(node.get("label", "")).strip().removeprefix(".")
return label.split("(", 1)[0]
def resolve_csharp_interface_dispatch(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link each single-implementer interface method to its implementation.
Purely additive: the existing call edge to the interface method is left in
place, since the call site really does name the interface.
"""
if not any(
str(result.get("source_file", "")).endswith(_CSHARP_SUFFIXES)
for result in per_file
if isinstance(result, dict)
) and not any(
str(n.get("source_file", "")).endswith(_CSHARP_SUFFIXES) for n in all_nodes
):
return
node_by_id = {n.get("id"): n for n in all_nodes}
implementers: dict[str, set[str]] = {}
methods_of: dict[str, dict[str, set[str]]] = {}
for e in all_edges:
rel = e.get("relation")
if rel == "implements":
implementers.setdefault(e.get("target"), set()).add(e.get("source"))
elif rel == "method":
owner, method_nid = e.get("source"), e.get("target")
mnode = node_by_id.get(method_nid)
if mnode is None or not _is_csharp(mnode):
continue
name = _method_label(mnode)
if name:
# A set, so the same method arriving on two `method` edges cannot
# look like two same-named methods and trip the guard below.
methods_of.setdefault(owner, {}).setdefault(name, set()).add(method_nid)
if not implementers or not methods_of:
return
# Scoped to this relation: another edge between the two members, whatever it
# is, says nothing about whether the dispatch link is already there.
existing_pairs = {
(e.get("source"), e.get("target"))
for e in all_edges
if e.get("relation") == DISPATCH_RELATION
}
new_edges: list[dict] = []
for interface_nid, impls in implementers.items():
if len(impls) != 1:
continue
impl_nid = next(iter(impls))
interface_node = node_by_id.get(interface_nid)
impl_node = node_by_id.get(impl_nid)
if interface_node is None or impl_node is None:
continue
# Both ends must be C# declarations. A sourceless stub minted for a
# dangling reference carries no members worth dispatching to, and a
# cross-language pair is a name collision rather than an implementation.
if not _is_csharp(interface_node) or not _is_csharp(impl_node):
continue
impl_methods = methods_of.get(impl_nid, {})
for name, declared in methods_of.get(interface_nid, {}).items():
if len(declared) != 1:
continue
candidates = impl_methods.get(name, set())
if len(candidates) != 1:
continue
source = next(iter(declared))
target = next(iter(candidates))
if source == target or (source, target) in existing_pairs:
continue
existing_pairs.add((source, target))
new_edges.append({
"source": source,
"target": target,
"relation": DISPATCH_RELATION,
"context": "call",
"confidence": "INFERRED",
"confidence_score": 0.9,
"source_file": str(impl_node.get("source_file", "")),
"source_location": impl_node.get("source_location"),
"weight": 1.0,
})
all_edges.extend(new_edges)
+871 -44
View File
File diff suppressed because it is too large. Load diff
+1684 -270
View File
File diff suppressed because it is too large. Load diff
+35 -3
View File
@@ -161,13 +161,26 @@ def diagnose_extraction(
max_examples: int = 5,
extract_path: str | Path | None = None,
) -> dict[str, Any]:
"""Summarize same-endpoint edge-collapse risk for one JSON graph/extraction dict."""
"""Summarize graph-integrity risks for one JSON graph/extraction dict.
Missing ``ref_*`` targets are expected external references produced for
dependencies outside the scanned corpus. They are counted separately from
actionable internal dangling endpoints.
"""
from graphify.build import build_from_json
node_ids = _node_ids(extraction)
raw_edges = _edge_list(extraction)
canonical_edges = [_canonical_edge(edge) for edge in raw_edges]
# Code-typed semantic nodes the extractor could not verify against the source
# it read (#1949): likely-inferred (or hallucinated) symbols surfaced from a
# document. Count them so the flag on graph.json nodes is actually surfaced.
unverified_node_count = sum(
1 for n in extraction.get("nodes", [])
if isinstance(n, dict) and n.get("verification") == "unverified"
)
exact_counts: Counter[str] = Counter(_exact_signature(edge) for edge in raw_edges)
directed_pairs: Counter[tuple[str, str]] = Counter()
undirected_pairs: Counter[tuple[str, str]] = Counter()
@@ -176,6 +189,7 @@ def diagnose_extraction(
non_object_edges = 0
missing_endpoint_edges = 0
dangling_endpoint_edges = 0
external_reference_edges = 0
self_loop_edges = 0
valid_candidate_edges = 0
@@ -189,7 +203,15 @@ def diagnose_extraction(
missing_endpoint_edges += 1
continue
if source not in node_ids or target not in node_ids:
dangling_endpoint_edges += 1
# Two intentionally-distinct populations of "external": a `ref_`
# target here is a JSON/config out-of-corpus reference ($ref /
# extends / references), whereas import-family externals are minted
# as declared `external=True` stub nodes at build time (#2873) and
# therefore never reach this branch. Don't try to unify them.
if source in node_ids and target.startswith("ref_"):
external_reference_edges += 1
else:
dangling_endpoint_edges += 1
continue
if source == target:
self_loop_edges += 1
@@ -239,10 +261,12 @@ def diagnose_extraction(
return {
"node_count": len(node_ids),
"unverified_node_count": unverified_node_count,
"raw_edge_count": len(raw_edges),
"non_object_edges": non_object_edges,
"missing_endpoint_edges": missing_endpoint_edges,
"dangling_endpoint_edges": dangling_endpoint_edges,
"external_reference_edges": external_reference_edges,
"self_loop_edges": self_loop_edges,
"valid_candidate_edges": valid_candidate_edges,
"exact_duplicate_edges": _count_extra(exact_counts),
@@ -274,7 +298,13 @@ def _read_json_file(path: str | Path) -> dict[str, Any]:
json_path = Path(path)
check_graph_file_size_cap(json_path)
data = json.loads(json_path.read_text(encoding="utf-8"))
try:
data = json.loads(json_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
raise RuntimeError(
f"Cannot parse {json_path}: {exc}. "
"The file may be corrupted — re-run 'graphify extract'."
) from exc
if not isinstance(data, dict):
raise ValueError("diagnostic input must be a JSON object")
return data
@@ -338,10 +368,12 @@ def format_diagnostic_report(summary: dict[str, Any]) -> str:
"input_stage: provided JSON (normal graph.json is post-build)",
f"effective_directed: {summary.get('effective_directed', '<direct-call>')}",
f"nodes: {summary['node_count']}",
f"unverified_code_nodes: {summary.get('unverified_node_count', 0)}",
f"raw_edges: {summary['raw_edge_count']}",
f"valid_candidate_edges: {summary['valid_candidate_edges']}",
f"missing_endpoint_edges: {summary['missing_endpoint_edges']}",
f"dangling_endpoint_edges: {summary['dangling_endpoint_edges']}",
f"external_reference_edges: {summary.get('external_reference_edges', 0)}",
f"self_loop_edges: {summary['self_loop_edges']}",
f"exact_duplicate_edges: {summary['exact_duplicate_edges']}",
f"directed_unique_endpoint_pairs: {summary['directed_unique_endpoint_pairs']}",
+606 -652
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
"""exporters package."""
+14
View File
@@ -0,0 +1,14 @@
"""Shared constants/helpers for the graphify exporters package.
Symbols used by more than one exporter live here so each exporter module can be
split out of graphify/export.py without a circular import (export.py and the
per-format modules both import from here, never from each other).
"""
from __future__ import annotations
# Categorical palette for community coloring, shared by the HTML, SVG, and
# Obsidian exporters. Moved verbatim from graphify/export.py.
COMMUNITY_COLORS = [
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
"#EDC948", "#B07AA1", "#FF9DA7", "#9C755F", "#BAB0AC",
]
+210
View File
@@ -0,0 +1,210 @@
"""graphdb — moved verbatim from graphify/export.py."""
from __future__ import annotations
from graphify.analyze import _node_community_map
import networkx as nx
import re
def _distinct_node_labels(G: nx.Graph) -> list[str]:
"""Distinct Cypher labels the node-upsert loop will write, sorted.
The label is derived exactly as the push loops derive it, so the indexes
created up front cover every label the MERGE statements will match against.
"""
labels = set()
for _, data in G.nodes(data=True):
label = data.get("file_type", "Entity").capitalize()
labels.add(re.sub(r"[^A-Za-z0-9_]", "", label) or "Entity")
return sorted(labels)
def push_to_neo4j(
G: nx.Graph,
uri: str,
user: str,
password: str,
communities: dict[int, list[str]] | None = None,
) -> dict[str, int]:
"""Push graph directly to a running Neo4j instance via the Python driver.
Requires: pip install neo4j
Uses MERGE so re-running is safe - nodes and edges are upserted, not duplicated.
Returns a dict with counts of nodes and edges pushed.
"""
try:
from neo4j import GraphDatabase
except ImportError as e:
raise ImportError(
"neo4j driver not installed. Run: pip install neo4j"
) from e
node_community = _node_community_map(communities) if communities else {}
def _safe_rel(relation: str) -> str:
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
def _safe_label(label: str) -> str:
"""Sanitize a Neo4j node label to prevent Cypher injection."""
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
return sanitized if sanitized else "Entity"
driver = GraphDatabase.driver(uri, auth=(user, password))
nodes_pushed = 0
edges_pushed = 0
with driver.session() as session:
# Index (label, id) before any upsert, for the same reason as the
# FalkorDB path: MERGE matches on (label, id), so an unindexed match
# pattern scans the whole label and the push degrades to O(n^2)
# (#3804). IF NOT EXISTS keeps this idempotent across re-pushes.
for label in _distinct_node_labels(G):
try:
session.run(f"CREATE INDEX IF NOT EXISTS FOR (n:{label}) ON (n.id)")
except Exception:
pass
for node_id, data in G.nodes(data=True):
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
props["id"] = node_id
cid = node_community.get(node_id)
if cid is not None:
props["community"] = cid
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
session.run(
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
id=node_id,
props=props,
)
nodes_pushed += 1
for u, v, data in G.edges(data=True):
rel = _safe_rel(data.get("relation", "RELATED_TO"))
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
session.run(
f"MATCH (a {{id: $src}}), (b {{id: $tgt}}) "
f"MERGE (a)-[r:{rel}]->(b) SET r += $props",
src=u,
tgt=v,
props=props,
)
edges_pushed += 1
driver.close()
return {"nodes": nodes_pushed, "edges": edges_pushed}
def push_to_falkordb(
G: nx.Graph,
uri: str,
user: str | None = None,
password: str | None = None,
communities: dict[int, list[str]] | None = None,
graph_name: str = "graphify",
) -> dict[str, int]:
"""Push graph directly to a running FalkorDB instance via the Python SDK.
Requires: pip install falkordb
FalkorDB is OpenCypher-compatible, so the MERGE/SET upsert queries are
identical to push_to_neo4j. Differences from the Neo4j path:
- connects with FalkorDB(host, port, username, password) instead of a bolt
driver; only the host/port are read from the URI, so the scheme is
informational - "falkordb://localhost:6379", "redis://localhost:6379"
and a bare "localhost:6379" are all equivalent (default port 6379).
- a named graph is selected via db.select_graph(graph_name) (default
"graphify"); FalkorDB keys each graph by name in the same instance.
- queries run via graph.query(cypher, params) - there is no session object.
- auth is optional (FalkorDB runs without credentials by default), so user
and password may be None.
- no APOC: the Neo4j path does not use APOC either, so nothing to port.
Uses MERGE so re-running is safe - nodes and edges are upserted, not
duplicated. Returns a dict with counts of nodes and edges pushed.
"""
try:
from falkordb import FalkorDB
except ImportError as e:
raise ImportError(
"falkordb SDK not installed. Run: pip install falkordb"
) from e
from urllib.parse import urlparse
node_community = _node_community_map(communities) if communities else {}
def _safe_rel(relation: str) -> str:
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
def _safe_label(label: str) -> str:
"""Sanitize a FalkorDB node label to prevent Cypher injection."""
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
return sanitized if sanitized else "Entity"
parsed = urlparse(uri if "://" in uri else f"redis://{uri}")
# FalkorDB auth is optional. Only send credentials when a password is
# provided; otherwise connect anonymously and ignore any bolt-style default
# username (e.g. Neo4j's "neo4j"), which FalkorDB rejects as an unknown ACL
# user. Credentials embedded in the URI take precedence over the args.
connect_user = parsed.username or (user if password else None)
connect_password = parsed.password or (password or None)
db = FalkorDB(
host=parsed.hostname or "localhost",
port=parsed.port or 6379,
username=connect_user,
password=connect_password,
)
graph = db.select_graph(graph_name)
nodes_pushed = 0
edges_pushed = 0
# Index (label, id) before any upsert. The MERGE below matches on
# (label, id), so with no index FalkorDB scans every existing node carrying
# that label to decide whether the node is new: each upsert costs
# O(nodes with that label) and the whole push degrades to O(n^2) (#3804).
# Measured on a 167k-node / 209k-edge graph, adding these indexes first
# restored the throughput the push started at. FalkorDB's CREATE INDEX has
# no IF NOT EXISTS, so a re-run against an already-indexed graph raises —
# tolerate that rather than failing an otherwise valid push.
for label in _distinct_node_labels(G):
try:
graph.query(f"CREATE INDEX FOR (n:{label}) ON (n.id)")
except Exception:
pass
for node_id, data in G.nodes(data=True):
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
props["id"] = node_id
cid = node_community.get(node_id)
if cid is not None:
props["community"] = cid
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
graph.query(
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
{"id": node_id, "props": props},
)
nodes_pushed += 1
for u, v, data in G.edges(data=True):
rel = _safe_rel(data.get("relation", "RELATED_TO"))
props = {
k: v for k, v in data.items()
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
}
graph.query(
f"MATCH (a {{id: $src}}), (b {{id: $tgt}}) "
f"MERGE (a)-[r:{rel}]->(b) SET r += $props",
{"src": u, "tgt": v, "props": props},
)
edges_pushed += 1
return {"nodes": nodes_pushed, "edges": edges_pushed}
+663
View File
@@ -0,0 +1,663 @@
"""html — moved verbatim from graphify/export.py."""
from __future__ import annotations
from graphify.exporters.base import COMMUNITY_COLORS # noqa: E402,F401
from pathlib import Path
import html as _html
from graphify.analyze import _node_community_map
from graphify.paths import write_text_atomic
import json
import networkx as nx
from graphify.security import sanitize_label
MAX_NODES_FOR_VIZ = 5_000
_HTML_STALE_MARKER = ".graph.html.stale"
def _viz_node_limit() -> int:
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
"""
import os
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
if raw is None or not raw.strip():
return MAX_NODES_FOR_VIZ
try:
return int(raw)
except ValueError:
return MAX_NODES_FOR_VIZ
def _html_styles() -> str:
return """<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #0f0f1a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; display: flex; height: 100vh; overflow: hidden; }
#graph { flex: 1; }
#sidebar { width: 280px; background: #1a1a2e; border-left: 1px solid #2a2a4e; display: flex; flex-direction: column; overflow: hidden; }
#search-wrap { padding: 12px; border-bottom: 1px solid #2a2a4e; }
#search { width: 100%; background: #0f0f1a; border: 1px solid #3a3a5e; color: #e0e0e0; padding: 7px 10px; border-radius: 6px; font-size: 13px; outline: none; }
#search:focus { border-color: #4E79A7; }
#search-results { max-height: 140px; overflow-y: auto; padding: 4px 12px; border-bottom: 1px solid #2a2a4e; display: none; }
.search-item { padding: 4px 6px; cursor: pointer; border-radius: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.search-item:hover { background: #2a2a4e; }
#info-panel { padding: 14px; border-bottom: 1px solid #2a2a4e; min-height: 140px; }
#info-panel h3 { font-size: 13px; color: #aaa; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.05em; }
#info-content { font-size: 13px; color: #ccc; line-height: 1.6; }
#info-content .field { margin-bottom: 5px; }
#info-content .field b { color: #e0e0e0; }
#info-content .empty { color: #555; font-style: italic; }
.neighbor-link { display: block; padding: 2px 6px; margin: 2px 0; border-radius: 3px; cursor: pointer; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 3px solid #333; }
.neighbor-link:hover { background: #2a2a4e; }
#neighbors-list { max-height: 160px; overflow-y: auto; margin-top: 4px; }
#legend-wrap { flex: 1; overflow-y: auto; padding: 12px; }
#legend-wrap h3 { font-size: 13px; color: #aaa; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; }
.legend-item { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; font-size: 12px; }
.legend-item:hover { background: #2a2a4e; padding-left: 4px; }
.legend-item.dimmed { opacity: 0.35; }
.legend-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.legend-count { color: #666; font-size: 11px; }
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
#legend-controls { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; padding: 4px 0; }
#legend-controls label { display: flex; align-items: center; gap: 6px; cursor: pointer; font-size: 12px; color: #aaa; user-select: none; }
#legend-controls label:hover { color: #e0e0e0; }
.legend-cb, #select-all-cb { appearance: none; -webkit-appearance: none; width: 14px; height: 14px; border: 1.5px solid #3a3a5e; border-radius: 3px; background: #0f0f1a; cursor: pointer; position: relative; flex-shrink: 0; }
.legend-cb:checked, #select-all-cb:checked { background: #4E79A7; border-color: #4E79A7; }
.legend-cb:checked::after, #select-all-cb:checked::after { content: ''; position: absolute; left: 3.5px; top: 1px; width: 4px; height: 7px; border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg); }
#select-all-cb:indeterminate { background: #4E79A7; border-color: #4E79A7; }
#select-all-cb:indeterminate::after { content: ''; position: absolute; left: 2px; top: 5px; width: 8px; height: 2px; background: #fff; border: none; transform: none; }
</style>"""
def _hyperedge_script(hyperedges_json: str) -> str:
return f"""<script>
// Render hyperedges as shaded regions
const hyperedges = {hyperedges_json};
// afterDrawing passes ctx already transformed to network coordinate space.
// Draw node positions raw — no manual pan/zoom/DPR math needed.
// Andrew's monotone chain. Returns the hull in counter-clockwise order, which
// is what the perimeter must be traced in. Collinear and duplicate points
// collapse to the extremes, so degenerate member sets render as a segment
// rather than a zero-area crossed path.
function convexHull(pts) {{
const p = pts.slice().sort((a, b) => (a.x - b.x) || (a.y - b.y));
if (p.length < 3) return p;
const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const build = seq => {{
const out = [];
for (const q of seq) {{
while (out.length >= 2 && cross(out[out.length - 2], out[out.length - 1], q) <= 0) out.pop();
out.push(q);
}}
out.pop();
return out;
}};
const hull = build(p).concat(build(p.slice().reverse()));
return hull.length >= 3 ? hull : p;
}}
network.on('afterDrawing', function(ctx) {{
hyperedges.forEach(h => {{
const positions = h.nodes
.map(nid => network.getPositions([nid])[nid])
.filter(p => p !== undefined);
if (positions.length < 2) return;
ctx.save();
ctx.globalAlpha = 0.12;
ctx.fillStyle = '#6366f1';
ctx.strokeStyle = '#6366f1';
ctx.lineWidth = 2;
ctx.beginPath();
// Centroid and expanded hull in network coordinates.
// The perimeter must follow hull order, not h.nodes order: tracing the
// raw member order self-intersects whenever the layout does not happen
// to place members in angular order, filling as crossed wedges.
const cx = positions.reduce((s, p) => s + p.x, 0) / positions.length;
const cy = positions.reduce((s, p) => s + p.y, 0) / positions.length;
const hull = convexHull(positions);
const expanded = hull.map(p => ({{
x: cx + (p.x - cx) * 1.15,
y: cy + (p.y - cy) * 1.15
}}));
ctx.moveTo(expanded[0].x, expanded[0].y);
expanded.slice(1).forEach(p => ctx.lineTo(p.x, p.y));
ctx.closePath();
ctx.fill();
ctx.globalAlpha = 0.4;
ctx.stroke();
// Label
ctx.globalAlpha = 0.8;
ctx.fillStyle = '#4f46e5';
ctx.font = 'bold 11px sans-serif';
ctx.textAlign = 'center';
ctx.fillText(h.label, cx, cy - 5);
ctx.restore();
}});
}});
</script>"""
def _html_script(nodes_json: str, edges_json: str, legend_json: str) -> str:
return f"""<script>
const RAW_NODES = {nodes_json};
const RAW_EDGES = {edges_json};
const LEGEND = {legend_json};
// HTML-escape helper — prevents XSS when injecting graph data into innerHTML
function esc(s) {{
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}}
// Build vis datasets
const nodesDS = new vis.DataSet(RAW_NODES.map((n, i) => ({{
id: n.id, label: n.label, color: n.color, size: n.size,
font: n.font, title: n.title,
// Fermat/golden-angle spiral seed positions (#3699): spreading nodes out
// before physics runs keeps avoidOverlap from computing near-zero-distance
// repulsion that blows the BarnesHut recursion into a stack overflow on large
// graphs. `i` is the map index — physics still settles small graphs identically.
x: 30 * Math.sqrt(i) * Math.cos(i * 2.4),
y: 30 * Math.sqrt(i) * Math.sin(i * 2.4),
community: n.community, community_name: n.community_name,
source_file: n.source_file, file_type: n.file_type, degree: n.degree,
member_count: n.member_count,
}})));
const edgesDS = new vis.DataSet(RAW_EDGES.map((e, i) => ({{
id: i, from: e.from, to: e.to,
label: '',
title: e.title,
dashes: e.dashes,
width: e.width,
color: e.color,
arrows: {{ to: {{ enabled: true, scaleFactor: 0.5 }} }},
}})));
const container = document.getElementById('graph');
const network = new vis.Network(container, {{ nodes: nodesDS, edges: edgesDS }}, {{
physics: {{
enabled: true,
solver: 'forceAtlas2Based',
forceAtlas2Based: {{
gravitationalConstant: -60,
centralGravity: 0.005,
springLength: 120,
springConstant: 0.08,
damping: 0.4,
avoidOverlap: 0.8,
}},
stabilization: {{ iterations: 200, fit: true }},
}},
interaction: {{
hover: true,
tooltipDelay: 100,
hideEdgesOnDrag: true,
navigationButtons: false,
keyboard: false,
}},
nodes: {{ shape: 'dot', borderWidth: 1.5 }},
edges: {{ smooth: {{ type: 'continuous', roundness: 0.2 }}, selectionWidth: 3 }},
}});
network.once('stabilizationIterationsDone', () => {{
network.setOptions({{ physics: {{ enabled: false }} }});
}});
function showInfo(nodeId) {{
const n = nodesDS.get(nodeId);
if (!n) return;
const neighborIds = network.getConnectedNodes(nodeId);
const neighborItems = neighborIds.map(nid => {{
const nb = nodesDS.get(nid);
const color = nb ? nb.color.background : '#555';
return `<span class="neighbor-link" style="border-left-color:${{esc(color)}}" data-nid="${{esc(nid)}}">${{esc(nb ? nb.label : nid)}}</span>`;
}}).join('');
const isMetaNode = !n.file_type && !n.source_file;
let html = `<div class="field"><b>${{esc(n.label)}}</b></div>`;
if (!isMetaNode) {{
html += `<div class="field">Type: ${{esc(n.file_type || 'unknown')}}</div>`;
}}
html += `<div class="field">Community: ${{esc(n.community_name || '')}}</div>`;
if (!isMetaNode) {{
html += `<div class="field">Source: ${{esc(n.source_file || '-')}}</div>`;
}} else if (n.member_count !== undefined && n.member_count !== null) {{
html += `<div class="field">Members: ${{esc(n.member_count)}}</div>`;
}}
html += `<div class="field">Degree: ${{n.degree}}</div>`;
if (neighborIds.length) {{
html += `<div class="field" style="margin-top:8px;color:#aaa;font-size:11px">Neighbors (${{neighborIds.length}})</div><div id="neighbors-list">${{neighborItems}}</div>`;
}}
document.getElementById('info-content').innerHTML = html;
}}
function focusNode(nodeId) {{
network.focus(nodeId, {{ scale: 1.4, animation: true }});
network.selectNodes([nodeId]);
showInfo(nodeId);
}}
// Neighbor links use a data attribute + one delegated listener rather than an
// inline onclick. A node id/label sourced from a document or a scraped URL
// (graphify add) can contain a double-quote; dropping the stringified id
// unescaped into a quoted onclick both broke every link and allowed a hostile
// source to inject an event handler into the local report (stored XSS, #1838).
// esc() on data-nid keeps the value inside the attribute; the listener reads it
// back verbatim. Bound to document so it survives the innerHTML rebuild that
// recreates #neighbors-list on each showInfo().
document.addEventListener('click', e => {{
const el = e.target.closest('.neighbor-link');
if (el && el.dataset.nid !== undefined) focusNode(el.dataset.nid);
}});
// Track hovered node — hover detection is more reliable than click params
let hoveredNodeId = null;
network.on('hoverNode', params => {{
hoveredNodeId = params.node;
container.style.cursor = 'pointer';
}});
network.on('blurNode', () => {{
hoveredNodeId = null;
container.style.cursor = 'default';
}});
container.addEventListener('click', () => {{
if (hoveredNodeId !== null) {{
showInfo(hoveredNodeId);
network.selectNodes([hoveredNodeId]);
}}
}});
network.on('click', params => {{
if (params.nodes.length > 0) {{
showInfo(params.nodes[0]);
}} else if (hoveredNodeId === null) {{
document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
}}
}});
const searchInput = document.getElementById('search');
const searchResults = document.getElementById('search-results');
searchInput.addEventListener('input', () => {{
const q = searchInput.value.toLowerCase().trim();
searchResults.innerHTML = '';
if (!q) {{ searchResults.style.display = 'none'; return; }}
const matches = RAW_NODES.filter(n => n.label.toLowerCase().includes(q)).slice(0, 20);
if (!matches.length) {{ searchResults.style.display = 'none'; return; }}
searchResults.style.display = 'block';
matches.forEach(n => {{
const el = document.createElement('div');
el.className = 'search-item';
el.textContent = n.label;
el.style.borderLeft = `3px solid ${{n.color.background}}`;
el.style.paddingLeft = '8px';
el.onclick = () => {{
network.focus(n.id, {{ scale: 1.5, animation: true }});
network.selectNodes([n.id]);
showInfo(n.id);
searchResults.style.display = 'none';
searchInput.value = '';
}};
searchResults.appendChild(el);
}});
}});
document.addEventListener('click', e => {{
if (!searchResults.contains(e.target) && e.target !== searchInput)
searchResults.style.display = 'none';
}});
const hiddenCommunities = new Set();
const selectAllCb = document.getElementById('select-all-cb');
function updateSelectAllState() {{
const total = LEGEND.length;
const hidden = hiddenCommunities.size;
selectAllCb.checked = hidden === 0;
selectAllCb.indeterminate = hidden > 0 && hidden < total;
}}
function toggleAllCommunities(hide) {{
document.querySelectorAll('.legend-item').forEach(item => {{
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
}});
document.querySelectorAll('.legend-cb').forEach(cb => {{
cb.checked = !hide;
}});
LEGEND.forEach(c => {{
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
}});
const updates = RAW_NODES.map(n => ({{ id: n.id, hidden: hide }}));
nodesDS.update(updates);
updateSelectAllState();
}}
const legendEl = document.getElementById('legend');
LEGEND.forEach(c => {{
const item = document.createElement('div');
item.className = 'legend-item';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'legend-cb';
cb.checked = true;
cb.addEventListener('change', (e) => {{
e.stopPropagation();
if (cb.checked) {{
hiddenCommunities.delete(c.cid);
item.classList.remove('dimmed');
}} else {{
hiddenCommunities.add(c.cid);
item.classList.add('dimmed');
}}
const updates = RAW_NODES
.filter(n => n.community === c.cid)
.map(n => ({{ id: n.id, hidden: !cb.checked }}));
nodesDS.update(updates);
updateSelectAllState();
}});
item.innerHTML = `<div class="legend-dot" style="background:${{c.color}}"></div>
<span class="legend-label">${{c.label}}</span>
<span class="legend-count">${{c.count}}</span>`;
item.prepend(cb);
item.onclick = (e) => {{
if (e.target === cb) return;
cb.checked = !cb.checked;
cb.dispatchEvent(new Event('change'));
}};
legendEl.appendChild(item);
}});
</script>"""
def _html_document_title(output_path: str) -> str:
"""Return a portable label for the graph.html <title>.
Tracked artifacts must not embed the generator host absolute path
(regression of #433; reported again as #2598 on Windows). Keep from the
configured output-dir bare name (``graphify-out`` / ``GRAPHIFY_OUT``
basename) onward — portable in every case; otherwise fall back to a
cwd-relative label, and finally the filename only.
"""
from graphify.paths import GRAPHIFY_OUT_NAME
raw = str(output_path).replace("\\", "/")
# Drop Windows drive prefix so Path parts are comparable on any OS.
if len(raw) >= 3 and raw[1] == ":" and raw[0].isalpha() and raw[2] == "/":
raw = raw[2:] # "/Users/..." style after drive strip
p = Path(raw)
parts = list(Path(raw).parts)
# Path("C:/Users/..") on POSIX may keep "C:" as first part — strip it.
if parts and len(parts[0]) == 2 and parts[0][1] == ":" and parts[0][0].isalpha():
parts = parts[1:]
# Prefer keeping from the output-dir marker onward: portable in every
# case, whereas a cwd-relative path still leaks host/user segments when
# the graph is built from a directory ABOVE the project (#2598 follow-up).
marker = GRAPHIFY_OUT_NAME
for i, part in enumerate(parts):
if part == marker or part.startswith("graphify-out"):
return "/".join(parts[i:])
# No standard out-dir marker (fully custom output path): fall back to a
# cwd-relative label when the target is under cwd, else the bare filename.
try:
resolved = p if p.is_absolute() else (Path.cwd() / p)
rel = resolved.resolve().relative_to(Path.cwd().resolve())
label = rel.as_posix()
if label and label != ".":
return label
except (ValueError, OSError, RuntimeError):
pass
name = p.name
return name if name else "graph.html"
def to_html(
G: nx.Graph,
communities: dict[int, list[str]],
output_path: str,
community_labels: dict[int, str] | None = None,
member_counts: dict[int, int] | None = None,
node_limit: int | None = None,
learning_overlay: dict | None = None,
) -> bool:
"""Generate an interactive vis.js HTML visualization of the graph.
Features: node size by degree, click-to-inspect panel, search box,
community filter, physics clustering by community, confidence-styled edges.
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
If member_counts is provided (aggregated community view), node sizes are
based on community member counts rather than graph degree.
If node_limit is set and the graph exceeds it, automatically builds an
aggregated community-level meta-graph instead of raising ValueError.
Returns True when the output was written. Returns False when an aggregated
view would contain fewer than two communities and is intentionally skipped.
"""
limit = node_limit if node_limit is not None else _viz_node_limit()
if G.number_of_nodes() > limit:
if node_limit is not None:
# Build aggregated community meta-graph
from collections import Counter as _Counter
import networkx as _nx
print(f"Graph has {G.number_of_nodes()} nodes (above {limit} limit). Building aggregated community view...")
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
meta = _nx.Graph()
for cid, members in communities.items():
meta.add_node(str(cid), label=(community_labels or {}).get(cid, f"Community {cid}"))
edge_counts = _Counter()
for u, v in G.edges():
cu, cv = node_to_community.get(u), node_to_community.get(v)
if cu is not None and cv is not None and cu != cv:
edge_counts[(min(cu, cv), max(cu, cv))] += 1
for (cu, cv), w in edge_counts.items():
meta.add_edge(str(cu), str(cv), weight=w,
relation=f"{w} cross-community edges", confidence="AGGREGATED")
if meta.number_of_nodes() <= 1:
print("Single community - aggregated view not useful. Skipping graph.html.")
return False
meta_communities = {cid: [str(cid)] for cid in communities}
mc = {cid: len(members) for cid, members in communities.items()}
# Remap hyperedges from semantic node IDs to community IDs
raw_hyperedges = G.graph.get("hyperedges", [])
if raw_hyperedges:
remapped = []
for he in raw_hyperedges:
he_members = he.get("nodes", [])
comm_ids, seen = [], set()
for nid in he_members:
c = node_to_community.get(nid)
if c is None:
continue
s = str(c)
if s in seen:
continue
seen.add(s)
comm_ids.append(s)
if len(comm_ids) < 2:
continue
remapped.append({
"id": he.get("id", ""),
"label": he.get("label") or he.get("relation", "").replace("_", " "),
"nodes": comm_ids,
})
meta.graph["hyperedges"] = remapped
written = to_html(meta, meta_communities, output_path,
community_labels=community_labels, member_counts=mc)
if not written:
return False
print(f"graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)")
print("Tip: run with --obsidian for full node-level detail.")
return True
raise ValueError(
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
f"or reduce input size."
)
node_community = _node_community_map(communities)
degree = dict(G.degree())
max_deg = max(degree.values(), default=1) or 1
max_mc = (max(member_counts.values(), default=1) or 1) if member_counts else 1
# Work-memory overlay (derived sidecar). When not passed explicitly, load it
# best-effort from the sibling .graphify_learning.json next to the output
# graph.html (which lives beside graph.json). Empty/missing => no learning
# fields, so the un-annotated render is byte-identical to pre-feature.
if learning_overlay is None:
learning_overlay = {}
try:
from graphify.reflect import load_learning_overlay as _llo
learning_overlay = _llo(Path(output_path))
except Exception:
learning_overlay = {}
# Status -> ring color. preferred=green, contested=amber. Tentative gets no
# ring (it's not yet trustworthy enough to highlight in the map).
_RING = {"preferred": "#22c55e", "contested": "#f59e0b"}
# Build nodes list for vis.js
vis_nodes = []
for node_id, data in G.nodes(data=True):
cid = node_community.get(node_id, 0)
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
label = sanitize_label(data.get("label", node_id))
deg = degree.get(node_id, 1)
if member_counts:
mc = member_counts.get(cid, 1)
size = 10 + 30 * (mc / max_mc)
font_size = 12
else:
size = 10 + 30 * (deg / max_deg)
# Only show label for high-degree nodes by default; others show on hover
font_size = 12 if deg >= max_deg * 0.15 else 0
node = {
"id": node_id,
"label": label,
"color": {"background": color, "border": color, "highlight": {"background": "#ffffff", "border": color}},
"size": round(size, 1),
"font": {"size": font_size, "color": "#ffffff"},
# Tooltip `title` is a STRING, which vis-network renders via
# Popup.setText -> `frame.innerText = t` (verified in the pinned
# 9.1.6 bundle: the only non-Element branch is innerText, and the
# bundle has zero `innerHTML = <var>` sinks). So raw special chars
# are shown literally and must NOT be html-escaped here or the user
# sees `&amp;`/`&lt;` in the tooltip (#3664/#3686). This is the
# #1838 stored-XSS boundary: never pass an HTMLElement as `title`,
# and do not change the vis-network pin below without re-checking
# Popup rendering (the test_export version-pin guard enforces this).
"title": label,
"community": cid,
"community_name": sanitize_label((community_labels or {}).get(cid, f"Community {cid}")),
"source_file": sanitize_label(str(data.get("source_file") or "")),
"file_type": data.get("file_type", ""),
"degree": deg,
}
if member_counts:
node["member_count"] = member_counts.get(cid, len(communities.get(cid, [])))
# Conditional learning fields — only present for annotated nodes, so
# un-annotated output keeps the exact pre-feature node dict shape.
entry = learning_overlay.get(str(node_id)) if learning_overlay else None
if entry:
status = sanitize_label(str(entry.get("status", "")))
stale = bool(entry.get("stale"))
node["learning_status"] = status
node["learning_stale"] = stale
ring = _RING.get(status)
if ring:
# Status-colored ring via the border; stale => desaturated +
# dashed (vis.js supports per-node `shapeProperties.borderDashes`).
if stale:
ring = "#9ca3af"
node["shapeProperties"] = {"borderDashes": [4, 4]}
node["borderWidth"] = 3
node["color"] = {
"background": color, "border": ring,
"highlight": {"background": "#ffffff", "border": ring},
}
# Lesson line appended to the hover title.
if status == "contested":
lesson = f"Lesson: contested (useful {entry.get('uses', 0)} / dead-end {entry.get('neg', 0)})"
elif status == "preferred":
lesson = f"Lesson: preferred source ({entry.get('uses', 0)} useful, score={entry.get('score', 0)})"
else:
lesson = f"Lesson: {status} ({entry.get('uses', 0)} useful)"
if stale:
lesson += " [code changed — re-verify]"
node["title"] = f"{label}\n{sanitize_label(lesson)}"
vis_nodes.append(node)
# Build edges list. Restore original edge direction from _src/_tgt
# (stashed by build.py for exactly this reason): undirected NetworkX
# canonicalizes endpoint order, which would otherwise flip the arrow
# for `calls` and `rationale_for` in the rendered graph (#563).
vis_edges = []
for u, v, data in G.edges(data=True):
confidence = data.get("confidence", "EXTRACTED")
relation = data.get("relation", "")
true_src = data.get("_src", u)
true_tgt = data.get("_tgt", v)
vis_edges.append({
"from": true_src,
"to": true_tgt,
"label": relation,
"title": sanitize_label(f"{relation} [{confidence}]"),
"dashes": confidence != "EXTRACTED",
"width": 2 if confidence == "EXTRACTED" else 1,
"color": {"opacity": 0.7 if confidence == "EXTRACTED" else 0.35},
"confidence": confidence,
})
# Build community legend data
legend_data = []
for cid in sorted((community_labels or {}).keys()):
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
lbl = _html.escape(sanitize_label((community_labels or {}).get(cid, f"Community {cid}")))
n = member_counts.get(cid, len(communities.get(cid, []))) if member_counts else len(communities.get(cid, []))
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
# Escape </script> sequences so embedded JSON cannot break out of the script tag
def _js_safe(obj) -> str:
return json.dumps(obj).replace("</", "<\\/")
nodes_json = _js_safe(vis_nodes)
edges_json = _js_safe(vis_edges)
legend_json = _js_safe(legend_data)
hyperedges_json = _js_safe(getattr(G, "graph", {}).get("hyperedges", []))
title = _html.escape(sanitize_label(_html_document_title(output_path)))
stats = f"{G.number_of_nodes()} nodes &middot; {G.number_of_edges()} edges &middot; {len(communities)} communities"
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>graphify - {title}</title>
<script src="https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js"
integrity="sha384-Ux6phic9PEHJ38YtrijhkzyJ8yQlH8i/+buBR8s3mAZOJrP1gwyvAcIYl3GWtpX1"
crossorigin="anonymous"></script>
{_html_styles()}
</head>
<body>
<div id="graph"></div>
<div id="sidebar">
<div id="search-wrap">
<input id="search" type="text" placeholder="Search nodes..." autocomplete="off">
<div id="search-results"></div>
</div>
<div id="info-panel">
<h3>Node Info</h3>
<div id="info-content"><span class="empty">Click a node to inspect it</span></div>
</div>
<div id="legend-wrap">
<h3>Communities</h3>
<div id="legend-controls">
<label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
</div>
<div id="legend"></div>
</div>
<div id="stats">{stats}</div>
</div>
{_html_script(nodes_json, edges_json, legend_json)}
{_hyperedge_script(hyperedges_json)}
</body>
</html>"""
write_text_atomic(output_path, html)
return True
+6807 -9495
View File
File diff suppressed because it is too large. Load diff
+107
View File
@@ -0,0 +1,107 @@
# Migrating a language extractor out of extract.py
`graphify/extract.py` is being split into this package, one language per PR
(upstream issue #1212). This is the playbook for porting ONE language. It is
written so an AI agent can execute it in a single session.
## Status
| module | migrated |
|---|---|
| blade | yes |
| zig | yes |
| elixir | yes |
| razor | yes |
| dart | yes |
| rust | yes |
| go | yes |
| powershell (ps1 + psd1 manifest) | yes |
| fortran | yes |
| sql | yes |
| dm (dm/dmm/dmi/dmf) | yes |
| bash | yes |
| apex | yes |
| terraform | yes |
| sln | yes |
| pascal_forms (dfm + lfm) | yes |
| json_config | yes |
| (config-driven core: python, js, java, c, cpp, csharp, kotlin, scala, php, lua, swift, groovy, vue, svelte, astro, xaml, groovy) | no — shared _extract_generic core, move as one batch |
| (other bespoke: julia, verilog, markdown, objc, csproj, slnx, lazarus_package, pascal) | no |
Note: config-driven extractors (python, js, java, c, cpp, ruby, csharp,
kotlin, scala, php, lua, swift, groovy) depend on the shared
`_extract_generic` core (~1,300 lines). Do NOT port them one-by-one; the core
must move first as its own coordinated batch. Pick a bespoke extractor.
## Invariants (non-negotiable)
1. **Verbatim moves only.** No renames, no docstring edits, no reformatting,
no added annotations, no "improvements". Verify: save the block before
cutting and confirm the pasted block is byte-identical.
2. **One language per PR.** Small diffs keep review trivial and avoid
conflicts with other in-flight ports.
3. **Facade re-export is mandatory.** `extract.py` must keep exporting every
moved name (`from graphify.extractors.<mod> import extract_<lang> # noqa: F401`
in the marked migration block, kept alphabetical). Existing importers
(`__main__.py`, `watch.py`, `pg_introspect.py`, tests) must not change.
4. **Never import from `graphify.extract` inside this package.** Import
direction is strictly extract.py -> extractors/. If you need a helper that
lives in extract.py, classify it (below) and move it.
5. **Zero test edits** outside `tests/test_extractors_registry.py`. The
untouched language tests passing IS the proof of behavior preservation.
## Helper classification
For every `_name` your function references that is defined OUTSIDE it:
- run `grep -c '_name' graphify/extract.py` AFTER your candidate move;
- remaining uses > 0 -> **shared**: move it to `base.py` and add it to the
facade re-import in extract.py;
- remaining uses = 0 -> **private**: move it into your language module.
Closures, constants, and `import` statements defined INSIDE your function
move with it for free — leave them exactly where they are. Only add a
module-header import for names the pasted code references at module scope
that are not satisfied internally, and verify each header import is used.
## Pre-flight
1. Check upstream for conflicts: open PRs/issues mentioning your language,
and churn: `git log --oneline --since="3 months ago" upstream/<default> | grep -i <lang>`.
High churn -> pick another language.
2. Confirm your extractor is bespoke (its `extract_<lang>` is a full function,
not a 5-line `_extract_generic(path, LanguageConfig(...))` wrapper).
3. Check whether tests/ exercises your language's behavior (grep for
`test_<lang>`). If it has no behavioral tests, the byte-identity check in
step 3 below is the ENTIRE proof of preservation — include the
`git diff --color-moved` evidence in your PR description.
## Steps
1. Append a failing test to `tests/test_extractors_registry.py`:
module import + facade identity + registry identity (copy an existing
`test_<lang>_migrated` as the template).
2. `grep -n 'def extract_<lang>' graphify/extract.py`; the span ends at the
line before the next top-level statement (`^def ` or `^_CONST`). Beware
neighbors: top-level constants AFTER your function may belong to the NEXT
function (e.g. `_CONFIG_JSON_*` sit after where extract_razor used to be
but were never razor's).
3. Save the span to a temp file. Create `graphify/extractors/<lang>.py` with
module docstring (`"""<Lang> extractor. Moved verbatim from graphify/extract.py."""`),
`from __future__ import annotations`, minimal stdlib imports, base imports,
then paste the function. Verify byte-identity against the temp file.
4. Delete the span from extract.py, leaving exactly two blank lines between
the now-adjacent top-level definitions; add the facade re-import; add the
registry entry in `__init__.py` (alphabetical); update the Status table
above.
5. `uv run pytest -q` -> 0 failures, no test file changed except the registry
test. If ImportError/NameError: a helper was misclassified — go to
Helper classification.
6. One commit: `refactor(extract): move extract_<lang> to extractors/<lang>.py (verbatim)`.
## What NOT to do
- Do not rewire dispatch, add classes, or add lazy imports — mechanism layers
come later, by separate agreement (see #1212 discussion).
- Do not port two languages in one PR "while you're at it".
- Do not touch `__main__.py`.
+76
View File
@@ -0,0 +1,76 @@
"""Per-language extractors, incrementally migrated out of graphify/extract.py.
Dispatch still flows through graphify.extract (the facade re-exports every
moved name), so importing from graphify.extract keeps working unchanged.
LANGUAGE_EXTRACTORS is the registry seed; wiring dispatch through it is a
later, separate step. See MIGRATION.md for how to port another language.
"""
from __future__ import annotations
from pathlib import Path
from typing import Callable
from graphify.extractors.apex import extract_apex
from graphify.extractors.bash import extract_bash
from graphify.extractors.blade import extract_blade
from graphify.extractors.cobol import extract_cobol
from graphify.extractors.commonlisp import extract_commonlisp
from graphify.extractors.dart import extract_dart
from graphify.extractors.dm import extract_dm, extract_dmf, extract_dmi, extract_dmm
from graphify.extractors.elixir import extract_elixir
from graphify.extractors.erlang import extract_erlang
from graphify.extractors.fortran import extract_fortran
from graphify.extractors.go import extract_go
from graphify.extractors.json_config import extract_json
from graphify.extractors.julia import extract_julia
from graphify.extractors.markdown import extract_markdown
from graphify.extractors.objc import extract_objc
from graphify.extractors.pascal import extract_pascal
from graphify.extractors.pascal_forms import extract_delphi_form, extract_lazarus_form
from graphify.extractors.powershell import extract_powershell, extract_powershell_manifest
from graphify.extractors.r import extract_r
from graphify.extractors.razor import extract_razor
from graphify.extractors.rust import extract_rust
from graphify.extractors.sln import extract_sln
from graphify.extractors.solidity import extract_solidity
from graphify.extractors.sql import extract_sql
from graphify.extractors.terraform import extract_terraform
from graphify.extractors.verilog import extract_verilog
from graphify.extractors.vbnet import extract_vbnet
from graphify.extractors.zig import extract_zig
LANGUAGE_EXTRACTORS: dict[str, Callable[[Path], dict]] = {
"apex": extract_apex,
"bash": extract_bash,
"blade": extract_blade,
"cobol": extract_cobol,
"commonlisp": extract_commonlisp,
"dart": extract_dart,
"delphi_form": extract_delphi_form,
"dm": extract_dm,
"dmf": extract_dmf,
"dmi": extract_dmi,
"dmm": extract_dmm,
"elixir": extract_elixir,
"erlang": extract_erlang,
"fortran": extract_fortran,
"go": extract_go,
"json": extract_json,
"julia": extract_julia,
"lazarus_form": extract_lazarus_form,
"markdown": extract_markdown,
"objc": extract_objc,
"pascal": extract_pascal,
"powershell": extract_powershell,
"powershell_manifest": extract_powershell_manifest,
"r": extract_r,
"razor": extract_razor,
"rust": extract_rust,
"sln": extract_sln,
"solidity": extract_solidity,
"sql": extract_sql,
"terraform": extract_terraform,
"verilog": extract_verilog,
"vbnet": extract_vbnet,
"zig": extract_zig,
}
+215
View File
@@ -0,0 +1,215 @@
"""Apex extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id
def extract_apex(path: Path) -> dict:
"""Extract classes, interfaces, enums, methods, and Salesforce constructs from
Apex .cls and .trigger files using regex (no tree-sitter grammar on PyPI)."""
import re as _re
try:
source = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return {"nodes": [], "edges": []}
str_path = str(path)
stem = _file_stem(path)
file_nid = _make_id(str_path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
def add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": label,
"file_type": "code",
"source_file": str_path,
"source_location": f"L{line}",
})
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED") -> None:
edges.append({
"source": src,
"target": tgt,
"relation": relation,
"confidence": confidence,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
add_node(file_nid, path.name, 1)
lines = source.splitlines()
_ACCESS = r"(?:public|private|protected|global|webService)?"
_SHARING = r"(?:\s+(?:with|without|inherited)\s+sharing)?"
_MOD = r"(?:\s+(?:abstract|virtual|override|static|final|transient|testMethod))?"
_ANNOTATION = r"(?:\s*@\w+(?:\s*\([^)]*\))?\s*)*"
cls_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*class\s+(\w+)"
rf"(?:\s+extends\s+(\w+))?(?:\s+implements\s+([\w,\s]+))?\s*\{{?",
_re.IGNORECASE,
)
iface_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*interface\s+(\w+)"
rf"(?:\s+extends\s+([\w,\s]+))?\s*\{{?",
_re.IGNORECASE,
)
enum_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*enum\s+(\w+)\s*\{{?",
_re.IGNORECASE,
)
trigger_re = _re.compile(
r"^\s*trigger\s+(\w+)\s+on\s+(\w+)\s*\(",
_re.IGNORECASE,
)
method_re = _re.compile(
rf"^{_ANNOTATION}\s*{_ACCESS}{_MOD}\s*(?:static\s+)?[\w<>\[\]]+\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+\w+\s*)?\{{?",
_re.IGNORECASE,
)
annotation_re = _re.compile(r"@(\w+)", _re.IGNORECASE)
soql_re = _re.compile(r"\[\s*SELECT\b[^\]]+FROM\s+(\w+)", _re.IGNORECASE)
dml_re = _re.compile(r"\b(insert|update|delete|upsert|merge|undelete)\s+\w", _re.IGNORECASE)
_CONTROL_FLOW = frozenset({
"if", "else", "for", "while", "do", "switch", "try", "catch",
"finally", "return", "throw", "new", "void", "null",
"true", "false", "this", "super", "class", "interface", "enum",
"trigger", "on",
})
current_class_nid: str | None = None
pending_annotations: list[str] = []
for lineno, line_text in enumerate(lines, start=1):
stripped = line_text.strip()
if stripped.startswith("@"):
for m in annotation_re.finditer(stripped):
pending_annotations.append(m.group(1).lower())
continue
tm = trigger_re.match(stripped)
if tm:
trig_name, sobject = tm.group(1), tm.group(2)
trig_nid = _make_id(stem, trig_name)
add_node(trig_nid, trig_name, lineno)
add_edge(file_nid, trig_nid, "contains", lineno)
sob_nid = _make_id(sobject)
if sob_nid not in seen_ids:
add_node(sob_nid, sobject, lineno)
add_edge(trig_nid, sob_nid, "uses", lineno, confidence="INFERRED")
current_class_nid = trig_nid
pending_annotations = []
continue
cm = cls_re.match(stripped)
if cm:
class_name = cm.group(1)
if class_name.lower() in _CONTROL_FLOW:
pending_annotations = []
continue
class_nid = _make_id(stem, class_name)
add_node(class_nid, class_name, lineno)
add_edge(file_nid, class_nid, "contains", lineno)
if cm.group(2):
base = cm.group(2).strip()
base_nid = _make_id(stem, base)
if base_nid not in seen_ids:
base_nid = _make_id(base)
if base_nid not in seen_ids:
add_node(base_nid, base, lineno)
add_edge(class_nid, base_nid, "extends", lineno, confidence="INFERRED")
if cm.group(3):
for iface in cm.group(3).split(","):
iface = iface.strip()
if iface:
iface_nid = _make_id(stem, iface)
if iface_nid not in seen_ids:
iface_nid = _make_id(iface)
if iface_nid not in seen_ids:
add_node(iface_nid, iface, lineno)
add_edge(class_nid, iface_nid, "implements", lineno, confidence="INFERRED")
current_class_nid = class_nid
pending_annotations = []
continue
im = iface_re.match(stripped)
if im:
iface_name = im.group(1)
if iface_name.lower() in _CONTROL_FLOW:
pending_annotations = []
continue
iface_nid = _make_id(stem, iface_name)
add_node(iface_nid, iface_name, lineno)
add_edge(file_nid if current_class_nid is None else current_class_nid,
iface_nid, "contains", lineno)
if im.group(2):
for parent in im.group(2).split(","):
parent = parent.strip()
if parent:
parent_nid = _make_id(stem, parent)
if parent_nid not in seen_ids:
parent_nid = _make_id(parent)
if parent_nid not in seen_ids:
add_node(parent_nid, parent, lineno)
add_edge(iface_nid, parent_nid, "extends", lineno, confidence="INFERRED")
pending_annotations = []
continue
em = enum_re.match(stripped)
if em:
enum_name = em.group(1)
if enum_name.lower() in _CONTROL_FLOW:
pending_annotations = []
continue
enum_nid = _make_id(stem, enum_name)
add_node(enum_nid, enum_name, lineno)
add_edge(file_nid if current_class_nid is None else current_class_nid,
enum_nid, "contains", lineno)
pending_annotations = []
continue
if current_class_nid is not None:
mm = method_re.match(stripped)
if mm:
method_name = mm.group(1)
if method_name.lower() not in _CONTROL_FLOW:
method_nid = _make_id(current_class_nid, method_name)
method_label = f".{method_name}()"
add_node(method_nid, method_label, lineno)
add_edge(current_class_nid, method_nid, "method", lineno)
if "auraenabled" in pending_annotations or "invocablemethod" in pending_annotations:
add_edge(file_nid, method_nid, "contains", lineno, confidence="INFERRED")
pending_annotations = []
continue
pending_annotations = []
for sm in soql_re.finditer(line_text):
sobject = sm.group(1)
sob_nid = _make_id(sobject)
if sob_nid not in seen_ids:
add_node(sob_nid, sobject, lineno)
src = current_class_nid or file_nid
add_edge(src, sob_nid, "uses", lineno, confidence="INFERRED")
for dm in dml_re.finditer(line_text):
dml_op = dm.group(1).lower()
dml_nid = _make_id(f"dml_{dml_op}")
if dml_nid not in seen_ids:
add_node(dml_nid, dml_op, lineno)
src = current_class_nid or file_nid
add_edge(src, dml_nid, "uses", lineno, confidence="INFERRED")
return {"nodes": nodes, "edges": edges}
+85
View File
@@ -0,0 +1,85 @@
# DO NOT import from graphify.extract here — direction is extract.py → extractors/ only.
from __future__ import annotations
from pathlib import Path
from graphify.ids import make_id
# Language built-in globals that AST may classify as call targets when used as
# constructors or coercion functions (e.g. String(x), Number(x), Boolean(x)).
# Without this filter they become god-nodes accumulating spurious edges from
# every call site. Filter applied at same-file and cross-file resolution.
# See issue #726.
_LANGUAGE_BUILTIN_GLOBALS: frozenset[str] = frozenset({
# JavaScript / TypeScript ECMAScript built-ins
"String", "Number", "Boolean", "Object", "Array", "Symbol", "BigInt",
"Date", "RegExp", "Error", "TypeError", "RangeError", "SyntaxError",
"ReferenceError", "EvalError", "URIError",
"Promise", "Map", "Set", "WeakMap", "WeakSet", "JSON", "Math",
"Reflect", "Proxy", "Intl",
"parseInt", "parseFloat", "isNaN", "isFinite",
"encodeURIComponent", "decodeURIComponent", "encodeURI", "decodeURI",
# Browser / Node common globals
"URL", "URLSearchParams", "FormData", "Blob", "File",
"Headers", "Request", "Response", "AbortController", "AbortSignal",
"TextEncoder", "TextDecoder", "console",
# Python built-in callables
"str", "int", "float", "bool", "list", "dict", "set", "tuple", "bytes",
"len", "range", "enumerate", "zip", "map", "filter", "sum", "min", "max",
"print", "open", "isinstance", "type", "super", "sorted", "reversed",
"any", "all", "abs", "round", "next", "iter", "hash", "id", "repr",
"callable", "getattr", "setattr", "hasattr", "delattr", "vars", "dir",
# Swift standard library / Foundation / SwiftUI (#2147). Value-type
# initializers (Data(x), Int(x), UUID()) and protocol conformance targets
# appear from virtually every file of a Swift codebase, exactly like the
# ECMAScript constructors above. String/Date/URL/Error are already listed.
"Int", "Int8", "Int16", "Int32", "Int64",
"UInt", "UInt8", "UInt16", "UInt32", "UInt64",
"Double", "Float", "Bool", "Character",
"Sendable", "Codable", "Decodable", "Encodable", "Equatable", "Hashable",
"Identifiable", "Comparable", "CaseIterable", "RawRepresentable",
"CustomStringConvertible", "CustomDebugStringConvertible", "AnyObject",
"LocalizedError",
"Data", "UUID", "Decimal", "Calendar", "Locale", "TimeZone", "Bundle",
"IndexPath", "IndexSet", "NotificationCenter", "UserDefaults",
"FileManager", "URLSession", "URLRequest", "URLComponents",
"JSONDecoder", "JSONEncoder", "DateFormatter", "NumberFormatter",
"ISO8601DateFormatter",
"NSObject", "NSString", "NSError", "NSLock", "NSAttributedString",
"DispatchQueue", "DispatchGroup", "OperationQueue", "RunLoop",
"View", "Color", "Font",
})
def _make_id(*parts: str) -> str:
return make_id(*parts)
def _file_stem(path: Path) -> str:
"""Stem used as the node-ID prefix for a file and its symbols.
The full path (extension dropped) is preserved as path segments; ``make_id``
later collapses the separators to underscores. Using every segment — not just
the immediate parent dir (#1504) — means same-named files in different
directories get distinct IDs instead of colliding into one
last-writer-wins node:
docs/v1/api/README.md -> docs/v1/api/README -> docs_v1_api_readme
docs/v2/api/README.md -> docs/v2/api/README -> docs_v2_api_readme
Top-level files keep a bare stem (``setup.py`` -> ``setup``). When passed an
absolute path the whole path is encoded; the extract() id-remap post-pass
re-derives the canonical repo-relative form from ``source_file`` so the on-disk
location can't leak into the persisted IDs (#502).
Returns "" for a path with no name (``Path('.')`` — a source_file that equals
the scan root, so it has no per-file stem). Guarding here keeps
``path.with_suffix("")`` from raising ``ValueError: '.' has an empty name`` and
protects every caller, not just ``_semantic_id_remap`` (#1618)."""
if not path.name:
return ""
return path.with_suffix("").as_posix()
def _read_text(node, source: bytes) -> str:
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
+579
View File
@@ -0,0 +1,579 @@
"""Bash extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any
from graphify.extractors.base import _file_stem, _make_id, _read_text
# Leading `${VAR}` / `$VAR` expansion segment(s) of a `source` path argument. The
# canonical `BENCH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` idiom makes
# such a variable resolve to the script's own directory, so the literal suffix that
# follows (`lib/x.sh`) can be resolved against the sourcing file's own dir (#2079).
_BASH_LEADING_EXPANSION = re.compile(
r"^(?:(?:\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*)/?)+"
)
def _bash_source_suffix(raw: str, allow_dotdot: bool = False) -> str | None:
"""Return the literal path suffix of a variable-built `source` argument, or
None when the remainder is empty or still holds an expansion.
``"${DIR}/lib/x.sh"`` -> ``"lib/x.sh"``.
When *allow_dotdot* is False (the default — the base is a script-dir guess),
``..`` segments are rejected to prevent traversal outside the project tree.
When True (the base is a tracked var_bases entry — a known directory),
``..`` is permitted and the caller normalises with ``os.path.normpath``.
"""
suffix = _BASH_LEADING_EXPANSION.sub("", raw, count=1).lstrip("/")
if not suffix or "$" in suffix:
return None
if not allow_dotdot and ".." in suffix.split("/"):
return None
return suffix
def _within_tree(ceiling: Path, target: Path) -> bool:
"""True if *target* is *ceiling* or lives beneath it, compared lexically
(normpath, no filesystem access).
A ``source`` path built with ``..`` (the ``$VAR/../lib`` idiom, #2596 form 4,
or a ``$(dirname …)`` prefix) must not be allowed to walk up to an arbitrary
host path: a corpus is attacker-controllable, and both the ``is_file()``
existence probe and the recorded absolute ``target_file`` on the emitted edge
are a corpus-side information leak (``source "$VAR/../../../../etc/passwd"``).
Callers gate the probe/emit on this so a target that escapes the allowed tree
is dropped before it is ever stat-ed. Defense in depth only:
``resolve_bash_source_edges`` independently keeps a *resolved* edge only when
the target is itself a scanned corpus file."""
c = os.path.normpath(str(ceiling))
t = os.path.normpath(str(target))
return t == c or t.startswith(c + os.sep)
# Recognise ``$(dirname "$VAR")`` (or ``$(dirname "${VAR}")``) at the start of
# a ``source`` argument, capturing the variable name so the source resolver
# can treat the whole construct as ``var_bases[VAR].parent`` (#2596 form 3).
_BASH_SOURCE_DIRNAME = re.compile(
r'\$\(dirname\s+"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?"\)'
)
# Name of the leading variable of a `source` argument: `${ROOT}/lib/x.sh` -> ROOT.
_BASH_LEADING_VAR = re.compile(
r"^\$\{([A-Za-z_][A-Za-z0-9_]*)[^}]*\}|^\$([A-Za-z_][A-Za-z0-9_]*)"
)
# The `$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)` idiom, capturing the
# trailing `/..` hops applied to the dirname result.
_BASH_DIRNAME_IDIOM = re.compile(r"dirname[^)]*\)((?:/\.\.)*)")
def _bash_assignment_base(value: str, script_dir: Path) -> Path | None:
"""Resolve a top-level assignment's value to a directory, or None if untracked.
Covers the two forms that make a ``source "${VAR}/lib/x.sh"`` target knowable
statically (#2172):
* the script-dir idiom ``"$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"``,
including any number of trailing ``/..`` hops (and the ``$0`` spelling)
* a literal path, absolute or relative to the script's own directory
Anything else -- a value built from other variables, or command substitution
we do not model -- is left untracked so the caller keeps its previous
script-dir guess rather than binding somewhere invented.
"""
val = value.strip().strip("'\"")
if not val:
return None
if "dirname" in val and ("BASH_SOURCE" in val or "$0" in val):
m = _BASH_DIRNAME_IDIOM.search(val)
base = script_dir
for _ in range((m.group(1).count("..") if m else 0)):
base = base.parent
return base
if "$" in val or "`" in val:
return None
candidate = Path(val)
return candidate if candidate.is_absolute() else script_dir / candidate
def extract_bash(path: Path) -> dict:
"""Extract functions, source imports, and cross-function calls from a .sh file."""
try:
import tree_sitter_bash as tsbash
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-bash not installed"}
try:
language = Language(tsbash.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
# Cross-file resolution scaffolding consumed by resolve_bash_source_edges in
# the extract pipeline: `bash_sources` records which files this one `source`s,
# `raw_calls` records calls whose callee isn't defined in this file (candidate
# calls into a sourced library). The extractor sees one file at a time and so
# can't resolve these itself (#2141).
raw_calls: list[dict] = []
bash_sources: list[dict] = []
raw_seen: set[tuple[str, str]] = set()
seen_ids: set[str] = set()
function_bodies: list[tuple[str, Any]] = []
defined_functions: set[str] = set()
from graphify.security import sanitize_metadata # module-level cached import
def add_node(nid: str, label: str, line: int, kind: str = "code") -> None:
if nid and nid not in seen_ids:
seen_ids.add(nid)
nodes.append({"id": nid, "label": label, "file_type": "code",
"source_file": str_path, "source_location": f"L{line}",
"metadata": sanitize_metadata({"language": "bash", "kind": kind})}) # noqa: E501
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0,
context: str | None = None,
target_file: str | None = None) -> None:
if not src or not tgt or src == tgt:
return
edge = {"source": src, "target": tgt, "relation": relation,
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight}
if context:
edge["context"] = context
# Transient resolved-target hint (#1814/#2169), mirroring the Python/
# markdown extractors: lets the extract() id-remap pass canonicalize a
# target minted from an absolute path even when the target file is not
# in the batch (incremental run) or lives out of root (#2243). Popped
# before anything persists, never shipped into graph.json.
if target_file is not None:
edge["target_file"] = target_file
edges.append(edge)
file_nid = _make_id(str(path))
# file_nid is fully path-derived and never produced by _make_id(stem, func_name),
# so appending "__entry" guarantees a distinct ID from any function node.
entry_nid = file_nid + "__entry"
add_node(file_nid, path.name, 1, kind="file")
add_node(entry_nid, f"{path.name} script", 1, kind="bash_entrypoint")
add_edge(file_nid, entry_nid, "contains", 1)
_BASH_SOURCE_COMMANDS = frozenset({"source", "."})
_BASH_SCRIPT_RUNNERS = frozenset({"bash", "sh", "zsh", "ksh", "dash"})
# Parent node types that mean a contained command is part of a substitution
# or expansion, not a real function call. Token-level filtering misses
# these because `$(build)` exposes `build` as a child command whose name
# token has no metacharacters — only the parent does.
_BASH_EXPANSION_PARENTS = frozenset({
"command_substitution",
"process_substitution",
})
def text(node) -> str:
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
def is_inside_expansion(node) -> bool:
parent = node.parent
while parent is not None:
if parent.type in _BASH_EXPANSION_PARENTS:
return True
parent = parent.parent
return False
def _bash_call_in_command_allowed(cmd_node) -> bool:
"""Whether a command node should emit call edges.
Bare ``$(fn)`` at script level and process substitutions stay suppressed
(#2141). Value capture via ``x=$(fn)`` is a real invocation (#2978).
"""
parent = cmd_node.parent
saw_command_substitution = False
while parent is not None:
if parent.type == "process_substitution":
return False
if parent.type == "command_substitution":
saw_command_substitution = True
if parent.type == "variable_assignment" and saw_command_substitution:
return True
parent = parent.parent
return not saw_command_substitution
def literal(node) -> str | None:
# Token-level filter: rejects names containing shell metacharacters.
# Combined with `is_inside_expansion` for parent-context rejection.
raw = text(node).strip()
if not raw:
return None
if raw[0:1] in {"'", '"'} and raw[-1:] == raw[0]:
raw = raw[1:-1]
if any(token in raw for token in ("$", "`", "$(", "<(", ">", "|", ";", "&")):
return None
return raw
def _bash_func_name(node) -> str | None:
"""Get the name from a function_definition node."""
# bash grammar: function_definition has a word child (the name)
for child in node.children:
if child.type == "word":
return literal(child)
return None
def walk_calls(body_node, func_nid: str, seen_calls: set) -> None:
if body_node is None:
return
for child in body_node.children:
if child.type == "function_definition":
# Skip nested function definitions — their bodies are walked
# separately, so we don't attribute their calls to the
# enclosing scope.
continue
if child.type == "command" and _bash_call_in_command_allowed(child):
cmd_name_node = child.child_by_field_name("name")
if cmd_name_node is None and child.children:
cmd_name_node = child.children[0]
if cmd_name_node:
name = literal(cmd_name_node)
# Defined-functions wins. Skip-lists for external commands
# would create false negatives when a user defines a
# function shadowing an external (`install`, `find`, etc.).
if name and name in defined_functions:
tgt = _make_id(stem, name)
key = (func_nid, tgt)
if tgt and key not in seen_calls:
seen_calls.add(key)
add_edge(func_nid, tgt, "calls",
child.start_point[0] + 1,
confidence="EXTRACTED", context="call")
elif (name and name not in _BASH_SOURCE_COMMANDS
and name not in _BASH_SCRIPT_RUNNERS):
# Callee isn't defined in this file — it may be a function
# from a sourced library. Record an unresolved raw_call for
# resolve_bash_source_edges to bind against the files this
# script `source`s. A callee that is not a sourced function
# (a genuine external command) matches nothing there and
# yields no edge, so this can't over-connect the graph (#2141).
raw_key = (func_nid, name)
if raw_key not in raw_seen:
raw_seen.add(raw_key)
raw_calls.append({
"language": "bash",
"callee": name,
"caller_nid": func_nid,
"source_file": str_path,
"source_location": f"L{child.start_point[0] + 1}",
})
walk_calls(child, func_nid, seen_calls)
def walk(node, parent_nid: str) -> None:
t = node.type
if t == "function_definition":
name = _bash_func_name(node)
if name:
fn_nid = _make_id(stem, name)
line = node.start_point[0] + 1
add_node(fn_nid, f"{name}()", line, kind="bash_function")
add_edge(parent_nid, fn_nid, "defines", line)
defined_functions.add(name)
# find the compound_statement body
body = None
for child in node.children:
if child.type == "compound_statement":
body = child
break
function_bodies.append((fn_nid, body))
# Recurse into the body so nested function definitions are discovered
# and added to function_bodies for the second-pass walk_calls.
if body is not None:
walk(body, fn_nid)
return
if t == "command":
if is_inside_expansion(node):
return
cmd_name_node = node.child_by_field_name("name")
if cmd_name_node is None and node.children:
cmd_name_node = node.children[0]
if cmd_name_node:
cmd = literal(cmd_name_node)
args = [c for c in node.children
if c.type in ("word", "string", "concatenation")
and c != cmd_name_node]
if cmd in _BASH_SOURCE_COMMANDS and cmd not in defined_functions:
# find the path argument (first word after command name)
if args:
raw = _read_text(args[0], source).strip().strip("'\"")
line = node.start_point[0] + 1
if raw.startswith((".", "/")):
resolved = (path.parent / raw).resolve()
# Only emit the edge if the target actually exists on
# disk — prevents graph pollution from crafted paths
# like `source ../../etc/passwd` that traverse outside
# the project tree (B-1).
if resolved.exists():
tgt_nid = _make_id(str(resolved))
add_edge(file_nid, tgt_nid, "imports_from", line,
context="import",
target_file=str(resolved))
# Record the sourced file so resolve_bash_source_edges
# can bind calls into its functions (#2141). Gated on
# existence like the edge above, so crafted traversal
# paths never enter the resolver's data.
bash_sources.append({
"target_path": raw,
"source_file": str_path,
"source_location": f"L{line}",
})
elif "$" in raw:
# Variable-built path, e.g. the ubiquitous
# `source "${BENCH_DIR}/lib/x.sh"` idiom. The raw text
# bakes the unexpanded `${VAR}` into the id, which
# matches no node and is dropped as a dangling edge
# (#2079). Strip the leading expansion(s) and resolve
# the literal suffix against the script's own dir;
# emit INFERRED (the expansion can't be proven
# statically) only when it resolves to a real file,
# never a dead id.
# Form 3 (#2596): `source "$(dirname "$VAR")/lib/x.sh"`
# — command substitution in the source argument.
# Recognise the dirname idiom on the source line the
# same way _bash_assignment_base does on assignment
# lines: treat `$(dirname "$VAR")` as
# `var_bases[VAR].parent` (falling back to
# `script_dir.parent` when VAR is untracked), then
# resolve the literal suffix against it.
dirname_match = _BASH_SOURCE_DIRNAME.match(raw)
if dirname_match:
var_name = dirname_match.group(1)
if var_name in var_bases:
base = var_bases[var_name].parent
else:
# Untracked var: fall back to the script's
# own directory, so dirname resolves to its
# parent — matching the existing untracked-var
# fallback semantics.
base = path.parent.parent
# Strip the $(dirname ...) prefix and any leading
# slash to get the literal suffix.
suffix = raw[dirname_match.end():].lstrip("/")
# The base is a guessed script dir, so reject a
# `..` suffix outright — same policy as
# _bash_source_suffix(allow_dotdot=False); without
# it, `$(dirname "$VAR")/../../../etc/passwd`
# resolves and gets probed/recorded (#2596).
if (suffix and "$" not in suffix
and ".." not in suffix.split("/")):
resolved = (base / suffix).resolve()
if resolved.is_file():
add_edge(file_nid, _make_id(str(resolved)),
"imports_from", line,
confidence="INFERRED", context="import",
target_file=str(resolved))
bash_sources.append({
"target_path": str(resolved),
"source_file": str_path,
"source_location": f"L{line}",
})
else:
# Check if the leading variable is tracked
# before deciding whether to allow `..` in
# the suffix (Form 4, #2596). When the base
# is a known var_bases entry, `..` is safe.
var_match = _BASH_LEADING_VAR.match(raw)
allow_dotdot = False
if var_match:
_vn = var_match.group(1) or var_match.group(2)
if _vn in var_bases:
allow_dotdot = True
suffix = _bash_source_suffix(raw, allow_dotdot=allow_dotdot)
if suffix:
# Resolve against the variable's tracked base
# when we know it, else fall back to the
# script's own directory as before (#2172).
base = path.parent
if var_match:
var_name = var_match.group(1) or var_match.group(2)
if var_name in var_bases:
base = var_bases[var_name]
if var_match and var_name in var_bases:
resolved = Path(os.path.normpath(base / suffix))
# A tracked base may reach a sibling via
# `$VAR/../lib`, so the ceiling is one
# level up — but `..` must not walk past
# it to an arbitrary host path (#2596).
ceiling = base.parent
else:
resolved = (base / suffix).resolve()
# Untracked base: `..` was already rejected
# by _bash_source_suffix, so the target is
# under base; the gate is belt-and-braces.
ceiling = base
if _within_tree(ceiling, resolved) and resolved.is_file():
add_edge(file_nid, _make_id(str(resolved)),
"imports_from", line,
confidence="INFERRED", context="import",
target_file=str(resolved))
# Integration (#2141 + #2079): record
# the resolved sourced file so calls
# into its functions resolve too, not
# just the source edge. target_path is
# absolute here; resolve_bash_source_edges
# takes it as-is.
bash_sources.append({
"target_path": str(resolved),
"source_file": str_path,
"source_location": f"L{line}",
})
else:
# Bare `source lib.sh` (no leading ./ or /). Bash
# itself resolves such a name via $PATH at runtime,
# but in practice the file sits next to the script,
# so bind it when a sibling of that name exists
# (#2171). Same existence gate as the ./-prefixed
# branch above: a name that resolves to nothing keeps
# the old opaque `imports` edge and records no
# bash_sources entry, so nothing is fabricated.
sibling: Path | None = None
if raw:
try:
candidate = path.parent / raw
if candidate.is_file():
sibling = candidate.resolve()
except OSError:
sibling = None
if sibling is not None:
# A bare `source lib.sh` resolves via $PATH at
# runtime; binding it to the sibling of that name
# is a heuristic, so mark it INFERRED (#2171).
add_edge(file_nid, _make_id(str(sibling)),
"imports_from", line,
confidence="INFERRED", context="import",
target_file=str(sibling))
bash_sources.append({
"target_path": raw,
"source_file": str_path,
"source_location": f"L{line}",
})
else:
tgt_nid = _make_id(raw)
if tgt_nid:
add_edge(file_nid, tgt_nid, "imports", line,
context="import")
elif cmd not in defined_functions:
raw = cmd if (cmd and cmd.endswith(".sh")) else None
if cmd and cmd in _BASH_SCRIPT_RUNNERS and args:
raw = literal(args[0])
if raw is None:
# The command name is itself an expansion, e.g.
# `"$script_dir/x.sh" --flag`. `literal()` rejects any
# candidate containing "$", so `cmd` is None and neither
# of the two branches above can see the path. Read the
# node's raw text the way the `source` branch does and
# strip the leading ${VAR}/ segments -- the same
# script-dir assumption already used for `source
# "$DIR/lib/x.sh"` (#2079). `_bash_source_suffix`
# rejects a remainder that still holds an expansion or
# a `..` segment, and the `resolved.is_file()` gate
# below means a wrong script-dir guess emits nothing.
cand = _read_text(cmd_name_node, source).strip().strip("'\"")
if cand.endswith(".sh") and "$" in cand:
raw = _bash_source_suffix(cand) or None
if raw and raw.endswith(".sh"):
resolved = (path.parent / raw).resolve()
if resolved.is_file():
target_path = resolved
if not path.is_absolute():
try:
target_path = resolved.relative_to(Path.cwd().resolve())
except ValueError:
pass
caller_nid = entry_nid if parent_nid == file_nid else parent_nid
# target_file lets the extract() remap loop learn
# this script's canonical id even when it is not in
# the batch; the "__entry"-suffixed endpoint is
# rewritten there via the suffix-aware entry
# registration (#2243).
add_edge(caller_nid, _make_id(str(target_path)) + "__entry",
"calls", node.start_point[0] + 1,
context="script_invocation",
target_file=str(target_path))
return
if t == "declaration_command":
# export/declare/readonly VAR=value at program level
if node.parent and node.parent.type == "program":
for child in node.children:
if child.type == "variable_assignment":
var_node = child.child_by_field_name("name")
if var_node:
var = _read_text(var_node, source).strip()
if var:
var_nid = _make_id(stem, var)
line = child.start_point[0] + 1
add_node(var_nid, var, line)
add_edge(file_nid, var_nid, "defines", line)
return
for child in node.children:
walk(child, parent_nid)
# Pre-pass: collect all defined function names so the source-command handler
# in walk() can detect user-defined functions that shadow 'source' / '.'
# regardless of definition order in the file.
def _prescan_functions(node) -> None:
if node.type == "function_definition":
name = _bash_func_name(node)
if name:
defined_functions.add(name)
for child in node.children:
_prescan_functions(child)
else:
for child in node.children:
_prescan_functions(child)
_prescan_functions(root)
# Bases for `source "${VAR}/lib/x.sh"` resolution (#2172). #2079 always resolved
# the literal suffix against the script's own directory, which is right for the
# `DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` idiom but wrong whenever
# the variable points elsewhere -- e.g. ROOT=".../scripts/.." with a same-named
# decoy under the script dir bound to the decoy. Track top-level assignments so
# the real base is used; untracked variables keep the script-dir guess.
var_bases: dict[str, Path] = {}
for _assign in root.children:
if _assign.type != "variable_assignment":
continue
_name_node = _assign.child_by_field_name("name")
_value_node = _assign.child_by_field_name("value")
if _name_node is None or _value_node is None:
continue
_name = _read_text(_name_node, source).strip()
if not _name:
continue
_base = _bash_assignment_base(_read_text(_value_node, source), path.parent)
if _base is not None:
var_bases[_name] = _base
walk(root, file_nid)
# Second pass: cross-function calls
top_seen: set = set()
walk_calls(root, entry_nid, top_seen) # top-level calls attributed to the entrypoint
for fn_nid, body in function_bodies:
walk_calls(body, fn_nid, set())
return {"nodes": nodes, "edges": edges,
"raw_calls": raw_calls, "bash_sources": bash_sources}
+67
View File
@@ -0,0 +1,67 @@
"""Laravel Blade template extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
from pathlib import Path
from graphify.extractors.base import _make_id
def extract_blade(path: Path) -> dict:
"""Extract @extends, @include, <livewire:> components, and wire:click bindings from Blade templates."""
import re
try:
src = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return {"error": f"cannot read {path}"}
file_nid = _make_id(str(path))
nodes = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str(path), "source_location": None}]
edges = []
# @extends('layouts.app') — template inheritance: this view renders inside
# the named parent layout. It is the primary structural relationship in a
# Blade view (most page templates extend a layout), so dropping it left the
# child disconnected from its layout in the graph.
for m in re.finditer(r"@extends\(['\"]([^'\"]+)['\"]", src):
tgt = m.group(1).replace(".", "/")
tgt_nid = _make_id(tgt)
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": tgt_nid, "relation": "extends",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
# @include('path.to.partial') or @include("path.to.partial")
for m in re.finditer(r"@include\(['\"]([^'\"]+)['\"]", src):
tgt = m.group(1).replace(".", "/")
tgt_nid = _make_id(tgt)
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": tgt_nid, "relation": "includes",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
# <livewire:component.name /> or <livewire:component.name>
for m in re.finditer(r"<livewire:([\w.\-]+)", src):
tgt_nid = _make_id(m.group(1))
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": tgt_nid, "relation": "uses_component",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
# wire:click="methodName"
for m in re.finditer(r'wire:click=["\']([^"\']+)["\']', src):
tgt_nid = _make_id(m.group(1))
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": tgt_nid, "relation": "binds_method",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
return {"nodes": nodes, "edges": edges}
+297
View File
@@ -0,0 +1,297 @@
"""Deterministic extraction for fixed- and free-format COBOL source."""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
from graphify.extractors.base import _make_id
_NAME = r"[A-Z0-9][A-Z0-9-]*"
_PROGRAM = re.compile(rf"\bPROGRAM-ID\s*\.\s*({_NAME})", re.IGNORECASE)
_PARAGRAPH = re.compile(
rf"^({_NAME})(?:\s+(SECTION))?\s*\.\s*$", re.IGNORECASE
)
_PERFORM = re.compile(
rf"\bPERFORM\s+({_NAME})(?:\s+(?:THRU|THROUGH)\s+({_NAME}))?\b",
re.IGNORECASE,
)
_COPY = re.compile(
rf"\bCOPY\s+(?:'([^']+)'|\"([^\"]+)\"|({_NAME}(?:\.[A-Z0-9-]+)?))",
re.IGNORECASE,
)
_CALL = re.compile(r"\bCALL\s+(['\"])([A-Z0-9-]+)\1", re.IGNORECASE)
_DATA_ITEM = re.compile(
rf"^\s*(?:0[1-9]|[1-4][0-9]|66|77|88)\s+({_NAME})\b", re.IGNORECASE
)
_NOT_PARAGRAPHS = frozenset({
"IDENTIFICATION", "ENVIRONMENT", "DATA", "PROCEDURE", "FILE",
"WORKING-STORAGE", "LOCAL-STORAGE", "LINKAGE", "CONFIGURATION",
"INPUT-OUTPUT", "STOP", "EXIT", "GOBACK", "CONTINUE", "DISPLAY", "MOVE",
"COMPUTE", "ADD", "SUBTRACT", "MULTIPLY", "DIVIDE", "PERFORM", "COPY",
"CALL", "IF", "ELSE", "END-IF", "END-PERFORM", "END-EXEC",
})
_PERFORM_MODIFIERS = frozenset({
"UNTIL", "VARYING", "TIMES", "WITH", "TEST", "FOREVER",
})
def _code_lines(source: str) -> list[tuple[int, str]]:
"""Return logical COBOL lines with fixed-format continuations joined."""
physical = source.splitlines()
forced_free = bool(
re.search(r">>\s*SOURCE\s+FORMAT\s+(?:IS\s+)?FREE", source, re.IGNORECASE)
)
# A fixed-format line is a 6-column sequence area followed by the indicator
# in column 7. The sequence area is blank on some files but carries a
# sequence NUMBER on legacy mainframe source (the historical norm), so match
# both: six spaces, or six digits, followed by a valid indicator (space =
# code, `*`/`/` = comment, `-` = continuation, `D` = debug). Requiring six
# blank columns misclassified every sequence-numbered file as free-format,
# which then kept the sequence number in the code and dropped every paragraph
# (its `^NAME.$` anchor no longer matched) and PERFORM edge.
fixed_markers = sum(
bool(re.match(r"^(?: {6}|\d{6})[ *\-/dD]", line))
for line in physical if line.strip()
)
nonempty = sum(bool(line.strip()) for line in physical)
free = forced_free or fixed_markers < max(1, nonempty // 2)
logical: list[tuple[int, str]] = []
for number, line in enumerate(physical, 1):
if free:
code = line.split("*>", 1)[0].rstrip()
if not code.strip() or code.lstrip().startswith(">>"):
continue
logical.append((number, code))
continue
if len(line) < 7:
continue
indicator = line[6]
if indicator in "*/":
continue
code = line[7:72].split("*>", 1)[0].rstrip()
if not code.strip():
continue
if indicator == "-" and logical:
prior_number, prior = logical[-1]
joiner = "" if prior.rstrip().endswith("-") else " "
logical[-1] = (prior_number, prior.rstrip() + joiner + code.lstrip())
else:
logical.append((number, code))
return logical
def _mask_strings(code: str) -> str:
return re.sub(r"'[^']*'|\"[^\"]*\"", lambda match: " " * len(match.group()), code)
def _starts_inside_string(code: str, offset: int) -> bool:
"""Whether *offset* lies inside a COBOL quoted literal."""
for match in re.finditer(r"'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"", code):
if match.start() <= offset < match.end():
return True
return False
def extract_cobol(path: Path) -> dict:
try:
source = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return {"nodes": [], "edges": [], "error": str(exc)}
source_file = str(path)
file_id = _make_id(source_file)
nodes: list[dict[str, Any]] = []
edges: list[dict[str, Any]] = []
raw_calls: list[dict[str, Any]] = []
seen_ids: set[str] = set()
seen_edges: set[tuple[str, str, str]] = set()
def add_node(
nid: str,
label: str,
line: int,
*,
kind: str,
source_backed: bool = True,
callable_node: bool = False,
) -> str:
if nid not in seen_ids:
seen_ids.add(nid)
item: dict[str, Any] = {
"id": nid,
"label": label,
"file_type": "code",
"source_location": f"L{line}",
"metadata": {"language": "cobol", "kind": kind},
}
if source_backed:
item["source_file"] = source_file
if callable_node:
item["_callable"] = True
nodes.append(item)
return nid
def add_edge(
source_id: str,
target_id: str,
relation: str,
line: int,
*,
target_file: str | None = None,
) -> None:
key = (source_id, target_id, relation)
if not source_id or not target_id or source_id == target_id or key in seen_edges:
return
seen_edges.add(key)
edge: dict[str, Any] = {
"source": source_id,
"target": target_id,
"relation": relation,
"confidence": "EXTRACTED",
"source_file": source_file,
"source_location": f"L{line}",
"weight": 1.0,
}
if target_file:
edge["target_file"] = target_file
edges.append(edge)
add_node(file_id, path.name, 1, kind="file")
code_lines = _code_lines(source)
current_program = file_id
current_scope = file_id
in_procedure = False
in_exec = False
paragraphs: dict[tuple[str, str], str] = {}
pending_performs: list[tuple[str, str, str, int]] = []
for line, code in code_lines:
upper = code.upper().strip()
if in_exec:
if "END-EXEC" in upper:
in_exec = False
continue
if re.search(r"\bEXEC\s+(?:SQL|CICS)\b", upper):
if "END-EXEC" not in upper:
in_exec = True
continue
program_match = _PROGRAM.search(upper)
if program_match:
name = program_match.group(1).upper()
current_program = add_node(
_make_id(file_id, "program", name.casefold()),
name,
line,
kind="program",
callable_node=True,
)
add_edge(file_id, current_program, "contains", line)
current_scope = current_program
in_procedure = False
continue
copy_match = _COPY.search(code)
if copy_match:
written = next(group for group in copy_match.groups() if group)
copy_name = written.rstrip(".")
copy_path = Path(copy_name)
if not copy_path.suffix:
copy_path = copy_path.with_suffix(".cpy")
target = path.parent / copy_path
reference_id = add_node(
_make_id(current_program, "copybook", copy_name.casefold()),
Path(copy_name).stem.upper(),
line,
kind="copybook_reference",
)
add_edge(current_program, reference_id, "contains", line)
add_edge(
current_program,
_make_id(str(target)),
"imports_from",
line,
target_file=str(target),
)
if "PROCEDURE DIVISION" in upper:
in_procedure = True
current_scope = current_program
continue
if not in_procedure:
item = _DATA_ITEM.match(upper)
if item:
name = item.group(1).upper()
if name != "FILLER":
item_id = add_node(
_make_id(current_program, "data", name.casefold()),
name,
line,
kind="data_item",
)
add_edge(current_program, item_id, "contains", line)
continue
paragraph = _PARAGRAPH.match(upper)
if paragraph and paragraph.group(1) not in _NOT_PARAGRAPHS:
name = paragraph.group(1).upper()
key = (current_program, name.casefold())
paragraph_id = paragraphs.get(key)
if paragraph_id is None:
paragraph_id = add_node(
_make_id(current_program, "paragraph", name.casefold()),
name,
line,
kind="section" if paragraph.group(2) else "paragraph",
callable_node=True,
)
paragraphs[key] = paragraph_id
add_edge(current_program, paragraph_id, "contains", line)
current_scope = paragraph_id
continue
masked = _mask_strings(upper)
for match in _PERFORM.finditer(masked):
# `PERFORM A THRU Z` runs the range A..Z, so both endpoints are
# performed — link both. Only the entry paragraph was captured
# before, leaving the range-end with no inbound edge ("what performs
# Z?" answered nothing even though this paragraph does). Intermediate
# paragraphs in the range are not individually linked (that needs
# source ordering); the two endpoints are the reliable, common signal.
for group in (match.group(1), match.group(2)):
if group is None:
continue
name = group.upper()
if name not in _PERFORM_MODIFIERS:
pending_performs.append((current_scope, current_program, name, line))
for match in _CALL.finditer(upper):
if _starts_inside_string(upper, match.start()):
continue
callee = match.group(2).upper()
raw_calls.append({
"caller_nid": current_scope,
"callee": callee,
"language": "cobol",
"source_file": source_file,
"source_location": f"L{line}",
})
for caller_id, program_id, name, line in pending_performs:
target_id = paragraphs.get((program_id, name.casefold()))
if target_id is not None:
add_edge(caller_id, target_id, "calls", line)
clean_edges = [
edge for edge in edges
if edge["source"] in seen_ids
and (edge["target"] in seen_ids or edge["relation"] == "imports_from")
]
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
+540
View File
@@ -0,0 +1,540 @@
"""Common Lisp extractor for .lisp/.cl/.lsp/.asd, backed by tree-sitter-commonlisp."""
from __future__ import annotations
import warnings
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id
# Standard CL definer forms that introduce data/type/variable bindings
# (not callable, no body to walk for calls)
_CL_DATA_DEFINERS = frozenset({
"defstruct", "deftype", "define-condition",
"defvar", "defparameter", "defconstant",
"define-symbol-macro",
})
# Subset of data definers that take a VALUE as their second argument, which
# may itself be a string literal. For these, we must not mistake the value
# for a docstring.
_CL_VALUE_DEFINERS = frozenset({"defvar", "defparameter", "defconstant"})
# Standard CL macro-style definers
_CL_MACRO_DEFINERS = frozenset({
"define-modify-macro", "define-compiler-macro",
"define-setf-expander", "defsetf",
})
# Symbols that start with "def" but are NOT definitions (denylist for the
# def-prefix heuristic that catches custom definers like definline-maybe)
_CL_NOT_DEFINERS = frozenset({
"default", "default-value", "defaults", "define",
"defer", "deferred", "deflate", "deftest",
})
# CL special forms / macros that should not count as "calls" in the graph
_CL_SPECIAL_FORMS = frozenset({
"let", "let*", "flet", "labels", "macrolet",
"if", "when", "unless", "cond", "case", "ecase", "typecase", "etypecase",
"progn", "prog1", "prog2", "block", "return-from", "tagbody", "go",
"lambda", "function", "funcall", "apply",
"setf", "setq", "psetf", "psetq", "incf", "decf", "push", "pop",
"loop", "do", "do*", "dolist", "dotimes", "map", "mapcar", "mapc",
"format", "print", "princ", "prin1", "write", "terpri",
"and", "or", "not", "null",
"values", "multiple-value-bind", "multiple-value-setq",
"declare", "the", "locally", "eval-when",
"quote", "backquote",
"error", "signal", "warn", "assert", "check-type",
"handler-case", "handler-bind", "restart-case", "ignore-errors",
"unwind-protect", "catch", "throw",
"with-open-file", "with-output-to-string", "with-input-from-string",
"with-slots", "with-accessors",
"defvar", "defparameter", "defconstant",
"in-package", "require", "provide", "use-package",
"t", "nil",
})
def extract_commonlisp(path: Path) -> dict:
"""Extract packages, classes, functions, methods, macros, and calls from a Common Lisp file."""
try:
import tree_sitter_commonlisp as tscl
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-commonlisp not installed"}
try:
# tree-sitter-commonlisp 0.4.1 (latest) ships the old binding that returns
# an int pointer from language(); tree_sitter.Language only accepts that
# int via a deprecated path. Silence that one warning at the call site
# until the grammar ships a PyCapsule binding.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="int argument support is deprecated",
category=DeprecationWarning,
)
language = Language(tscl.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
# Path-qualified, not the bare `path.stem`: same-named .lisp files in
# different directories must not collide (#1504). Pre-collapsed through
# `_make_id` because `_cl_id` would otherwise map the `/` separators to
# `_slash` via _CL_CHAR_MAP.
stem = _make_id(_file_stem(path))
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
function_bodies: list[tuple[str, object]] = [] # (nid, body_nodes)
current_package: str | None = None
def _text(node) -> str:
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
# CL symbols can contain operator chars like = < > ? ! + * / that the
# generic _make_id strips. Map them to readable suffixes so upi=, upi<,
# upi> become distinct ids.
_CL_CHAR_MAP = {
'=': '_eq', '<': '_lt', '>': '_gt', '?': '_p', '!': '_bang',
'+': '_plus', '*': '_star', '/': '_slash', '%': '_pct', '&': '_amp',
}
def _cl_id(*parts: str) -> str:
normalized = []
for p in parts:
normalized.append(''.join(_CL_CHAR_MAP.get(c, c) for c in p))
return _make_id(*normalized)
def add_node(nid: str, label: str, line: int, file_type: str = "code") -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": label,
"file_type": file_type,
"source_file": str_path,
"source_location": f"L{line}",
})
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0) -> None:
edges.append({
"source": src,
"target": tgt,
"relation": relation,
"confidence": confidence,
"source_file": str_path,
"source_location": f"L{line}",
"weight": weight,
})
file_nid = _cl_id(stem)
add_node(file_nid, path.name, 1)
def add_import_stub(mod_name: str) -> str:
"""Mint a SOURCELESS stub for an imported package so its `imports` edge
has a real target instead of dangling. The corpus rewire collapses it
onto a unique in-corpus `defpackage` of the same name; an external one
(cl, alexandria) stays a sourceless leaf. `origin_file` is stripped
before persist (no #1899 leak); a sourced bare stub would salt the id."""
nid = _cl_id(mod_name)
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": mod_name,
"file_type": "code",
"source_file": "",
"source_location": "",
"origin_file": str_path,
})
return nid
def ensure_class_ref(name: str, line: int) -> str:
"""Resolve a superclass name to a node id.
If the class is defined in THIS file, bind to its local node. Otherwise
mint a SOURCELESS stub (like `add_import_stub`) so the corpus-level
rewire can collapse it onto the real `defclass` in another file. Without
this, a cross-file superclass had no matching node and its `inherits`
edge was pruned by the dangling-edge filter — silently erasing every
inheritance edge whose parent lives in a different file."""
local = _cl_id(stem, name)
if local in seen_ids:
return local
stub = _cl_id(name)
if stub not in seen_ids:
seen_ids.add(stub)
nodes.append({
"id": stub,
"label": name,
"file_type": "code",
"source_file": "",
"source_location": "",
"origin_file": str_path,
})
return stub
def _first_sym(node) -> str | None:
"""Get the first sym_lit text from a list_lit's children."""
for child in node.children:
if child.type == "sym_lit":
return _text(child)
return None
def _kwd_text(node) -> str:
"""Extract the symbol name from a kwd_lit, stripping the leading colon."""
t = _text(node)
return t.lstrip(":").lstrip("#:")
def _handle_defpackage(node) -> None:
nonlocal current_package
children = node.children
pkg_name = None
for child in children:
if child.type == "kwd_lit" and pkg_name is None:
pkg_name = _kwd_text(child)
break
if child.type == "sym_lit" and _text(child) != "defpackage":
pkg_name = _text(child)
break
if not pkg_name:
return
current_package = pkg_name
pkg_nid = _cl_id(stem, pkg_name)
line = node.start_point[0] + 1
add_node(pkg_nid, pkg_name, line)
add_edge(file_nid, pkg_nid, "contains", line)
# Extract :use clauses as imports
for child in children:
if child.type == "list_lit":
first = _first_sym(child)
if first is None:
# Could be (:use ...) with kwd_lit
for gc in child.children:
if gc.type == "kwd_lit" and _kwd_text(gc) == "use":
for uc in child.children:
if uc.type == "kwd_lit" and uc != gc:
mod_name = _kwd_text(uc)
if mod_name != "use":
tgt_nid = add_import_stub(mod_name)
add_edge(pkg_nid, tgt_nid, "imports",
child.start_point[0] + 1)
break
def _handle_defclass(node) -> None:
children = node.children
# Find class name: second sym_lit after "defclass"
sym_lits = [c for c in children if c.type == "sym_lit"]
if len(sym_lits) < 2:
return
class_name = _text(sym_lits[1])
line = node.start_point[0] + 1
class_nid = _cl_id(stem, class_name)
add_node(class_nid, class_name, line)
parent_nid = file_nid
if current_package:
pkg_nid = _cl_id(stem, current_package)
if pkg_nid in seen_ids:
parent_nid = pkg_nid
add_edge(parent_nid, class_nid, "contains", line)
# Superclasses (third element, a list)
list_lits = [c for c in children if c.type == "list_lit"]
if list_lits:
superclass_list = list_lits[0]
for sc in superclass_list.children:
if sc.type == "sym_lit":
sc_name = _text(sc)
sc_nid = ensure_class_ref(sc_name, superclass_list.start_point[0] + 1)
add_edge(class_nid, sc_nid, "inherits",
superclass_list.start_point[0] + 1)
def _handle_defun_node(node) -> None:
"""Handle a defun AST node (covers defun, defmethod, defgeneric, defmacro)."""
header = None
for child in node.children:
if child.type == "defun_header":
header = child
break
if not header:
return
# Determine keyword type
keyword_type = "defun"
func_name = None
for child in header.children:
if child.type == "defun_keyword":
for kc in child.children:
if kc.type in ("defun", "defmethod", "defgeneric", "defmacro"):
keyword_type = kc.type
break
if child.type == "sym_lit" and func_name is None:
func_name = _text(child)
if not func_name:
return
line = node.start_point[0] + 1
func_nid = _cl_id(stem, func_name)
if keyword_type == "defmethod":
label = f".{func_name}()"
elif keyword_type == "defmacro":
label = f"{func_name} (macro)"
elif keyword_type == "defgeneric":
label = f"{func_name} (generic)"
else:
label = f"{func_name}()"
add_node(func_nid, label, line)
parent_nid = file_nid
if current_package:
pkg_nid = _cl_id(stem, current_package)
if pkg_nid in seen_ids:
parent_nid = pkg_nid
if keyword_type == "defmethod":
add_edge(parent_nid, func_nid, "method", line)
else:
add_edge(parent_nid, func_nid, "contains", line)
# Method specializers: (defmethod name ((param class) ...))
if keyword_type == "defmethod":
for child in header.children:
if child.type == "list_lit":
# This is the parameter list
for param in child.children:
if param.type == "list_lit":
syms = [c for c in param.children if c.type == "sym_lit"]
if len(syms) >= 2:
specializer_name = _text(syms[1])
spec_nid = _cl_id(stem, specializer_name)
add_edge(func_nid, spec_nid, "specializes",
param.start_point[0] + 1)
break
# Docstring
for child in node.children:
if child.type == "str_lit":
doc_text = _text(child).strip('"')
if doc_text:
doc_nid = _cl_id(func_nid, "rationale")
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
add_edge(doc_nid, func_nid, "rationale_for",
child.start_point[0] + 1)
break
# Collect body for call extraction
body_nodes = [c for c in node.children
if c.type not in ("(", ")", "defun_header", "str_lit")]
if body_nodes:
function_bodies.append((func_nid, body_nodes))
def _extract_def_name(node, def_keyword: str) -> str | None:
"""Get the name being defined. May be a sym_lit or a list_lit whose
first sym_lit is the name (e.g. (defstruct (foo :conc-name "BAR-") ...))."""
seen_keyword = False
for child in node.children:
if not seen_keyword:
if child.type == "sym_lit" and _text(child).lower() == def_keyword:
seen_keyword = True
continue
if child.type == "sym_lit":
return _text(child)
if child.type == "list_lit":
for gc in child.children:
if gc.type == "sym_lit":
return _text(gc)
return None
return None
def _collect_def_body(node, def_keyword: str) -> list:
"""Collect body forms from (DEFKEYWORD name (params) [doc] body...).
Skips the def keyword, the name, the params list (if present), and
a leading docstring str_lit."""
children = [c for c in node.children if c.type not in ("(", ")")]
idx = 0
# Skip def keyword
if idx < len(children) and children[idx].type == "sym_lit" \
and _text(children[idx]).lower() == def_keyword:
idx += 1
# Skip name (sym_lit or list_lit)
if idx < len(children) and children[idx].type in ("sym_lit", "list_lit"):
idx += 1
# Skip params list (the next list_lit, if any)
if idx < len(children) and children[idx].type == "list_lit":
idx += 1
# Skip leading docstring
if idx < len(children) and children[idx].type == "str_lit":
idx += 1
return children[idx:]
def _handle_def_form(node, def_keyword: str) -> None:
"""Handle a generic (DEFKEYWORD name ...) form. Covers standard CL
definers (defstruct, deftype, defvar, define-condition, etc.) and
custom def-prefixed macros (definline, definline-maybe, etc.)."""
name = _extract_def_name(node, def_keyword)
if not name:
return
line = node.start_point[0] + 1
nid = _cl_id(stem, name)
kw = def_keyword.lower()
if kw in _CL_DATA_DEFINERS:
label = name
is_callable = False
elif kw in _CL_MACRO_DEFINERS or "macro" in kw:
label = f"{name} (macro)"
is_callable = True
else:
# Custom def-prefixed: assume function-like
label = f"{name}()"
is_callable = True
add_node(nid, label, line)
parent_nid = file_nid
if current_package:
pkg_nid = _cl_id(stem, current_package)
if pkg_nid in seen_ids:
parent_nid = pkg_nid
add_edge(parent_nid, nid, "contains", line)
# Docstring. Skip for defvar/defparameter/defconstant — their second
# argument is a value (possibly a string literal) which would be
# wrongly captured as a docstring.
if kw not in _CL_VALUE_DEFINERS:
for child in node.children:
if child.type == "str_lit":
doc_text = _text(child).strip('"')
if doc_text:
doc_nid = _cl_id(nid, "rationale")
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
add_edge(doc_nid, nid, "rationale_for",
child.start_point[0] + 1)
break
if is_callable:
body_nodes = _collect_def_body(node, def_keyword)
if body_nodes:
function_bodies.append((nid, body_nodes))
def _is_def_prefixed(sym: str) -> bool:
"""Heuristic: does this symbol look like a definition macro?"""
if sym in _CL_NOT_DEFINERS:
return False
return sym.startswith("def") or sym.startswith("define-")
def _process_form(top) -> bool:
"""Dispatch on a single list_lit form. Returns True if it was
recognized as a definition or package directive (caller must NOT
recurse into it). Returns False if unrecognized, so the caller can
recurse to find defs nested inside wrapper macros like
(optimizing ...), (eval-when ...), (progn ...), etc."""
nonlocal current_package
# Check for defun node type inside list_lit
for child in top.children:
if child.type == "defun":
_handle_defun_node(child)
return True
first = _first_sym(top)
if not first:
return False
first_lower = first.lower()
if first_lower == "defpackage":
_handle_defpackage(top)
return True
if first_lower == "in-package":
for child in top.children:
if child.type == "kwd_lit":
current_package = _kwd_text(child)
break
if child.type == "sym_lit" and _text(child) != "in-package":
current_package = _text(child)
break
return True
if first_lower == "defclass":
_handle_defclass(top)
return True
if first_lower in ("require", "ql:quickload"):
for child in top.children:
if child.type in ("kwd_lit", "str_lit"):
mod_name = _kwd_text(child) if child.type == "kwd_lit" else _text(child).strip('"')
if mod_name:
tgt_nid = add_import_stub(mod_name)
add_edge(file_nid, tgt_nid, "imports",
top.start_point[0] + 1)
break
return True
if first_lower in _CL_DATA_DEFINERS or first_lower in _CL_MACRO_DEFINERS:
_handle_def_form(top, first_lower)
return True
if _is_def_prefixed(first_lower):
# Custom definer (definline, definline-maybe, defcomponent, etc.)
_handle_def_form(top, first_lower)
return True
return False
def _walk_forms(parent) -> None:
"""Walk list_lit children of `parent`, processing each. If a form
isn't recognized, recurse into it — many CL codebases wrap
definitions in macros like (optimizing ...), (eval-when ...), or
(progn ...) that aren't themselves definers but contain defs.
Also descends into reader conditionals (#+feature / #-feature),
which wrap their guarded form in an include_reader_macro node."""
for top in parent.children:
if top.type == "list_lit":
if not _process_form(top):
_walk_forms(top)
elif top.type == "include_reader_macro":
_walk_forms(top)
_walk_forms(root)
# Call extraction pass
label_to_nid: dict[str, str] = {}
for n in nodes:
raw = n["label"]
normalised = raw.replace(" (macro)", "").replace(" (generic)", "").strip("()").lstrip(".")
label_to_nid[normalised.lower()] = n["id"]
seen_call_pairs: set[tuple[str, str]] = set()
def walk_calls(node, caller_nid: str) -> None:
if node.type == "defun":
return
if node.type == "list_lit":
callee = _first_sym(node)
if callee and callee.lower() not in _CL_SPECIAL_FORMS:
tgt_nid = label_to_nid.get(callee.lower())
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
seen_call_pairs.add(pair)
add_edge(caller_nid, tgt_nid, "calls",
node.start_point[0] + 1, confidence="EXTRACTED", weight=1.0)
for child in node.children:
walk_calls(child, caller_nid)
for caller_nid, body_nodes in function_bodies:
for body_node in body_nodes:
walk_calls(body_node, caller_nid)
clean_edges = [e for e in edges if e["source"] in seen_ids and
(e["target"] in seen_ids or e["relation"] in ("imports", "imports_from"))]
return {"nodes": nodes, "edges": clean_edges}
+474
View File
@@ -0,0 +1,474 @@
"""C# cross-file resolution.
The config-driven C# *extractor* (``extract_csharp`` → ``_extract_generic``)
still lives in ``graphify/extract.py``; per ``extractors/MIGRATION.md`` the
config-driven languages cannot be ported one-by-one until the shared
``_extract_generic`` core moves as its own coordinated batch. This module is
the C# home for the parts that *are* cleanly separable — today, the cross-file
type-reference resolver below — and is where ``extract_csharp`` will land when
the core migration happens.
"""
from __future__ import annotations
import html
from pathlib import Path
from graphify.extractors.base import _make_id
def _build_csharp_type_def_index(
all_nodes: list[dict],
all_edges: list[dict] | None = None,
) -> dict[tuple[str, str], str]:
"""Return deterministic ``(namespace, name) -> node_id`` C# type definitions."""
non_type_ids: set[str] = set()
if all_edges is not None:
for edge in all_edges:
rel = edge.get("relation")
if rel in ("case_of", "defines", "method"):
tgt = edge.get("_tgt") or edge.get("target")
if isinstance(tgt, str):
non_type_ids.add(tgt)
candidates: dict[tuple[str, str], list[dict]] = {}
for node in all_nodes:
if node.get("type") == "namespace":
continue
metadata = node.get("metadata") or {}
if not isinstance(metadata, dict):
metadata = {}
if metadata.get("is_nested_type"):
continue
nid = node.get("id")
label = node.get("label")
if not (
isinstance(nid, str)
and nid
and isinstance(label, str)
and label
):
continue
if all_edges is not None and nid in non_type_ids:
continue
source_file = node.get("source_file")
if (
not isinstance(source_file, str)
or not source_file.endswith(".cs")
or node.get("file_type") != "code"
):
continue
if label.endswith(")") or label.startswith(".") or "." in label:
continue
namespace = metadata.get("namespace", "")
if not isinstance(namespace, str):
namespace = ""
candidates.setdefault((namespace, label), []).append(node)
return {
key: sorted(
nodes,
key=lambda node: (
str(node.get("source_file") or ""),
str(node.get("source_location") or ""),
str(node.get("id") or ""),
),
)[0]["id"]
for key, nodes in candidates.items()
}
def _strip_trailing_csharp_generic_args(target_fqn: str) -> str:
target_fqn = target_fqn.strip()
if not target_fqn.endswith(">"):
return target_fqn
depth = 0
for index in range(len(target_fqn) - 1, -1, -1):
char = target_fqn[index]
if char == ">":
depth += 1
elif char == "<":
depth -= 1
if depth == 0:
return target_fqn[:index].strip()
return target_fqn
def _resolve_cross_file_csharp_imports(
per_file: list[dict],
paths: list[Path],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Re-point resolvable C# ``using`` import edges to canonical internal nodes.
Namespace imports resolve only to canonical C# namespace nodes. Alias imports
resolve only when the alias target's prefix is a known canonical namespace and
the simple type name exists in the shared C# type-definition index. ``using
static`` and nested type aliases remain deliberate gaps because they need
member/nested-type modeling beyond this import pass.
"""
_ = (per_file, paths)
namespace_id_by_label: dict[str, str] = {}
for node in sorted(
all_nodes,
key=lambda node: (
str(node.get("source_file") or ""),
str(node.get("source_location") or ""),
str(node.get("id") or ""),
),
):
if node.get("type") != "namespace":
continue
label = node.get("label")
nid = node.get("id")
if isinstance(label, str) and label and isinstance(nid, str) and nid:
namespace_id_by_label.setdefault(label, nid)
type_def_index = _build_csharp_type_def_index(all_nodes, all_edges)
if not namespace_id_by_label and not type_def_index:
return
repointed_from: set[str] = set()
for edge in all_edges:
if edge.get("relation") != "imports":
continue
metadata = edge.get("metadata") or {}
if not isinstance(metadata, dict):
continue
using_kind = metadata.get("using_kind")
target_fqn = metadata.get("target_fqn")
if not using_kind or not isinstance(target_fqn, str) or not target_fqn:
continue
resolved = None
if using_kind == "namespace":
resolved = namespace_id_by_label.get(target_fqn)
elif using_kind == "alias":
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
prefix, sep, name = base_fqn.rpartition(".")
if sep and prefix in namespace_id_by_label:
resolved = type_def_index.get((prefix, name))
old_target = edge.get("target")
if resolved and resolved != old_target:
edge["target"] = resolved
if isinstance(old_target, str) and old_target:
repointed_from.add(old_target)
if not repointed_from:
return
still_referenced: set[str] = set()
for edge in all_edges:
still_referenced.add(edge.get("source"))
still_referenced.add(edge.get("target"))
all_nodes[:] = [
node for node in all_nodes
if node.get("id") not in repointed_from or node.get("id") in still_referenced
]
_DOTNET_SOURCE_EXTS = (".cs", ".razor", ".cshtml")
def _is_cs_file(value: object) -> bool:
return isinstance(value, str) and value.endswith(".cs")
def _is_dotnet_source_file(value: object) -> bool:
return isinstance(value, str) and value.endswith(_DOTNET_SOURCE_EXTS)
def _metadata(value: object) -> dict:
return value if isinstance(value, dict) else {}
class CsharpNameResolver:
"""Namespace/using/alias-aware C# simple-name resolution.
Factored out of ``_resolve_csharp_type_references`` so the member-call pass
(``_resolve_csharp_member_calls`` in ``graphify/extract.py``) can type a
receiver with the same scoping rules the type-reference side already applies
(the core of #1620), instead of bailing on any corpus-wide bare-name clash.
Built from graph-stamped facts only: the ``(namespace, name)`` type-definition
index plus the per-file ``using``/alias import edges (each carrying its lexical
scope — ``("file", None)`` applies file-wide; ``("namespace", scope_id)``
applies only where ``scope_id`` is in the referencing node's ``scope_chain``).
"""
def __init__(self, all_nodes: list[dict], all_edges: list[dict]) -> None:
self.node_by_id: dict[str, dict] = {
node["id"]: node
for node in all_nodes
if isinstance(node.get("id"), str) and node.get("id")
}
self.type_def_index = _build_csharp_type_def_index(all_nodes, all_edges)
self.known_namespaces = {
node.get("label")
for node in all_nodes
if node.get("type") == "namespace" and isinstance(node.get("label"), str)
}
self.namespace_usings_by_file: dict[str, list[tuple[str, str, str | None]]] = {}
self.aliases_by_file: dict[str, dict[str, list[tuple[str, str, str | None]]]] = {}
for edge in all_edges:
if edge.get("relation") != "imports":
continue
source_node = self.node_by_id.get(edge.get("source"))
if not (
source_node
and isinstance(source_node.get("label"), str)
and source_node.get("label", "").endswith(_DOTNET_SOURCE_EXTS)
):
continue
source_file = source_node.get("source_file")
if not _is_dotnet_source_file(source_file):
continue
metadata = _metadata(edge.get("metadata"))
target_fqn = metadata.get("target_fqn")
if not isinstance(target_fqn, str) or not target_fqn:
continue
scope_kind = metadata.get("scope_kind") or "file"
scope_id = metadata.get("scope_id")
using_kind = metadata.get("using_kind")
if using_kind == "namespace":
entry = (target_fqn, scope_kind, scope_id)
bucket = self.namespace_usings_by_file.setdefault(source_file, [])
if entry not in bucket:
bucket.append(entry)
elif using_kind == "alias":
alias = metadata.get("alias")
if isinstance(alias, str) and alias:
entry = (target_fqn, scope_kind, scope_id)
bucket = self.aliases_by_file.setdefault(source_file, {}).setdefault(alias, [])
if entry not in bucket:
bucket.append(entry)
@staticmethod
def _namespace(node: dict | None) -> str:
metadata = _metadata((node or {}).get("metadata"))
namespace = metadata.get("namespace", "")
return namespace if isinstance(namespace, str) else ""
@staticmethod
def _scope_chain(node: dict) -> list[str]:
chain = _metadata(node.get("metadata")).get("scope_chain")
return chain if isinstance(chain, list) else []
def _using_in_scope(self, scope_kind: str, scope_id: str | None, source_node: dict) -> bool:
if scope_kind == "file":
return True
return scope_id is not None and scope_id in self._scope_chain(source_node)
def _scopes_for(self, source_node: dict, source_file: str) -> list[str]:
def _append_unique(items: list[str], value: str) -> None:
if value not in items:
items.append(value)
scopes: list[str] = []
_append_unique(scopes, self._namespace(source_node))
_append_unique(scopes, "")
for namespace, scope_kind, scope_id in self.namespace_usings_by_file.get(source_file, []):
if self._using_in_scope(scope_kind, scope_id, source_node):
_append_unique(scopes, namespace)
return scopes
def _resolve_alias(self, label: str, source_node: dict, source_file: str) -> str | None:
hits = set()
for target_fqn, scope_kind, scope_id in self.aliases_by_file.get(source_file, {}).get(label, []):
if not self._using_in_scope(scope_kind, scope_id, source_node):
continue
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
namespace, sep, simple_name = base_fqn.rpartition(".")
if not sep:
simple_name = namespace
namespace = ""
if not simple_name:
continue
hit = self.type_def_index.get((namespace, simple_name))
if hit:
hits.add(hit)
return next(iter(hits)) if len(hits) == 1 else None
def resolve_type_name(
self, label: str, source_node: dict, source_file: str
) -> tuple[str | None, bool]:
"""Resolve a simple type name to a definition node id, with a verdict.
Returns ``(node_id, decisive)``:
* ``(nid, True)`` — exactly one in-scope definition (or alias target).
* ``(None, True)`` — the name is claimed by this file's scoping (an
alias, or >1 in-scope candidates): genuinely ambiguous/unresolvable,
the caller must NOT fall back to a looser corpus-wide match.
* ``(None, False)`` — scoping knows nothing about the name; a caller
may fall back (e.g. to the corpus-wide unique bare-name match).
"""
if label in self.aliases_by_file.get(source_file, {}):
return self._resolve_alias(label, source_node, source_file), True
candidates: list[str] = []
for namespace in self._scopes_for(source_node, source_file):
hit = self.type_def_index.get((namespace, label))
if hit and hit not in candidates:
candidates.append(hit)
if len(candidates) == 1:
return candidates[0], True
return None, bool(candidates)
def resolve_label(self, label: str, source_node: dict, source_file: str) -> str | None:
resolved, _decisive = self.resolve_type_name(label, source_node, source_file)
return resolved
def resolve_qualified(
self, label: str, qualifier: object, source_node: dict, source_file: str
) -> str | None:
# Sound qualified resolution: an in-scope alias for Q shadows the namespace Q. For a qualified
# ref Q.label, look up (alias_target_namespace, label). If no in-scope alias, fall through to an
# exact known namespace. Dangle on ambiguity / no hit / unknown qualifier.
if not isinstance(qualifier, str) or not qualifier:
return None
in_scope = [
entry for entry in self.aliases_by_file.get(source_file, {}).get(qualifier, [])
if self._using_in_scope(entry[1], entry[2], source_node)
]
if in_scope:
hits = set()
for target_fqn, _scope_kind, _scope_id in in_scope:
alias_ns = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
hit = self.type_def_index.get((alias_ns, label))
if hit:
hits.add(hit)
return next(iter(hits)) if len(hits) == 1 else None
if qualifier in self.known_namespaces:
return self.type_def_index.get((qualifier, label))
return None
def _resolve_csharp_type_references(
per_file: list[dict],
paths: list[Path],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Arbitrate all C# ``inherits``/``implements``/``references`` targets.
The extractor emits provisional same-file bindings and sourceless stubs. This
pass is the single soundness gate: it uses only graph-stamped namespace/import
facts, keeps a binding only when the referenced simple name resolves to one
in-scope real type definition, and otherwise leaves the edge on a dangling stub.
"""
_ = (per_file, paths)
resolver = CsharpNameResolver(all_nodes, all_edges)
node_by_id = resolver.node_by_id
aliases_by_file = resolver.aliases_by_file
def _resolve_label(label: str, source_node: dict, source_file: str) -> str | None:
return resolver.resolve_label(label, source_node, source_file)
def _resolve_qualified(label: str, qualifier: object, source_node: dict, source_file: str) -> str | None:
return resolver.resolve_qualified(label, qualifier, source_node, source_file)
def _is_placeholder(node: dict | None) -> bool:
return bool(node) and not node.get("source_file")
def _is_csharp_relevant_target(node: dict) -> bool:
if node.get("type") == "namespace":
return True
source_file = node.get("source_file")
return not source_file or _is_cs_file(source_file)
def _label_for_type_ref_target(target_node: dict, source_file: str) -> str | None:
label = target_node.get("label")
if not isinstance(label, str) or not label:
return None
if not label.endswith(".cs"):
return label
stem = label[:-3]
for alias in aliases_by_file.get(source_file, {}):
if alias.lower() == stem.lower() or _make_id(alias) == _make_id(stem):
return alias
return stem or None
def _dangling_stub_id(label: str, current_target: object) -> str:
current = node_by_id.get(current_target)
if _is_placeholder(current) and current.get("label") == label:
return str(current_target)
for node in all_nodes:
nid = node.get("id")
if (
isinstance(nid, str)
and node.get("label") == label
and _is_placeholder(node)
):
return nid
stem = _make_id(label)
stub_id = stem
if stub_id in node_by_id:
stub_id = _make_id("csharp_type_ref", label)
suffix = 2
while stub_id in node_by_id:
stub_id = _make_id("csharp_type_ref", label, str(suffix))
suffix += 1
node = {
"id": stub_id,
"label": label,
"file_type": "code",
"source_file": "",
"source_location": "",
}
all_nodes.append(node)
node_by_id[stub_id] = node
return stub_id
REPOINT_RELATIONS = {"implements", "inherits", "references"}
repointed_from: set[str] = set()
for edge in all_edges:
if edge.get("relation") not in REPOINT_RELATIONS:
continue
source_file = edge.get("source_file")
if not _is_dotnet_source_file(source_file):
continue
source_node = node_by_id.get(edge.get("source"))
target_node = node_by_id.get(edge.get("target"))
if not source_node or not target_node:
continue
if not _is_csharp_relevant_target(target_node):
continue
metadata = _metadata(edge.get("metadata"))
label = metadata.get("ref_token") or _label_for_type_ref_target(target_node, source_file)
if not label:
continue
if metadata.get("qualified"):
resolved = _resolve_qualified(label, metadata.get("ref_qualifier"), source_node, source_file)
else:
resolved = _resolve_label(label, source_node, source_file)
target = edge.get("target")
desired = resolved or _dangling_stub_id(label, target)
if desired != target:
edge["target"] = desired
if isinstance(target, str) and _is_placeholder(target_node):
repointed_from.add(target)
if not repointed_from:
return
still_referenced: set[str] = set()
for edge in all_edges:
still_referenced.add(edge.get("source"))
still_referenced.add(edge.get("target"))
all_nodes[:] = [
node for node in all_nodes
if node.get("id") not in repointed_from or node.get("id") in still_referenced
]
+564
View File
@@ -0,0 +1,564 @@
"""Dart extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
import re
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id
def extract_dart(path: Path) -> dict:
"""Extract classes, mixins, functions, imports, generic calls, and annotations from a .dart file using regex."""
try:
src = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return {"error": f"cannot read {path}"}
# Remove inline and multi-line comments while leaving string literals untouched to prevent stripping URLs/paths inside strings
comment_string_pattern = re.compile(
r'"""(?:\\.|[\s\S])*?"""'
r"|'''(?:\\.|[\s\S])*?'''"
r'|"(?:\\.|[^"\\])*"'
r"|'(?:\\.|[^'\\])*'"
r"|/\*[\s\S]*?\*/"
r"|//[^\n]*"
)
def _comment_replace(match: re.Match) -> str:
token = match.group(0)
if token.startswith("/"):
# Blank to the SAME number of newlines the comment spanned, not
# to an empty string: every offset computed against src_clean
# below (including every source_location line number) is only
# valid if src_clean's line count tracks the original file's.
# Deleting a multi-line comment outright shifted every later
# line number up by the comment's own height (#3365).
return "\n" * token.count("\n")
return token
src_clean = comment_string_pattern.sub(_comment_replace, src)
def _line_at(offset: int) -> int:
return src_clean[:offset].count("\n") + 1
stem = _file_stem(path)
file_nid = _make_id(str(path))
# Check if this is a part-of file and redirect to parent
part_of_match = re.search(r"^\s*part\s+of\s+['\"]([^'\"]+)['\"]", src_clean, re.MULTILINE)
is_part = False
if part_of_match:
parent_ref = part_of_match.group(1)
if parent_ref.endswith(".dart"):
try:
parent_path = (path.parent / parent_ref).resolve()
if parent_path.exists():
stem = _file_stem(parent_path)
file_nid = _make_id(str(parent_path))
is_part = True
except Exception:
pass
nodes = []
if not is_part:
nodes.append({"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str(path), "source_location": None})
edges = []
defined: set[str] = set()
def add_node(nid: str, label: str, ftype: str = "code", source_file: str | None = str(path),
line: int | None = None) -> None:
if nid not in defined:
nodes.append({"id": nid, "label": label, "file_type": ftype,
"source_file": source_file,
"source_location": f"L{line}" if line else None})
defined.add(nid)
def add_edge(src_id: str, tgt_id: str, relation: str, weight: float = 1.0, context: str | None = None,
line: int | None = None) -> None:
edge = {"source": src_id, "target": tgt_id, "relation": relation,
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path),
"source_location": f"L{line}" if line else None, "weight": weight}
if context:
edge["context"] = context
edges.append(edge)
def _split_types(text: str) -> list[str]:
parts = []
current = []
depth = 0
for char in text:
if char == "<":
depth += 1
current.append(char)
elif char == ">":
depth -= 1
current.append(char)
elif char == "," and depth == 0:
parts.append("".join(current).strip())
current = []
else:
current.append(char)
if current:
parts.append("".join(current).strip())
return [p for p in parts if p]
def _find_matching_brace(text: str, start_pos: int) -> int:
brace_count = 0
in_double_quote = False
in_single_quote = False
escape = False
first_brace = text.find("{", start_pos)
if first_brace == -1:
return len(text)
brace_count = 1
i = first_brace + 1
n = len(text)
while i < n:
char = text[i]
if escape:
escape = False
i += 1
continue
if char == "\\":
escape = True
i += 1
continue
if text[i:i+3] == '"""' and not in_single_quote:
i += 3
end = text.find('"""', i)
i = end + 3 if end != -1 else n
continue
if text[i:i+3] == "'''" and not in_double_quote:
i += 3
end = text.find("'''", i)
i = end + 3 if end != -1 else n
continue
if char == '"' and not in_single_quote:
in_double_quote = not in_double_quote
elif char == "'" and not in_double_quote:
in_single_quote = not in_single_quote
elif not in_double_quote and not in_single_quote:
if char == "{":
brace_count += 1
elif char == "}":
brace_count -= 1
if brace_count == 0:
return i + 1
i += 1
return len(text)
# 1. Classes, mixins, and enums declarations (with inheritance, mixins, interfaces, and generics)
# Supports multiple combined modifiers (e.g., abstract base class, mixin class) without capturing "class" as a name
class_pattern = r"^\s*(?:(?:abstract|sealed|base|interface|final|mixin)\s+)*(?:class|mixin|enum|extension\s+type)\s+(\w+)"
for m in re.finditer(class_pattern, src_clean, re.MULTILINE):
class_name = m.group(1)
# Anchor on the capture group, not the whole match: the pattern's
# leading ^\s* makes m.start() land before the blank/indent lines
# that precede the declaration, reporting the line too early (#3365).
class_line = _line_at(m.start(1))
class_nid = _make_id(stem, class_name)
add_node(class_nid, class_name, line=class_line)
add_edge(file_nid, class_nid, "defines", line=class_line)
# Manually parse extends/on, with, and implements in header to handle nested generics brackets balanced
start_idx = m.end()
rest = src_clean[start_idx : start_idx + 500]
# Skip class generic parameters
if rest.lstrip().startswith("<"):
offset = rest.find("<")
depth = 1
i = offset + 1
while i < len(rest) and depth > 0:
if rest[i] == "<": depth += 1
elif rest[i] == ">": depth -= 1
i += 1
rest = rest[i:]
# Skip primary constructor (e.g. extension type MyExt(int id))
if rest.lstrip().startswith("("):
offset = rest.find("(")
depth = 1
i = offset + 1
while i < len(rest) and depth > 0:
if rest[i] == "(": depth += 1
elif rest[i] == ")": depth -= 1
i += 1
rest = rest[i:]
header_end = rest.find("{")
if header_end == -1:
header_end = rest.find(";")
if header_end == -1:
header_end = len(rest)
header = rest[:header_end]
base_class = None
generics = None
mixins_list = []
interfaces_list = []
# Parse extends or on
extends_m = re.search(r"^\s*(?:extends|on)\s+([a-zA-Z0-9_.]+)", header)
if extends_m:
base_class = extends_m.group(1)
rest_header = header[extends_m.end():]
if rest_header.strip().startswith("<"):
start_idx = rest_header.find("<")
depth = 1
i = start_idx + 1
while i < len(rest_header) and depth > 0:
if rest_header[i] == "<":
depth += 1
elif rest_header[i] == ">":
depth -= 1
if depth == 0:
generics = rest_header[start_idx + 1 : i]
break
i += 1
if generics is not None:
header = rest_header[i + 1:]
else:
header = rest_header
else:
header = rest_header
# Parse with
with_m = re.search(r"^\s*with\s+", header)
if with_m:
rest_header = header[with_m.end():]
impl_idx = rest_header.find("implements")
if impl_idx != -1:
mixins_str = rest_header[:impl_idx]
header = rest_header[impl_idx:]
else:
mixins_str = rest_header
header = ""
mixins_list = _split_types(mixins_str)
# Parse implements
impl_m = re.search(r"^\s*implements\s+", header)
if impl_m:
interfaces_list = _split_types(header[impl_m.end():])
# Map extends inheritance relation
if base_class:
base_nid = _make_id(base_class)
add_node(base_nid, base_class, source_file=None)
add_edge(class_nid, base_nid, "inherits", line=class_line)
# Map generic type arguments (e.g. MyBloc extends Bloc<MyEvent, MyState>)
if generics:
for gen in _split_types(generics):
gen_clean = gen.split("<")[0].strip()
if gen_clean not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
gen_nid = _make_id(gen_clean)
add_node(gen_nid, gen_clean, source_file=None)
add_edge(class_nid, gen_nid, "references", line=class_line)
# Map mixins
for mixin in mixins_list:
mixin_clean = mixin.split("<")[0].strip()
mixin_nid = _make_id(mixin_clean)
add_node(mixin_nid, mixin_clean, source_file=None)
add_edge(class_nid, mixin_nid, "mixes_in", line=class_line)
# Map interfaces
for interface in interfaces_list:
interface_clean = interface.split("<")[0].strip()
interface_nid = _make_id(interface_clean)
add_node(interface_nid, interface_clean, source_file=None)
add_edge(class_nid, interface_nid, "implements", line=class_line)
# Extract class body for precise framework dependencies and event handling
start_idx = m.start()
brace_pos = src_clean.find("{", start_idx)
semi_pos = src_clean.find(";", start_idx)
has_body = brace_pos != -1
if has_body and semi_pos != -1 and semi_pos < brace_pos:
has_body = False
if has_body:
end_pos = _find_matching_brace(src_clean, start_idx)
class_body = src_clean[brace_pos:end_pos]
# Bloc event registration: on<MyEvent>()
for em in re.finditer(r"\bon<(\w+)>\s*\(", class_body):
event_name = em.group(1)
event_nid = _make_id(event_name)
add_node(event_nid, event_name, source_file=None)
add_edge(class_nid, event_nid, "calls", context="bloc_event",
line=_line_at(brace_pos + em.start(1)))
# Bloc state emissions: emit(MyState) or yield MyState
for sm in re.finditer(r"\b(?:emit|yield)\s*\(?\s*(?:const\s+)?([A-Z]\w*)\b", class_body):
state_name = sm.group(1)
if state_name not in {"String", "List", "Map", "Set", "Future", "Stream", "Object"}:
state_nid = _make_id(state_name)
add_node(state_nid, state_name, source_file=None)
add_edge(class_nid, state_nid, "calls", context="emit_state",
line=_line_at(brace_pos + sm.start(1)))
# Bloc event additions: widget.add(MyEvent()) or bloc.add(MyEvent())
for am in re.finditer(r"\b(?:\w*[Bb]loc\w*|context\.read<\w+>\(\))\.add\(\s*(?:const\s+)?([A-Z]\w*)\b", class_body):
event_name = am.group(1)
if event_name not in {"String", "List", "Map", "Set", "Future", "Stream", "Object"}:
event_nid = _make_id(event_name)
add_node(event_nid, event_name, source_file=None)
add_edge(class_nid, event_nid, "calls", context="bloc_add_event",
line=_line_at(brace_pos + am.start(1)))
# Riverpod provider references: ref.watch(provider)
for rm in re.finditer(r"\bref\.(?:watch|read|listen)\s*\(\s*(\w+)\b", class_body):
provider_name = rm.group(1)
provider_nid = _make_id(provider_name)
add_node(provider_nid, provider_name, source_file=None)
add_edge(class_nid, provider_nid, "references", context="riverpod_reference",
line=_line_at(brace_pos + rm.start(1)))
# Widget to Bloc references: BlocBuilder<MyBloc, ...>
for bm in re.finditer(r"\bBloc(?:Builder|Listener|Consumer|Provider|Selector)\s*<\s*([a-zA-Z0-9_]+)\b", class_body):
bloc_name = bm.group(1)
if bloc_name not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
bloc_nid = _make_id(bloc_name)
add_node(bloc_nid, bloc_name, source_file=None)
add_edge(class_nid, bloc_nid, "references", context="bloc_widget_binding",
line=_line_at(brace_pos + bm.start(1)))
# context.read<MyBloc>() or BlocProvider.of<MyBloc>(context)
for lm in re.finditer(r"\b(?:read|watch|select|of)\s*<([a-zA-Z0-9_]+)>", class_body):
bloc_name = lm.group(1)
if bloc_name not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
bloc_nid = _make_id(bloc_name)
add_node(bloc_nid, bloc_name, source_file=None)
add_edge(class_nid, bloc_nid, "references", context="bloc_lookup",
line=_line_at(brace_pos + lm.start(1)))
# 2. Annotations mapping (class, mixin, enum, or function level annotations)
# Support: @riverpod, @Riverpod(...), @injectable, @singleton, @RoutePage(), @HiveType(typeId: 0), @RestApi()
# Matches `@annotation` and links it to the next class/mixin/enum/function declaration in the file
annotation_pattern = r"@(\w+)(?:\([^)]*\))?"
for am in re.finditer(annotation_pattern, src_clean):
annotation_name = am.group(1)
if annotation_name in {"override", "deprecated", "required", "protected", "mustCallSuper"}:
continue
annotation_pos = am.end()
intervening_text = src_clean[annotation_pos : annotation_pos + 300]
class_m = re.search(r"^\s*(?:(?:abstract|sealed|base|interface|final|mixin)\s+)*(?:class|mixin|enum|extension\s+type)\s+(\w+)", intervening_text, re.MULTILINE)
func_m = re.search(r"^\s*(?:factory\s+|static\s+|async\s+|external\s+|abstract\s+)?(?:\([^)]+\)|[a-zA-Z0-9_<>,.?]+)(?:\s+[a-zA-Z0-9_<>,.?]+){0,3}\s+(\w+)\s*\(", intervening_text, re.MULTILINE)
target_nid = None
target_name = None
target_type = None
if class_m and func_m:
if class_m.start() < func_m.start():
target_name = class_m.group(1)
target_type = "class"
target_nid = _make_id(stem, target_name)
else:
target_name = func_m.group(1)
target_type = "function"
target_nid = _make_id(stem, target_name)
elif class_m:
target_name = class_m.group(1)
target_type = "class"
target_nid = _make_id(stem, target_name)
elif func_m:
target_name = func_m.group(1)
target_type = "function"
target_nid = _make_id(stem, target_name)
if target_nid and target_name:
actual_intervening = intervening_text[:min(class_m.start() if class_m else 300, func_m.start() if func_m else 300)]
if ";" not in actual_intervening and "}" not in actual_intervening and "{" not in actual_intervening:
annotation_line = _line_at(am.start(1))
annotation_nid = _make_id("annotation", annotation_name.lower())
add_node(annotation_nid, f"@{annotation_name}", ftype="concept", source_file=None)
add_edge(target_nid, annotation_nid, "configures", line=annotation_line)
# Riverpod specific provider generation mapping (supports camelCase class and functional providers)
if annotation_name.lower() == "riverpod":
if target_type == "class":
provider_name = target_name[0].lower() + target_name[1:] + "Provider" if len(target_name) > 1 else target_name.lower() + "Provider"
else:
provider_name = target_name + "Provider"
provider_nid = _make_id(provider_name)
add_node(provider_nid, provider_name, ftype="concept", source_file=str(path), line=annotation_line)
add_edge(target_nid, provider_nid, "defines", context="riverpod_provider", line=annotation_line)
# 2.5 Typedefs (Type Aliases)
typedef_pattern = r"^\s*typedef\s+(\w+)\s*(?:<[^>]+>)?\s*=\s*([a-zA-Z0-9_<>,.?\s]+);"
for m in re.finditer(typedef_pattern, src_clean, re.MULTILINE):
typedef_name = m.group(1)
typedef_line = _line_at(m.start(1))
target_type = m.group(2).split("<")[0].split(".")[-1].strip()
if target_type not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "List", "Map", "Set", "void", "Function"}:
typedef_nid = _make_id(stem, typedef_name)
add_node(typedef_nid, typedef_name, line=typedef_line)
add_edge(file_nid, typedef_nid, "defines", line=typedef_line)
target_nid = _make_id(target_type)
add_node(target_nid, target_type, source_file=None)
add_edge(typedef_nid, target_nid, "references", context="typedef", line=typedef_line)
# 3. Extensions (extension MyExt on MyClass)
ext_pattern = r"^\s{0,4}extension\s+(\w+)?(?:<[^>]+>)?\s+on\s+(\w+)"
for m in re.finditer(ext_pattern, src_clean, re.MULTILINE):
ext_name = m.group(1) or f"{stem}_anonymous_extension"
target_class = m.group(2)
ext_line = _line_at(m.start(2))
ext_nid = _make_id(stem, ext_name)
label = m.group(1) or f"Extension on {target_class}"
add_node(ext_nid, label, line=ext_line)
add_edge(file_nid, ext_nid, "defines", line=ext_line)
target_nid = _make_id(target_class)
add_node(target_nid, target_class, source_file=None)
add_edge(ext_nid, target_nid, "extends", line=ext_line)
# 4. Top-level and class-level variable declarations (generic variables, records, late, and destructuring)
# Restrict indentation to 0-2 spaces to avoid matching local variables inside functions or switch expressions
var_pattern = r"^\s{0,2}(?:late\s+)?(?:(?:final|const|var)\s+)?(?:\([^)]+\)\s+|([a-zA-Z0-9_<>,.?]+(?:\s+[a-zA-Z0-9_<>,.?]+){0,3})\s+)?(?:(\w+)|(?:\w+\s*)?\(([^)]+)\))\s*(?:=|$|;)"
for m in re.finditer(var_pattern, src_clean, re.MULTILINE):
var_type = m.group(1)
single_name = m.group(2)
destructured_names = m.group(3)
if not re.match(r"^\s*(?:late|final|const|var)\b", m.group(0)) and not var_type:
continue
if single_name:
if single_name not in {"if", "for", "while", "switch", "catch", "return"}:
var_line = _line_at(m.start(2))
var_nid = _make_id(stem, single_name)
add_node(var_nid, single_name, line=var_line)
add_edge(file_nid, var_nid, "defines", line=var_line)
if var_type and var_type not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "List", "Map", "Set", "void"}:
clean_type = var_type.split("<")[0].split(".")[-1].strip()
type_nid = _make_id(clean_type)
add_node(type_nid, clean_type, source_file=None)
add_edge(file_nid, type_nid, "references", context="variable_type", line=var_line)
elif destructured_names:
destructure_line = _line_at(m.start(3))
for name in [n.strip() for n in destructured_names.split(",") if n.strip()]:
if ":" in name:
name = name.split(":")[-1].strip()
if re.match(r"^[a-zA-Z_]\w*$", name) and not re.match(r"^[A-Z]", name):
if name not in {"if", "for", "while", "switch", "catch", "return"}:
var_nid = _make_id(stem, name)
add_node(var_nid, name, line=destructure_line)
add_edge(file_nid, var_nid, "defines", line=destructure_line)
# 5. Top-level and member functions/methods (supports typed/generic/record return types and Riverpod/Bloc references)
# Restrict indentation to 0-2 spaces to avoid matching nested local functions or methods inside multiline switch statements
method_pattern = r"^\s{0,2}(?:factory\s+|static\s+|async\s+|external\s+|abstract\s+)?(?:\([^)]+\)|[a-zA-Z0-9_<>,.?]+)(?:\s+[a-zA-Z0-9_<>,.?]+){0,3}\s+(\w+(?:\.\w+)?)\s*\("
for m in re.finditer(method_pattern, src_clean, re.MULTILINE):
raw_name = m.group(1)
name = raw_name.split(".")[-1]
if name in {"if", "for", "while", "switch", "catch", "return", "void", "dynamic", "final", "const", "get", "set"}:
continue
if re.match(r"^[A-Z]", name):
continue
method_line = _line_at(m.start(1))
nid = _make_id(stem, name)
add_node(nid, name, line=method_line)
add_edge(file_nid, nid, "defines", line=method_line)
# Get function body using matching brace to extract Riverpod reference patterns
start_idx = m.start()
brace_pos = src_clean.find("{", start_idx)
semi_pos = src_clean.find(";", start_idx)
arrow_pos = src_clean.find("=>", start_idx)
has_body = brace_pos != -1
if has_body and semi_pos != -1 and semi_pos < brace_pos:
has_body = False
if has_body and arrow_pos != -1 and arrow_pos < brace_pos:
has_body = False
if has_body:
end_pos = _find_matching_brace(src_clean, start_idx)
func_body = src_clean[brace_pos:end_pos]
# Extract Riverpod provider references: ref.watch(provider)
for rm in re.finditer(r"\bref\.(?:watch|read|listen)\s*\(\s*(\w+)\b", func_body):
provider_name = rm.group(1)
provider_nid = _make_id(provider_name)
add_node(provider_nid, provider_name, source_file=None)
add_edge(nid, provider_nid, "references", context="riverpod_reference",
line=_line_at(brace_pos + rm.start(1)))
# Extract Bloc event additions: widget.add(MyEvent()) or bloc.add(MyEvent())
for am in re.finditer(r"\b(?:\w*[Bb]loc\w*|context\.read<\w+>\(\))\.add\(\s*(?:const\s+)?([A-Z]\w*)\b", func_body):
event_name = am.group(1)
if event_name not in {"String", "List", "Map", "Set", "Future", "Stream", "Object"}:
event_nid = _make_id(event_name)
add_node(event_nid, event_name, source_file=None)
add_edge(nid, event_nid, "calls", context="bloc_add_event",
line=_line_at(brace_pos + am.start(1)))
# context.read<MyBloc>() or BlocProvider.of<MyBloc>(context)
for lm in re.finditer(r"\b(?:read|watch|select|of)\s*<([a-zA-Z0-9_]+)>", func_body):
bloc_name = lm.group(1)
if bloc_name not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
bloc_nid = _make_id(bloc_name)
add_node(bloc_nid, bloc_name, source_file=None)
add_edge(nid, bloc_nid, "references", context="bloc_lookup",
line=_line_at(brace_pos + lm.start(1)))
# Universal Navigation Patters (GoRouter, AutoRoute, Navigator)
for nm in re.finditer(r"\b(?:go|push|goNamed|pushNamed|replace|replaceNamed)\s*\(\s*(?:context\s*,\s*)?['\"]([a-zA-Z0-9_/?=&%-]+)['\"]", func_body):
route_path = nm.group(1)
route_nid = _make_id("route", route_path.replace("/", "_").replace("?", "_").replace("=", "_").replace("&", "_"))
add_node(route_nid, f"Route {route_path}", ftype="concept", source_file=None)
add_edge(nid, route_nid, "navigates", context="route_path",
line=_line_at(brace_pos + nm.start(1)))
for cm in re.finditer(r"\b(?:go|push|goNamed|pushNamed|replace|replaceNamed)\s*\(\s*(?:context\s*,\s*)?([A-Z][a-zA-Z0-9_]*\.[a-zA-Z0-9_]+)", func_body):
route_const = cm.group(1)
route_nid = _make_id("route", route_const.replace(".", "_"))
add_node(route_nid, route_const, ftype="concept", source_file=None)
add_edge(nid, route_nid, "navigates", context="route_const",
line=_line_at(brace_pos + cm.start(1)))
for om in re.finditer(r"\b(?:push|replace)\s*\(\s*(?:context\s*,\s*)?.*?\b([A-Z]\w*(?:Route|Screen|Page))\b", func_body):
route_class = om.group(1)
route_nid = _make_id(route_class)
add_node(route_nid, route_class, source_file=None)
add_edge(nid, route_nid, "navigates", context="route_object",
line=_line_at(brace_pos + om.start(1)))
# 6. Imports and Exports
for m in re.finditer(r"""^\s*import\s+['"]([^'"]+)['"]""", src_clean, re.MULTILINE):
pkg = m.group(1)
tgt_nid = _make_id(pkg)
add_node(tgt_nid, pkg, source_file=None)
add_edge(file_nid, tgt_nid, "imports", line=_line_at(m.start(1)))
for m in re.finditer(r"""^\s*export\s+['"]([^'"]+)['"]""", src_clean, re.MULTILINE):
pkg = m.group(1)
tgt_nid = _make_id(pkg)
add_node(tgt_nid, pkg, source_file=None)
add_edge(file_nid, tgt_nid, "exports", line=_line_at(m.start(1)))
# 7. Generic Invocations / Type Lookups (Universal Dependency Lookup)
# Matches any method call with type parameters: methodName<Type>() or object.methodName<Type>()
# Automatically extracts GetIt, Injectable, Riverpod, Provider, BlocProvider, and InheritedWidget type lookups!
generic_call_pattern = r"\b\w+<([a-zA-Z0-9_.]+(?:<[a-zA-Z0-9_.,\s<>]+>)?)\s*>\s*\("
type_blacklist = {"String", "int", "double", "bool", "num", "dynamic", "Object", "List", "Map", "Set", "Future", "Stream", "void"}
for m in re.finditer(generic_call_pattern, src_clean):
type_name = m.group(1).split(".")[-1].strip()
clean_name = type_name.split("<")[0].strip()
if clean_name not in type_blacklist:
target_nid = _make_id(clean_name)
add_node(target_nid, clean_name, source_file=None)
add_edge(file_nid, target_nid, "references", context="type_lookup",
line=_line_at(m.start(1)))
return {"nodes": nodes, "edges": edges}
+494
View File
@@ -0,0 +1,494 @@
"""Dm extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
from graphify.extractors.base import _file_stem, _make_id, _read_text
def extract_dm(path: Path) -> dict:
"""Extract types, procs, includes, and calls from a .dm/.dme file."""
try:
import tree_sitter_dm as tsdm
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-dm not installed"}
try:
language = Language(tsdm.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
function_bodies: list[tuple[str, Any, "str | None"]] = []
def add_node(nid: str, label: str, line: int) -> None:
if nid and nid not in seen_ids:
seen_ids.add(nid)
nodes.append({"id": nid, "label": label, "file_type": "code",
"source_file": str_path, "source_location": f"L{line}"})
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0,
context: str | None = None) -> None:
if not src or not tgt or src == tgt:
return
edge: dict = {"source": src, "target": tgt, "relation": relation,
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight}
if context:
edge["context"] = context
edges.append(edge)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def _type_path_text(node) -> str:
return _read_text(node, source).strip()
def _ensure_type(path_text: str, line: int) -> str:
nid = _make_id(stem, path_text)
add_node(nid, path_text, line)
return nid
def _find_child(node, type_name: str):
for c in node.children:
if c.type == type_name:
return c
return None
def _read_include_path(file_node) -> str:
if file_node is None:
return ""
if file_node.type == "string_literal":
parts = []
for c in file_node.children:
if c.type == "string_content":
parts.append(_read_text(c, source))
return "".join(parts)
return _read_text(file_node, source).strip("'\"")
def walk(node, parent_type_path: "str | None" = None,
parent_type_nid: "str | None" = None) -> None:
t = node.type
line = node.start_point[0] + 1
if t == "preproc_include":
file_node = node.child_by_field_name("file")
raw = _read_include_path(file_node)
if raw:
norm = re.sub(r"^\./", "", raw.replace("\\", "/"))
resolved = (path.parent / norm).resolve()
edge: dict = {
"source": file_nid,
"target": _make_id(str(resolved)) if resolved.exists() else _make_id(norm),
"relation": "imports_from" if resolved.exists() else "imports",
"context": "import",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
}
if not resolved.exists():
edge["external"] = True
edges.append(edge)
return
if t == "type_definition":
tp_node = _find_child(node, "type_path")
if tp_node is None:
return
type_path_str = _type_path_text(tp_node)
type_nid = _ensure_type(type_path_str, line)
add_edge(file_nid, type_nid, "contains", line)
body = _find_child(node, "type_body")
if body is not None:
for c in body.children:
walk(c, parent_type_path=type_path_str, parent_type_nid=type_nid)
return
if t in ("type_body_intended", "type_body_braced"):
for c in node.children:
walk(c, parent_type_path, parent_type_nid)
return
if t in ("type_proc_definition", "type_proc_override"):
if parent_type_nid is None or parent_type_path is None:
return
name_node = node.child_by_field_name("name")
if name_node is None:
return
proc_name = _read_text(name_node, source)
proc_nid = _make_id(stem, parent_type_path, proc_name)
add_node(proc_nid, f"{parent_type_path}/{proc_name}()", line)
add_edge(parent_type_nid, proc_nid, "method", line)
block = _find_child(node, "block")
if block is not None:
function_bodies.append((proc_nid, block, parent_type_path))
return
if t in ("proc_definition", "proc_override"):
tp_node = _find_child(node, "type_path")
owner_path: "str | None" = None
owner_nid: "str | None" = None
if tp_node is not None:
owner_path = _type_path_text(tp_node)
owner_nid = _ensure_type(owner_path, line)
add_edge(file_nid, owner_nid, "contains", line)
name_node = node.child_by_field_name("name")
if name_node is None:
return
proc_name = _read_text(name_node, source)
if owner_path and owner_nid:
proc_nid = _make_id(stem, owner_path, proc_name)
add_node(proc_nid, f"{owner_path}/{proc_name}()", line)
add_edge(owner_nid, proc_nid, "method", line)
else:
proc_nid = _make_id(stem, proc_name)
add_node(proc_nid, f"{proc_name}()", line)
add_edge(file_nid, proc_nid, "contains", line)
block = _find_child(node, "block")
if block is not None:
function_bodies.append((proc_nid, block, owner_path))
return
if t in ("operator_override", "type_operator_override"):
return
for child in node.children:
walk(child, parent_type_path, parent_type_nid)
walk(root)
label_to_nids: dict[str, list[str]] = {}
path_to_nids: dict[str, list[str]] = {}
for n in nodes:
label = n["label"].strip("()")
last = label.rsplit("/", 1)[-1] if "/" in label else label
if last:
label_to_nids.setdefault(last.lower(), []).append(n["id"])
if label.startswith("/"):
path_to_nids.setdefault(label.lower(), []).append(n["id"])
seen_call_pairs: set[tuple[str, str]] = set()
raw_calls: list[dict] = []
def _emit_call(caller_nid: str, callee: str, line: int, is_member: bool) -> None:
candidates = label_to_nids.get(callee.lower(), [])
tgt_nid = candidates[0] if len(candidates) == 1 else None
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair in seen_call_pairs:
return
seen_call_pairs.add(pair)
edges.append({
"source": caller_nid, "target": tgt_nid, "relation": "calls",
"context": "call", "confidence": "EXTRACTED",
"source_file": str_path, "source_location": f"L{line}", "weight": 1.0,
})
else:
raw_calls.append({
"caller_nid": caller_nid, "callee": callee,
"is_member_call": is_member, "source_file": str_path,
"source_location": f"L{line}",
})
def walk_calls(body_node, caller_nid: str) -> None:
if body_node is None:
return
t = body_node.type
if t in ("proc_definition", "proc_override", "type_proc_definition",
"type_proc_override", "type_definition"):
return
if t == "call_expression":
name_node = body_node.child_by_field_name("name")
if name_node is not None:
callee = _read_text(name_node, source)
if callee and callee != "..":
_emit_call(caller_nid, callee, body_node.start_point[0] + 1,
is_member=False)
elif t == "field_proc_expression":
proc_field = body_node.child_by_field_name("proc")
if proc_field is not None:
callee = _read_text(proc_field, source)
if callee:
_emit_call(caller_nid, callee, body_node.start_point[0] + 1,
is_member=True)
elif t == "new_expression":
tp_node = _find_child(body_node, "type_path")
if tp_node is not None:
target_text = _type_path_text(tp_node)
candidates = path_to_nids.get(target_text.lower(), [])
tgt_nid = candidates[0] if len(candidates) == 1 else None
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
seen_call_pairs.add(pair)
edges.append({
"source": caller_nid, "target": tgt_nid,
"relation": "instantiates", "context": "call",
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{body_node.start_point[0] + 1}",
"weight": 1.0,
})
for child in body_node.children:
walk_calls(child, caller_nid)
for proc_nid, block, _owner_path in function_bodies:
walk_calls(block, proc_nid)
return {"nodes": nodes, "edges": edges, "raw_calls": raw_calls}
def _read_dmi_description(data: bytes) -> str:
"""Pull the BYOND metadata text out of a .dmi PNG, or empty string on failure."""
import struct
import zlib as _zlib
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
return ""
i = 8
while i + 8 <= len(data):
length = struct.unpack(">I", data[i:i + 4])[0]
chunk_type = data[i + 4:i + 8]
payload = data[i + 8:i + 8 + length]
if chunk_type in (b"tEXt", b"zTXt"):
try:
null = payload.index(b"\x00")
except ValueError:
return ""
keyword = payload[:null]
if keyword == b"Description":
if chunk_type == b"zTXt":
return _zlib.decompressobj().decompress(payload[null + 2:], max_length=1024 * 1024).decode("utf-8", errors="replace")
return payload[null + 1:].decode("utf-8", errors="replace")
i += 8 + length + 4
return ""
def extract_dmi(path: Path) -> dict:
"""Extract icon state names from a .dmi (BYOND PNG icon sheet)."""
try:
data = path.read_bytes()
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
str_path = str(path)
stem = _file_stem(path)
file_nid = _make_id(str(path))
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str_path, "source_location": "L1"}]
edges: list[dict] = []
seen: set[str] = {file_nid}
description = _read_dmi_description(data)
if not description:
return {"nodes": nodes, "edges": edges}
line_no = 0
for raw_line in description.splitlines():
line_no += 1
stripped = raw_line.strip()
if not stripped.startswith("state ="):
continue
value = stripped.split("=", 1)[1].strip()
if value.startswith('"') and value.endswith('"') and len(value) >= 2:
state_name = value[1:-1]
else:
state_name = value
if not state_name:
continue
nid = _make_id(stem, "state", state_name)
if nid in seen:
continue
seen.add(nid)
nodes.append({"id": nid, "label": f'"{state_name}"', "file_type": "code",
"source_file": str_path, "source_location": f"L{line_no}"})
edges.append({"source": file_nid, "target": nid, "relation": "contains",
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line_no}", "weight": 1.0})
return {"nodes": nodes, "edges": edges}
_DMM_GRID_RE = re.compile(r"^\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)\s*=", re.MULTILINE)
def _split_dmm_tile(body: str) -> list[str]:
out: list[str] = []
buf: list[str] = []
depth = 0
in_string = False
escape = False
for ch in body:
if escape:
buf.append(ch)
escape = False
continue
if in_string:
buf.append(ch)
if ch == "\\":
escape = True
elif ch == '"':
in_string = False
continue
if ch == '"':
in_string = True
buf.append(ch)
elif ch in "({[":
depth += 1
buf.append(ch)
elif ch in ")}]":
depth -= 1
buf.append(ch)
elif ch == "," and depth == 0:
out.append("".join(buf).strip())
buf = []
else:
buf.append(ch)
tail = "".join(buf).strip()
if tail:
out.append(tail)
return out
def _dmm_type_path(entry: str) -> str:
brace = entry.find("{")
if brace != -1:
entry = entry[:brace]
return entry.strip()
def extract_dmm(path: Path) -> dict:
"""Extract type-path references from a .dmm map file's tile dictionary."""
try:
if path.stat().st_size > 50 * 1024 * 1024:
return {"nodes": [], "edges": [], "error": "file too large (>50 MB)"}
text = path.read_text(encoding="utf-8", errors="replace")
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
str_path = str(path)
file_nid = _make_id(str(path))
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str_path, "source_location": "L1"}]
edges: list[dict] = []
grid_match = _DMM_GRID_RE.search(text)
dict_text = text[:grid_match.start()] if grid_match else text
seen_targets: set[str] = set()
buf: list[str] = []
open_line = 0
depth = 0
in_string = False
escape = False
for line_idx, line in enumerate(dict_text.splitlines(), start=1):
for ch in line:
if escape:
escape = False
elif in_string:
if ch == "\\":
escape = True
elif ch == '"':
in_string = False
elif ch == '"':
in_string = True
elif ch == "(":
if depth == 0:
open_line = line_idx
depth += 1
elif ch == ")":
depth -= 1
buf.append(ch)
buf.append("\n")
if depth == 0 and buf:
chunk = "".join(buf)
buf = []
lp = chunk.find("(")
rp = chunk.rfind(")")
if lp == -1 or rp == -1 or rp <= lp:
continue
inner = chunk[lp + 1:rp]
for entry in _split_dmm_tile(inner):
tpath = _dmm_type_path(entry)
if not tpath.startswith("/"):
continue
tgt = _make_id(tpath)
if tgt in seen_targets:
continue
seen_targets.add(tgt)
edges.append({"source": file_nid, "target": tgt, "relation": "uses",
"context": "map", "confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{open_line}", "weight": 1.0})
return {"nodes": nodes, "edges": edges}
_DMF_WINDOW_RE = re.compile(r'^\s*window\s+"([^"]+)"\s*$')
_DMF_ELEM_RE = re.compile(r'^\s*elem\s+"([^"]+)"\s*$')
_DMF_TYPE_RE = re.compile(r'^\s*type\s*=\s*(\S+)\s*$')
def extract_dmf(path: Path) -> dict:
"""Extract windows and controls from a .dmf interface file."""
try:
text = path.read_text(encoding="utf-8", errors="replace")
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
str_path = str(path)
stem = _file_stem(path)
file_nid = _make_id(str(path))
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str_path, "source_location": "L1"}]
edges: list[dict] = []
seen: set[str] = {file_nid}
current_window_nid: str | None = None
current_elem_nid: str | None = None
current_elem_name: str | None = None
for line_idx, line in enumerate(text.splitlines(), start=1):
m = _DMF_WINDOW_RE.match(line)
if m:
name = m.group(1)
nid = _make_id(stem, "window", name)
if nid not in seen:
seen.add(nid)
nodes.append({"id": nid, "label": f'window "{name}"', "file_type": "code",
"source_file": str_path, "source_location": f"L{line_idx}"})
edges.append({"source": file_nid, "target": nid, "relation": "contains",
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line_idx}", "weight": 1.0})
current_window_nid = nid
current_elem_nid = None
current_elem_name = None
continue
m = _DMF_ELEM_RE.match(line)
if m and current_window_nid is not None:
name = m.group(1)
nid = _make_id(stem, "elem", current_window_nid, name)
if nid not in seen:
seen.add(nid)
nodes.append({"id": nid, "label": f'elem "{name}"', "file_type": "code",
"source_file": str_path, "source_location": f"L{line_idx}"})
edges.append({"source": current_window_nid, "target": nid,
"relation": "contains", "confidence": "EXTRACTED",
"source_file": str_path, "source_location": f"L{line_idx}",
"weight": 1.0})
current_elem_nid = nid
current_elem_name = name
continue
m = _DMF_TYPE_RE.match(line)
if m and current_elem_nid is not None and current_elem_name is not None:
ctype = m.group(1)
for n in nodes:
if n["id"] == current_elem_nid and " [" not in n["label"]:
n["label"] = f'elem "{current_elem_name}" [{ctype}]'
break
return {"nodes": nodes, "edges": edges}
+309
View File
@@ -0,0 +1,309 @@
"""Elixir extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS, _file_stem, _make_id
def extract_elixir(path: Path) -> dict:
"""Extract modules, functions, imports, and calls from a .ex/.exs file."""
try:
import tree_sitter_elixir as tselixir
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree_sitter_elixir not installed"}
try:
language = Language(tselixir.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
function_bodies: list[tuple[str, Any]] = []
def add_node(nid: str, label: str, line: int, **attrs) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
node = {"id": nid, "label": label, "file_type": "code",
"source_file": str_path, "source_location": f"L{line}"}
node.update(attrs)
nodes.append(node)
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0,
context: str | None = None) -> None:
edge = {"source": src, "target": tgt, "relation": relation,
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight}
if context:
edge["context"] = context
edges.append(edge)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
_IMPORT_KEYWORDS = frozenset({"alias", "import", "require", "use"})
def _get_alias_text(node) -> str | None:
for child in node.children:
if child.type == "alias":
return source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
return None
def _get_alias_modules(node) -> list[str]:
"""Every module named by an alias/import/require/use argument.
Handles the single form (``alias Foo.Bar`` -> ``["Foo.Bar"]``) and the
multi-alias brace form (``alias Foo.{Bar, Baz}`` ->
``["Foo.Bar", "Foo.Baz"]``), which the grammar represents as a ``dot``
node holding the base alias and a trailing ``tuple`` of member aliases.
"""
def _text(n) -> str:
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
for child in node.children:
if child.type == "alias":
return [_text(child)]
if child.type == "dot":
base = None
tuple_node = None
for sub in child.children:
if sub.type == "alias" and base is None:
base = _text(sub)
elif sub.type == "tuple":
tuple_node = sub
if base and tuple_node is not None:
members = [_text(m) for m in tuple_node.children if m.type == "alias"]
if members:
return [f"{base}.{m}" for m in members]
return [_text(child)]
return []
def _get_defimpl_target(node) -> str | None:
"""The `for:` target module of a `defimpl Proto, for: Type` argument
list. The grammar holds it in a trailing `keywords` node as a `pair`
whose keyword is `for:` and whose value is an `alias`."""
for child in node.children:
if child.type != "keywords":
continue
for pair in child.children:
if pair.type != "pair":
continue
kw = None
val = None
for sub in pair.children:
if sub.type == "keyword":
kw = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
elif sub.type == "alias":
val = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
if kw and kw.rstrip(": ").strip() == "for" and val:
return val
return None
def walk(node, parent_module_nid: str | None = None) -> None:
if node.type != "call":
for child in node.children:
walk(child, parent_module_nid)
return
identifier_node = None
arguments_node = None
do_block_node = None
for child in node.children:
if child.type == "identifier":
identifier_node = child
elif child.type == "arguments":
arguments_node = child
elif child.type == "do_block":
do_block_node = child
if identifier_node is None:
for child in node.children:
walk(child, parent_module_nid)
return
keyword = source[identifier_node.start_byte:identifier_node.end_byte].decode("utf-8", errors="replace")
line = node.start_point[0] + 1
if keyword == "defmodule":
module_name = _get_alias_text(arguments_node) if arguments_node else None
if not module_name:
return
module_nid = _make_id(stem, module_name)
# Only a top-level module is a safe cross-file resolution target
# (#3603 follow-up): a nested `defmodule Supervisor` is labeled with
# its bare inner name and would otherwise capture an unrelated
# `use Supervisor` from another file. Mark just the top-level ones;
# the marker rides through incremental rebuilds via the
# resolution-context allow-list in watch.py / cli.py.
add_node(module_nid, module_name, line,
**({"_elixir_module": True} if parent_module_nid is None else {}))
add_edge(file_nid, module_nid, "contains", line)
if do_block_node:
for child in do_block_node.children:
walk(child, parent_module_nid=module_nid)
return
if keyword == "defprotocol":
# A protocol is a module-like named container. Without this branch
# the `defprotocol` call fell through to the generic recursion with
# parent_module_nid=None, so the protocol node was never minted and
# its callbacks (`def size(data)`) were attached to the FILE instead
# of the protocol.
proto_name = _get_alias_text(arguments_node) if arguments_node else None
if not proto_name:
return
proto_nid = _make_id(stem, proto_name)
add_node(proto_nid, proto_name, line,
**({"_elixir_module": True} if parent_module_nid is None else {}))
add_edge(parent_module_nid or file_nid, proto_nid, "contains", line)
if do_block_node:
for child in do_block_node.children:
walk(child, parent_module_nid=proto_nid)
return
if keyword == "defimpl":
# `defimpl Proto, for: Type do ... end`. Same orphaning bug as
# defprotocol: the implementation's functions leaked onto the file.
proto_name = _get_alias_text(arguments_node) if arguments_node else None
if not proto_name:
return
target = _get_defimpl_target(arguments_node)
impl_nid = _make_id(stem, "defimpl", proto_name, target or "")
label = f"{proto_name} (for {target})" if target else proto_name
add_node(impl_nid, label, line)
add_edge(parent_module_nid or file_nid, impl_nid, "contains", line)
# Link the implementation to the protocol it satisfies. A same-file
# protocol resolves directly; a cross-file target is filtered out by
# the dangling-edge guard below rather than left hanging.
add_edge(impl_nid, _make_id(stem, proto_name), "implements", line)
if do_block_node:
for child in do_block_node.children:
walk(child, parent_module_nid=impl_nid)
return
if keyword in ("def", "defp"):
func_name = None
if arguments_node:
for child in arguments_node.children:
# tree-sitter-elixir wraps a guarded head
# (`def f(x) when guard`) in `binary_operator`;
# without unwrapping, a function whose only clause
# carries `when` is dropped (#3111).
while child.type == "binary_operator":
head = None
for sub in child.children:
if sub.type in ("call", "identifier", "binary_operator"):
head = sub
break
if head is None:
break
child = head
if child.type == "call":
for sub in child.children:
if sub.type == "identifier":
func_name = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
break
elif child.type == "identifier":
func_name = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
break
if not func_name:
return
container = parent_module_nid or file_nid
func_nid = _make_id(container, func_name)
add_node(func_nid, f"{func_name}()", line)
if parent_module_nid:
add_edge(parent_module_nid, func_nid, "method", line)
else:
add_edge(file_nid, func_nid, "contains", line)
if do_block_node:
function_bodies.append((func_nid, do_block_node))
return
if keyword in _IMPORT_KEYWORDS and arguments_node:
for module_name in _get_alias_modules(arguments_node):
tgt_nid = _make_id(module_name)
add_edge(file_nid, tgt_nid, "imports", line, context="import")
return
for child in node.children:
walk(child, parent_module_nid)
walk(root)
label_to_nid: dict[str, str] = {}
for n in nodes:
normalised = n["label"].strip("()").lstrip(".")
label_to_nid[normalised] = n["id"]
seen_call_pairs: set[tuple[str, str]] = set()
raw_calls: list[dict] = []
_SKIP_KEYWORDS = frozenset({
"def", "defp", "defmodule", "defmacro", "defmacrop",
"defstruct", "defprotocol", "defimpl", "defguard",
"alias", "import", "require", "use",
"if", "unless", "case", "cond", "with", "for",
})
def walk_calls(node, caller_nid: str) -> None:
if node.type != "call":
for child in node.children:
walk_calls(child, caller_nid)
return
for child in node.children:
if child.type == "identifier":
kw = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
if kw in _SKIP_KEYWORDS:
for c in node.children:
walk_calls(c, caller_nid)
return
break
callee_name: str | None = None
is_member_call: bool = False
for child in node.children:
if child.type == "dot":
is_member_call = True
dot_text = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
parts = dot_text.rstrip(".").split(".")
if parts:
callee_name = parts[-1]
break
if child.type == "identifier":
callee_name = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
break
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
tgt_nid = label_to_nid.get(callee_name)
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
seen_call_pairs.add(pair)
add_edge(caller_nid, tgt_nid, "calls",
node.start_point[0] + 1, confidence="EXTRACTED", weight=1.0,
context="call")
else:
raw_calls.append({
"caller_nid": caller_nid,
"callee": callee_name,
"is_member_call": is_member_call,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
for child in node.children:
walk_calls(child, caller_nid)
for caller_nid, body in function_bodies:
walk_calls(body, caller_nid)
clean_edges = [e for e in edges if e["source"] in seen_ids and
(e["target"] in seen_ids or e["relation"] == "imports")]
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls, "input_tokens": 0, "output_tokens": 0}
File diff suppressed because it is too large. Load diff
Loaded 100 of 755 files, more files were not shown because too many files have changed in this diff. Show more