Compare commits

...
485 Commits
Author SHA1 Message Date
safishamsiandClaude Opus 4.8 5eedffa874 chore(release): bump version to 0.9.105
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 16:49:51 +00:00
safishamsiandClaude Opus 4.8 4067e31a88 docs(changelog): add the export/build/llm/perf/skillgen/deps/markdown/csharp batch to 0.9.105
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 16:47:24 +00:00
safishamsiandClaude Opus 4.8 6021290cf2 chore(cache): combine the schema-42 bump for markdown (#4806) and csharp (#4849)
Both change per-file extractor output (Markdown bare free-function mention
citation; C# extension-method facts + primitive receiver typing) and land in one
release window, so they share a single bump to 42 chained over prior (41).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 16:46:54 +00:00
Deepjyoti-Sarmah acae154d4c fix(csharp): use the 0.75 discrete tier for guarded extension edges (#4828)
The INFERRED rubric is {0.55, 0.65, 0.75, 0.85, 0.95}; the guarded rungs were
emitting 0.70, which test_inferred_confidence_rubric rejects (and which the
rubric has no tier for). 0.75 is the intended one-step-below-0.85 score.

(cherry picked from commit 27c01196ab)
2026-11-09 16:46:28 +00:00
Deepjyoti-Sarmah 7058cbd612 test(csharp): score candidates against the production BCL deny-list (#4828)
The A/B record imported a second copy of the deny-list, so the comparison could
silently stop describing the rule the fix applies. Use one source of truth.

(cherry picked from commit d49009e351)
2026-11-09 16:46:28 +00:00
Deepjyoti-Sarmah b824c815d2 feat(csharp): bind extension calls on chained receivers (#4828)
Closes the last shape in the report: `v.ToString().Mask()`. The receiver of the
outer call is the result of an inner call, so it carries no type at all, and
typing it would need BCL return types the corpus does not know.

The untyped rung therefore applies the same two name proofs the out-of-corpus
rung uses — the name is not a BCL member, and no regular method in the corpus
spells it — with no type-compatibility filter, and requires a unique surviving
declaration. A capitalized untyped receiver is a type named in source
(`Convert.ToInt32(x)`), never a value an extension applies to, so it is skipped.

This is the weakest rung and it is scored accordingly: INFERRED 0.70. The cost is
pinned by a fixture where a regular method elsewhere shares the name: the call
stays unbound rather than risking a false edge.

With all three rungs the reporter's corpus now matches the expected output:

  Connections (3):
    <-- StringExtensions [method] [EXTRACTED] Ext.cs:L3
    <-- .A() [calls] [INFERRED] Svc.cs:L3
    <-- .B() [calls] [INFERRED] Svc.cs:L4

Refs #4828

(cherry picked from commit 99d2834910)
2026-11-09 16:46:28 +00:00
Deepjyoti-Sarmah 8f4317704a feat(csharp): bind extension calls on primitive and third-party receivers (#4828)
Stage 1 deliberately refused a receiver whose type the corpus never declares,
which left the issue's headline case unbound: `s.Mask()` on a `string`, and the
same shape for `int` and any third-party type.

An undeclared type cannot have its instance members enumerated, so the
instance-wins rule cannot be applied. Two conservative proofs replace it:

  * the member name is not one a BCL type owns (`ToString`, `GetValue`, `Split`,
    ...), because those calls are instance calls on the real runtime type; and
  * no regular (non-extension) method anywhere in the corpus spells that name, so
    an in-corpus type cannot legitimately own it either.

A `this T` / `this object` declaration is subject to the same guard and still
applies only when no exact or base/interface match exists. These edges are
INFERRED 0.70, one discrete tier below a receiver typed by the extractor's
declaration table, so a query can tell the two proofs apart.

The reported false negative this cannot reach — `string.ToInt32()` when an
unrelated static class also declares `ToInt32` — is pinned as a documented miss
in the ground-truth fixtures rather than papered over.

Refs #4828

(cherry picked from commit f80468a01b)
2026-11-09 16:46:28 +00:00
Deepjyoti-Sarmah 637e9c6d8e feat(csharp): bind extension calls on typed receivers (#4828)
`value.Mask()` to a classic `this`-parameter extension produced no `calls`
edge: `_resolve_csharp_member_calls` types the receiver and looks the method up
on the receiver's type, but an extension is declared on a static class, so the
lookup found nothing and the call was dropped. The helper looked dead.

New `csharp_extension_calls` resolver, registered after the nominal pass, joins
a call site to the declaration its `this` parameter names. This first stage
binds only provable calls:

  * the receiver's declared type is declared in the corpus and its base chain is
    fully resolved — an out-of-corpus base may declare an instance member of
    that name, and an instance member always wins over an extension;
  * the receiver type declares no instance member of that name;
  * the declaring static class's namespace is visible at the call site, walked
    innermost namespace declaration outward (`CsharpNameResolver
    .visible_namespaces`), so a file-level using is only considered at the
    compilation-unit level and an inner-namespace extension wins;
  * the extended type is the receiver's type, a resolved base, or an implemented
    interface; an open generic `this T` / `this object` declaration applies only
    when no exact or base match exists;
  * the declaration accepts the call's argument count, reusing the arity /
    min_arity facts from #4584 (the receiver is one parameter short of the call);
  * exactly one declaration survives; a tie binds nothing.

Edges are INFERRED 0.85 (the receiver type comes from the extractor's declaration
table), sourced at the call site.

The tests pair the implementation with an executable A/B record: 15 fixtures
whose ground truth is decidable from the C# spec, and 10 candidate strategies
measured on the nominal graph (production resolver disabled for extraction). The
matrix test pins the trades that were measured rather than assumed — no scope
check binds an unimported extension, no poison binds through an unknown base, no
deny-list binds `PropertyInfo.GetValue`, and the bare-name fallback reproduces
the #1609 god-node edge. The production pass is asserted against the same ground
truth in test_csharp_extension_resolution.py.

Refs #4828

(cherry picked from commit a83cc6c0e3)
2026-11-09 16:46:28 +00:00
Deepjyoti-Sarmah 5bfb4241d8 fix(csharp): record extension-method facts and primitive receiver types (#4828)
A call to a classic `this`-parameter extension method produced no `calls`
edge: the member-call resolver looks the method up on the receiver's declared
type, while an extension is declared on a static class. Two facts were missing
before any resolver could join them.

The extractor now persists, on the extension method's node:

  extension: true
  extended_type: <simple name of the `this` parameter's type>
  extended_type_arity: <generic arity of that type>
  extended_is_type_param: true for `this T`

`_csharp_method_signature` already detected the `this` modifier, but only used
it to compute `min_arity`; the extended type is the join key a call site needs
and is recorded where the declaration is still at hand. The type is the same
simple name a receiver is stamped with (`_read_csharp_type_name` strips the
namespace qualifier and generic arguments), so qualified `this App.Widget` and
generic `this Box<int>` are comparable with `receiver_type`.

`_csharp_receiver_type_name` no longer drops every lowercase type: predefined
primitives are not declared in the corpus, but `this string` dispatches on
exactly that name, so filtering them made those calls untypeable before the
extension pass could ever see them. The parking path is guarded in exchange:
`_park_if_absent` does not park a well-known BCL receiver name as a cross-repo
candidate, so `x.ToString()` on an `int` no longer stamps an `unresolved_calls`
payload on the caller.

AST cache schema 29 -> 30: cached `.cs` extractions lack the new facts.

Refs #4828

(cherry picked from commit 6a15bfefab)
2026-11-09 16:46:28 +00:00
Lalit Madan 7b1d14489f test(markdown): isolate rebuild tests in a subprocess
The cache stat index and active scan root are process globals; in the full
suite a prior test's root can be served to a later rebuild and drop the
resolver-minted reference edges. Running each rebuild scenario in a fresh
interpreter gives the test the clean slate it has in isolation.

(cherry picked from commit d559ea232d)
2026-11-09 16:45:48 +00:00
Lalit Madan 1c74ae85af fix(markdown): resolve reference-style links to their uses (#4806)
(cherry picked from commit 814ae07bd8)
2026-11-09 16:45:48 +00:00
Lalit Madan b77380be5c fix(markdown): a bare free function name needs its file cited (#4804)
`resolve_markdown_mentions` linked bare code spans like `token` or `raw`
to unrelated free functions carrying the same label across languages.

Require section-scoped evidence for bare prose-like free function names:
- Keep a bare free-function mention only if the section cites the defining
  file (via a code span, file link, or path qualification) or cites another
  symbol from that file (#4804).
- Exempt distinct code identifiers (snake_case, camelCase, or PascalCase
  in export-by-convention languages).
- Extract source-file links as file citations, scoped to enclosing headings
  as evidence owners, minting doc->file references only for scanned files.
- Resolve inline Markdown links strictly against document-relative targets,
  and reject mixed-form citations escaping the scan root.
- Reconcile doc->file citations in watch rebuilds and bump AST cache schema.

(cherry picked from commit 638ab3ec18)
2026-11-09 16:45:48 +00:00
safishamsiandClaude Opus 4.8 130e072b8d fix(deps): raise the pypdf floor to 6.21.4 and refresh the lock (#5015)
Picks up the pypdf 6.21.3/6.21.4 security fixes in both the pdf and all extras.
Regenerated uv.lock on current v8 so the graphifyy self-entry reads 0.9.104 and
the pypdf bump lands on a clean lock (the PR's lock carried a stale self-version
from its fork). pdf extraction tests pass on 6.21.4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 16:45:30 +00:00
yotamleo 41f82c11a6 fix(deps): raise the pypdf floor to 6.21.4
pypdf 6.21.2 in uv.lock is affected by seven advisories (GHSA-42gh-23hr-vphw,
GHSA-4vqv-7265-gm2w, GHSA-5849-834g-hvw5, GHSA-62m5-6wh8-28x7,
GHSA-cggf-277g-3q54, GHSA-mfr5-77xh-9j7h, GHSA-x3rh-gjgm-fmqc), fixed in
6.21.3 and 6.21.4. Raise the floor in the pdf and all extras and refresh the lock
with uv lock --upgrade-package pypdf (6.21.2 to 6.21.4).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 99aa336ab3)
2026-11-09 16:45:14 +00:00
safishamsiandClaude Opus 4.8 caa6a0783b fix(llm): keep .yaml/.yml out of the splittable-document set (#5078 follow-up)
The doc-bisect fix added .yaml/.yml to _SPLITTABLE_TEXT_SUFFIXES, but those are
code, not documents (reclassified document->code in #2214), and never reach the
semantic pass, so slicing them at prose boundaries is meaningless. Drop the two
suffixes and their test parametrization; the core truncation-bisect fix stands.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 16:45:05 +00:00
thanhsonvoice 76a80a838c fix(skillgen): tell claw/kiro/pi subagents to write their chunk to CHUNK_PATH
claw, kiro and pi dispatch semantic subagents with a CHUNK_PATH and expect
each to write its chunk file there, but they shipped the compact extraction
spec, which never names CHUNK_PATH. A subagent following that prompt
verbatim returned its JSON inline, so Step B3 found no chunk file and
reported the chunk as missing.

Add a compact-disk spec variant (the compact prompt plus the CHUNK_PATH
substitution and write step) and switch claw, kiro and pi to it. Codex keeps
the plain compact spec: its workers return JSON inline and the orchestrator
writes the chunk files.

Add a regression test: every host whose dispatch passes CHUNK_PATH gets a
spec that writes to it, and the inline-JSON host (codex) does not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit b26a79372d)
2026-11-09 16:44:15 +00:00
marq 4e781ef8bc fix(llm): bisect splittable documents below char cap on output truncation (#5072)
(cherry picked from commit 3d06d10849)
2026-11-09 16:44:15 +00:00
dherreraj 91cc31b05f feat(llm): forward a custom provider's extra_headers as default_headers (#3680)
providers.json can already override request body fields with
`extra_body`, but not headers, and some OpenAI-compatible gateways
require one: OpenCode Go rejects any request without
`x-opencode-session` (400 MissingSessionID). The only workaround was
the SDK-global OPENAI_CUSTOM_HEADERS env var.

Accept an optional `extra_headers` object on a provider entry and pass
it to the OpenAI client as `default_headers` at both construction
sites, extraction (`_call_openai_compat`) and `_call_llm` (labeling and
the --dedup-llm tiebreaker). Only string-to-string entries are kept,
and an Authorization entry is dropped with a warning, so the API key
still always comes from the provider's env_key. Without the field, the
client is built exactly as before.

(cherry picked from commit 82b48065ac)
2026-11-09 16:44:06 +00:00
tpateeq eb9468a906 perf(extract): free whole-graph intermediates early to cut peak RAM
graphify extract kept several full copies of the graph alive after they
were consumed. Release each one as soon as it is used, without changing
call order or output (graph.json is byte-identical):

- extract(): new opt-in release_parse_memo clears the Python parse memo
  once both resolution passes finish; the CLI sets it, watch/MCP/library
  callers keep the warm memo as before.
- extract CLI: drop the parsed previous graph.json once the resolution
  context is built, the context after AST extraction, and the raw
  AST/semantic/merged lists once G is built.
- to_json: canonicalize node/link dicts in place, and free the shrink
  guard copies and the previous-graph parse before writing.
- cluster._partition: drop the sorted edge rows once stable is built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015ykSAxiohPs7ei9m9DasUD
(cherry picked from commit 3892aea30b)
2026-11-09 16:44:06 +00:00
Khaled Ali 2643077a22 fix(export): don't count replaced or pruned sources as lost in the write guard
to_json passed an empty deleted_sources to _lost_saved_semantic_nodes, so
the old ids of every doc build_merge re-extracted this run (LLM ids are not
stable) were reported as lost whenever the guard was armed, e.g. by an
omitted file. build_merge now stashes the saved sources it replaced
(semantic tier) or pruned on G.graph, and to_json pops it and excuses them.
Sources with an unverified shrink (#3203) and untouched files stay guarded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit ec964ea137)
2026-11-09 16:44:05 +00:00
sdivyanshu90 b327203c30 fix(build): tolerate structured enum fields
Report malformed enum values without hashing them, and use conservative builder fallbacks so one structured field cannot abort a usable extraction.

Refs #5086

Co-authored-by: OpenAI <noreply@openai.com>
(cherry picked from commit 00da7d0155)
2026-11-09 16:44:04 +00:00
safishamsiandClaude Opus 4.8 177b35e6a5 chore(cache,query): combine the schema-41 bump and clarify the qualified-tail doc
Fold the Markdown mention change (#5093) into #5098's AST schema-41 comment with a
chained prior (40), since both change per-file extractor output and share one
release window. Correct the _qualified_tail docstring example (a dotted tail is
one token, not CamelCase-split) and note the CamelCase fallback only fires on
cased input the lowercased-norm_label callers never pass (#5095 tweak).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 14:21:57 +00:00
safishamsiandClaude Opus 4.8 98dc02b1a1 docs(changelog): open 0.9.105 for the watch/cpp/markdown/wiki/build/query batch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 14:21:45 +00:00
safishamsiandClaude Opus 4.8 d51dce6164 fix(cpp): park a typed cross-repo local member call from the chain resolver (#5098 follow-up)
#5098's receiver-chain resolver dropped a single-element chain (`Greeter g;
g.greet()`) when the receiver's class is declared in no local file, where the
pre-chain path parked it by type name for the cross-repo merge to finish (#3152).
Restore that parking for a single-element chain with a known-but-local-absent
receiver type, so a typed local calling into another repo is parked, not lost.
Fixes test_cross_repo_member_calls[cpp-typed-local].

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 14:21:09 +00:00
Brenden Smith ae55b5b219 fix(cpp): resolve typed member chains across headers
Preserve lexical receiver types and access operators, resolve fields by their declaring class, and unwrap supported standard smart pointers without guessing ambiguous targets. Persist class metadata for incremental resolution and invalidate older AST caches. Add regression and negative coverage for split headers, shadowing, namespace collisions, forward declarations, and cached rebuilds.

(cherry picked from commit 287b78caca)
2026-11-09 14:09:57 +00:00
Aditya kumar singh 8fcec967ac fix(markdown): do not drop uppercase namespace classes or parenthesized method mentions
(cherry picked from commit ba55e741f3)
2026-11-09 14:09:56 +00:00
Houyun Sun 107ddf0846 fix(path): refuse an endpoint whose words the graph doesn't know
`graphify path` fell back to the top of the score ranking for any name that
matched no tier, so `zzqqxx_no_such_symbol_9137` resolved to
`no_such_symbol_helper()` (three shared `_`-split tokens) and printed its route
with exit 0, while `explain` on the same name said "No node matching".
Nothing that exists could have answered that request, and the route reads as
if it had.

The fallback now only runs when every word of the query appears in some
node's name or id. That keeps the partial names it is there for
(`draft-generator` -> `draft-generator.ts`, `Reject-everything judge` ->
`Degenerate Reject-Everything Judge`, a label the caller is still typing) and
turns a name made of unknown words into the miss `explain` already reports,
which the CLI surfaces as exit 4.

Fixes #5079

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit a084c3dd67)
2026-11-09 14:09:49 +00:00
Houyun Sun 3192fdf1f4 fix(query): match a label's name after its schema/namespace qualifier
`query sweep_widget_state` missed `public.sweep_widget_state()` even though
`explain` on the same name found it. The full-query tier only fires when the
joined query tokens equal or prefix the label, so a leading `public` defeated
it, and the per-token tiers handed the seed slots to unrelated nodes whose
whole label is one of the query's tokens (`SWEEP`, `WIDGET`, `State`).

Add a tier between exact and prefix for labels of the shape
`<qualifier><sep><rest>` where the query names exactly `<rest>`: dotted,
`::`, `/`, `:` and `@` segments, plus a CamelCase qualifier on the last
segment. It is scaled down by the qualifier's token count and capped at four
tokens, so `public.f()` is trusted more than `a.b.c.d.f()`. Trailing
file-extension and numeric segments are skipped, so `lib/foo/bar.py` is the
name `bar` rather than `py`.

Nothing changes for a query that already equals or prefixes a label, or for
plain snake_case identifiers: those never reach the new branch.

Fixes #5080

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 8d2e1caed8)
2026-11-09 14:09:46 +00:00
Houyun Sun 913b8e3a56 fix(detect): keep the racily-clean window when seen lands before mtime
_mtime_may_hide_a_rewrite() bailed out with "the mtime check already fired"
whenever seen - mtime came out negative. The caller only reaches it after the
stored and current mtime compared equal, so that shortcut skipped the hash on
a row that was still written in the same tick as the file.

seen is time.time() and mtime is the filesystem's, so the two clocks can
disagree by a few hundred nanoseconds in either direction (#5036: ~240 ns on
NTFS). When they do, a same-length rewrite inside the tick goes undetected and
detect_incremental reports the file as unchanged.

Only the magnitude of the delta says anything about whether the row is current,
so compare -delta against the same window. A row stamped a full window before
the mtime is still from an earlier run and keeps the stat-only fastpath.

Tests: test_a_row_stamped_just_before_the_mtime_still_hashes reproduces the
signed-delta miss, and test_a_row_stamped_well_before_the_mtime_keeps_the_
fastpath pins that the fastpath is not widened to every row.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 376f333f72)
2026-11-09 14:09:36 +00:00
sen bce80814d7 fix: resolve calls through destructured CommonJS barrel requires
A destructured require that reaches a symbol through a barrel
(`const { SourceCode } = require('./index')`, where `index.js` re-exports
`SourceCode` from another module) left the symbol import edge on the
barrel. The barrel defines no node, so cross-file call resolution found no
import evidence and dropped the `calls` edge.

Keep the required target file and imported name on the structural require
edge, then follow the target's exports to the declaring symbol before
cross-file resolution runs. The keys are internal and removed from the
final graph.

Fixes #5034

(cherry picked from commit 689e18a87e)
2026-11-09 14:09:31 +00:00
Aditya kumar singh 8a5756266a fix(tree): derive common directory root from file parents in build_tree
(cherry picked from commit 96fcb3b54e)
2026-11-09 14:09:25 +00:00
Aditya kumar singh d63d41165b fix(affected): recursively seed nested member nodes for file seeds
(cherry picked from commit 31e7414d7c)
2026-11-09 14:09:23 +00:00
nothariharan cbc48a69ab fix(cache): stop a degraded semantic entry from pinning the corpus (#5083)
An under-produced semantic extraction (e.g. a doc chunk that returns only
its file-level node) is saved to the unversioned content-hash cache
without a `partial` flag. The #3203 shrink guard then refuses the graph
write on every later run while the cache keeps serving the degraded chunk,
so no LLM call is ever made again and the corpus stays un-updatable until
the entry is deleted by hand.

`save_semantic_cache` cannot read graph.json (and should not), so the
shared shrink handler marks the entry the read path would serve `partial`
once the guard has measured the shrink. `load_cached` already treats
`partial` as a miss, so the next run re-dispatches the file and a complete
extraction overwrites the same content-hash key with a clean entry. This
covers both a fresh under-production and a run that replays an
already-poisoned entry written by an older version.

The guard's stderr now separates "fresh extraction is smaller" from "a
cached smaller chunk is being replayed", names the marked cache entry, and
stops recommending --allow-partial for the cached case: following that
advice would write the degraded replay over the larger graph and drop the
prior nodes.

Tests: cache-level marking (prompt-fingerprinted and legacy flat
fallback), plus two end-to-end CLI repros that fail on the old code. The
second demonstrates the reported loop: the next run hit the poisoned
cache and refused again without ever calling the model.

(cherry picked from commit fc7f700f9e)
2026-11-09 14:09:22 +00:00
nothariharan 0a14069d7f fix(build): keep hyperedges whole across an incremental merge (#5081)
_load_existing_graph backs build_merge (--update) and merge_raw_extraction (--update --no-cluster). It read hyperedges only from the top-level key, so a graph.json whose hyperedges live in the node-link slot (graph.hyperedges, the shape node_link_data-only writers emit) lost its whole hyperedge set on the next incremental merge. build_from_json already folds that slot (#2485); the loader now does too. A top-level list still wins (the canonical slot, and the CLI's source pruner edits only it); a missing, null, or malformed top-level value falls back to the nested list instead of dropping or raising on a readable set.

The deleted-source prune also removed nodes AFTER build() had revalidated hyperedge members, so a surviving cross-file hyperedge kept naming the deleted file's node. Re-run the same #1916 policy once the node set is final: drop members that no longer resolve, and drop the hyperedge only when no member remains.

Adds the reported #5081 flow end to end, nested-only coverage for both incremental paths, malformed top-level fallback, top-level precedence, and deleted-member pruning.

Co-Authored-By: DeepSeek V4.1 Flash <noreply@deepseek.com>
(cherry picked from commit e71d14cfa0)
2026-11-09 14:09:20 +00:00
nothariharan 1de3f09607 fix(wiki): fold slugs with casefold so the orphan sweep keeps current articles
to_wiki allocated unique slugs with str.lower() while the orphan sweep
indexed produced filenames with str.casefold(). For labels whose lower()
spellings differ but whose case folds agree ("Straße" / "STRASSE",
"Σ" / "ς"), both slugs were allocated, the folded map kept one, and the
sweep unlinked the other freshly written article. The export reported
both and index.md linked to the deleted page.

Dedup slugs on casefold(), the same relation the sweep uses, keeping the
existing ASCII filename behavior. Also skip any file whose exact name is
in produced before consulting the folded map, so "never delete a file
this run wrote" holds even if the two rules drift again, and build the
map from sorted(produced) so the survivor is deterministic.

Regressions cover community/community, community/hub and hub/hub
collisions for German sharp-s and Greek sigma, verify every link and
article body, and require repeated exports to be a byte-identical
fixpoint. The relabel test guards against turning the cleanup into a
no-op.

Fixes #5087

(cherry picked from commit 914f70d3fa)
2026-11-09 14:09:19 +00:00
Deepjyoti-Sarmah 43e1d4650a fix(watch): keep the recursive handler alive off Linux (#5074)
The pruned watch tree is Linux-only. macOS and Windows still use a
recursive schedule, so `watched` stays empty and the handler's parent
guard dropped every event. Apply the guard only when the manual tree is
active, and leave the recursive fallback alone when an ignore file
changes.

Add a darwin-simulated regression test and make the schedule contract
tests platform-aware.

(cherry picked from commit 2ee00533dd)
2026-11-09 14:09:19 +00:00
Deepjyoti-Sarmah ce66353f93 test(watch): pin the pruned watch tree (#5033)
Add a fake-observer scheduling test and a Linux inotify watch-count
test. Update the three contract assertions from recursive=True to
recursive=False.

(cherry picked from commit 3215888c13)
2026-11-09 14:09:19 +00:00
Deepjyoti-Sarmah 23390d21b1 fix(watch): survive ENOSPC while adding a watch (#5033)
inotify_add_watch returns ENOSPC when max_user_watches is exhausted.
Log and skip that directory instead of killing the watcher.

(cherry picked from commit 3c4c84a017)
2026-11-09 14:09:19 +00:00
Deepjyoti-Sarmah d81c4a9556 fix(watch): reload ignore rules when an ignore file changes (#5033)
The ignored predicate is built at startup. Rebuild it and reschedule the
tree when .graphifyignore or .gitignore changes, so a newly ignored
directory stops being watched and a newly unignored one starts.

(cherry picked from commit 509df2b391)
2026-11-09 14:09:19 +00:00
Deepjyoti-Sarmah 73a1e861a0 fix(watch): drop events from directories no longer watched (#5033)
A directory moved out of the root can still deliver an event after its
watch is removed. Drop events whose parent is not in the watched map,
and stale file paths whose parent no longer exists.

(cherry picked from commit cf36ca04d4)
2026-11-09 14:09:19 +00:00
Deepjyoti-Sarmah 549ae57159 fix(watch): prune ignored directories from the watch tree (#5033)
On Linux, schedule non-recursive watches only for directories that
ignored_predicate() keeps. Recursive schedule installs a watch on every
directory, including .graphifyignore'd trees, and can exhaust
max_user_watches.

New and moved directories are scanned and their existing files are
synthesized as created events, so mkdir && write is not missed.

(cherry picked from commit 0c60a6ce10)
2026-11-09 14:09:19 +00:00
safishamsiandClaude Opus 4.8 6c8002eca4 docs(changelog): cite the correct per-PR issues for the 0.9.104 robustness batch
The @azizur100389 cluster fixes #5016/#5017/#5018/#5019/#5020 (one each), not a
shared #5020, and the fresh-subfolder query fix references #2603. Correct the
thanks/issue refs and add the PR numbers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-08 00:50:14 +00:00
safishamsiandClaude Opus 4.8 433a57a002 test(install): allow the lean-core line budget for the #4762 per-block reads
The scan-path injection fix reads graphify-out/.graphify_root once per Python
block, so the lean claude core grew from ~795 to 807 lines. Raise the ceiling to
820 — still far under the ~1156-line pre-split monolith the guard exists to catch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 23:19:08 +00:00
safishamsiandClaude Opus 4.8 cb5106e861 chore(release): bump version to 0.9.104
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 23:13:24 +00:00
safishamsiandClaude Opus 4.8 c3d5305eb2 security(skill): read the scan root from .graphify_root, never substitute it (#4762)
The generated /graphify runbook substituted the agent-supplied scan path straight
into Python string literals across every code block: detect(Path('INPUT_PATH')),
extract(cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH')), the semantic
cache check/save, build_from_json/generate/diagnose, the manifest write, and the
--update detect_incremental + merge. A scan root whose NAME carried a single
quote or a $(...) / backtick broke out of the literal and ran as arbitrary code
the moment the block ran (e.g. a cloned repo with a subdirectory named
$(...) ). The shell transport was already hardened (#3642/#3844 write the path
to graphify-out/.graphify_root through a quoted heredoc); this extends the same
trust boundary to the Python blocks.

Each block now reads the resolved root from graphify-out/.graphify_root (the file
Step 1 writes) into an INPUT_PATH variable and passes the value, so the path is
always inert data, never code. The prose no longer tells the agent to substitute
a path. Applied to the assembled hosts (core.md, references/shared/update.md) and
to the Aider and Devin monoliths; a new _is_input_path_sidecar_fix_line sanctions
the monolith diff and --monolith-roundtrip / --check / --audit-coverage stay
green. A fast regression guard asserts no generated skill body carries a quoted
'INPUT_PATH' code literal.

SPEC_PATH (the skill's own extraction-spec install path, not attacker-controlled)
is left substituted and tracked as a follow-up.

Reported and first proposed by @danikdanik in #4762.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 23:13:09 +00:00
safishamsiandClaude Opus 4.8 1a6c252195 docs(changelog): add the extractor/watch/ingest/query/cli batch to 0.9.104
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 22:36:35 +00:00
safishamsiandClaude Opus 4.8 cd9634832c fix(cli): reject non-finite or negative provider pricing (#5031 follow-up)
The landed fix caught a non-numeric price but still accepted nan, inf and
negative values, which parse as floats and then flow into cost estimation as
NaN/inf/negative. Validate each --pricing-input/--pricing-output through
_valid_price (finite and >= 0) with the same clean error + exit(1), and test
that nan/inf/-inf/1e999/-5 are rejected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 22:36:00 +00:00
safishamsiandClaude Opus 4.8 6ee8e2258e fix(tree): align node-alias precedence with the graph build (#5030 follow-up)
tree_html.build_tree folded aliases in a different order (src first) than
build._fold_node_aliases (src last), so a node carrying two conflicting file
aliases could key on different paths in the viewer vs the built graph. Use the
same order and pop the consumed alias, as the build-side fold does.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 22:36:00 +00:00
Aditya kumar singh 778c906a08 fix(cli): support equals-syntax and safe float validation for provider pricing flags
(cherry picked from commit e39355c7fe)
2026-11-07 22:33:56 +00:00
Aditya kumar singh c018fc9f97 fix(tree): support src and file aliases to prevent empty tree viewer
(cherry picked from commit 035b0ada94)
2026-11-07 22:33:55 +00:00
safishamsiandClaude Opus 4.8 2ce70ce17d fix(global): isolate a malformed repo entry instead of discarding all (#5020)
Follow-up to #5025. The landed guard raised on any non-dict repo value, so a
single malformed entry backed up the whole manifest and dropped every tracked
repo. Keep the whole-file backup only for an unrecoverable shape (non-dict root
or repos map); when repos is a dict, drop just the malformed entries, keep the
valid repos, and report which went. Matches the per-entry isolation of #5024.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 22:33:44 +00:00
azizur100389 1192efc639 fix(global): recover from malformed manifest objects
Refs #5020.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit b424a2f049)
2026-11-07 22:31:59 +00:00
azizur100389 204b50854d fix(reflect): preserve legacy null source fields
Keep source-less annotations while discarding malformed non-string paths. Refs #5019.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 44a7ca59c1)
2026-11-07 22:31:45 +00:00
azizur100389 bf1e19dce9 fix(reflect): isolate malformed learning overlay entries
Refs #5019.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 344f2ae53e)
2026-11-07 22:31:45 +00:00
azizur100389 cd54401097 fix(ingest): reserve URL capture names exclusively
Refs #5018.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit de8345aa15)
2026-11-07 22:31:44 +00:00
azizur100389 4feadeda0d fix(watch): refresh JS/TS imports after resolver input changes
Refs #5017.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 84ca430505)
2026-11-07 22:31:44 +00:00
azizur100389 c66ccae853 fix(watch): rebuild the full corpus when graph.json is missing
Refs #5016.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 4f0d5eaa1a)
2026-11-07 22:31:43 +00:00
Peter Neumann 2394fd3f98 fix(query,serve): stop flagging fresh subfolder builds as pre-#1504
`graphify update sub` run from sub's parent stores source_file relative
to the build cwd (sub/pkg/mod.py, #2603) while ids are minted relative
to the scan root (pkg_mod). graph_has_legacy_ids derived the expected
stem from the stored path (sub_pkg_mod), so the real id matched the old
one-parent form and every query/MCP load of a freshly built graph told
the user to rebuild with `graphify extract --force`, which changes
nothing.

Read the cwd->scan-root offset from the relative .graphify_root marker
(new legacy_id_source_prefix) and strip it before deriving the stem.
Absolute, ".", and parent-escaping markers mean no offset, so behavior
for root-anchored graphs is unchanged and genuine legacy ids are still
reported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TGb7YtZeBXGNQMw6JjuqZu
(cherry picked from commit f5ee99de8f)
2026-11-07 22:31:35 +00:00
ayushcodes10 67c139e403 Add regression tests for CloudFormation intrinsic tag tolerance
Covers a SAM style template using nested Equals and Ref tags
extracting its structural nodes instead of failing the whole file,
plus a control confirming a python object tag alongside an
intrinsic tag still raises rather than executing.

(cherry picked from commit 4e2b26b211)
2026-11-07 22:31:35 +00:00
ayushcodes10 d458e272b9 Tolerate CloudFormation intrinsic tags in the YAML extractor
CloudFormation and SAM templates spell their intrinsic functions as
short local tags such as Ref, Sub, GetAtt and Equals. SafeLoader has
no constructor for any of them, so loading such a template raised a
constructor error and the whole file produced zero nodes, even
though nothing about the tag itself is unsafe. Composing the node
tree never hit this, since composing never resolves a tag into a
value, only constructing the actual document did.

Added a SafeLoader subclass with a multi constructor registered on
the bare exclamation mark prefix that builds a plain scalar,
sequence or mapping from the tagged node's own shape, exactly as if
the tag were absent, and never evaluates the intrinsic itself. Every
built in safe tag keeps its own constructor unchanged, since those
are registered under the full yaml.org tag namespace rather than a
bare local tag, so a python object tag still raises exactly as
before.

(cherry picked from commit e018cc2f38)
2026-11-07 22:31:35 +00:00
Shaikh Fardin 444c164cfe fix(extract): hash ambiguous Python import placeholders from root-relative data
`_suppress_ambiguous_python_imports` mints a node-less
`ambiguous_python_import_<sha1>` target for an import that more than one
scanned module could satisfy. The hash included the edge's `source_file`
and `source` id as they are at that point in the pipeline, which is
before relativization: `source_file` is still the absolute path and the
importer id is derived from it. The same commit built in two directories
therefore produced different placeholder ids, so `graph.json` was not
reproducible across checkouts and community detection could differ.

Hash the scan-root-relative `source_file` (POSIX form) with the module
name and source location, and drop the path-derived `source` id. These
already identify the import site uniquely, and the existing
`while target in node_ids` guard still prevents a collision with a real
node.

Adds a regression test that builds the same tree in two checkout
directories and asserts identical placeholder edges; it fails without
this change.

Fixes #5044

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit ff047dfea7)
2026-11-07 22:31:34 +00:00
safishamsiandClaude Opus 4.8 b81d8e51da docs(changelog): open 0.9.104 for the Solidity/C#/query/watch/cache batch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 17:23:05 +00:00
safishamsiandClaude Opus 4.8 6271f3ed40 chore(cache): combine the batch into one AST schema bump to 40
#5058, #5060, #5062, #5054 and #5056 each change per-file Solidity or C#
extraction output and each bumped _AST_CACHE_SCHEMA to 40 on their own. Landed
together in one release window they share a single bump; this folds their
descriptions into one chained schema-40 comment over the prior 39 so a warm
cache re-runs the affected Solidity and C# extractions exactly once.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-07 17:22:22 +00:00
rohit-jsfreaky 85ad8daa1e fix(csharp): credit calls in accessors, indexers and operators to that member
A C# property's accessor bodies, an indexer and a user-defined operator
or conversion were never walked, so every call made inside them was lost.
On Dapper, AutoMapper and Newtonsoft.Json (Roslyn answer key) that is 144
call links made from property/indexer accessors and 186 from conversion
operators, none found.

- A property's `get`/`set` bodies and an expression body (`int P =>
  F();`) are walked with the existing property node as the caller. An
  auto-accessor has no body and an initializer runs in the constructor,
  so neither adds calls. Only the declaration that owns the property
  node is walked: when the id is already another member's (an explicit
  `IFoo.Name` property spelled like a method `Name()`), its calls are
  dropped instead of being credited to that member.
- An indexer is a `this[]` node beside the properties (`defines`,
  context `field`), id `_make_id(type_id, "this")`, salted per
  signature (including an explicit interface) and away from a member
  spelled `This`.
- An operator or conversion is a `.operator +()` / `.operator int()`
  node owned through `method`; its id always carries a hash of the
  signature, since several conversions share one parameter list.
- A property/indexer counts as owned by its type for caller lookups
  (in-file unqualified calls, `this.`/`base.` member calls, the
  partial-type own-type preference), like a method. It is never a call
  target by name, and `operator` is kept out of the member-call index.
- No existing node id moves (checked on all three projects).
- AST cache schema 40.

Calls TO properties, indexers and operators are not linked: in these
projects they are about 3,500 property get/set links (more than half
to auto-properties), 27 indexer and 60 conversion links, against 0
user-defined binary operator calls. Linking them needs member-access
typing and a decision on the relation, so it is left out.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 0e6806a93b)
2026-11-07 17:21:33 +00:00
rohit-jsfreaky c3b6cfbd9f fix(csharp): make constructors nodes and link new/base/this to the overload by arity
A C# constructor had no node. Calls in its body were credited to the
type (#4246), calls in `: base(...)`/`: this(...)` arguments were never
walked, and `new X(a, b)` could only point at the type, never at the
overload it runs. On Dapper, AutoMapper and Newtonsoft.Json (Roslyn answer
key) 151 call links made from constructors were all lost and none of the
130 constructor initializers was linked.

- Each constructor (instance, static, and a type's primary constructor)
  is a node owned by its type through a `method` edge, labeled
  `.TypeName()` with metadata kind "constructor" plus arity/signature.
  The id is `_make_id(type_id, TypeName)`, the one a method named after
  the type would get; other signatures are salted like method overloads
  (#4584), a static constructor is its own "static" signature, and if a
  member spelled like the type in another case (`foo()` in `Foo`)
  already owns that id the constructor takes a salted one. No existing
  node id changes (checked on all three projects).
- Body and initializer calls belong to the constructor.
- `new X(...)` sites and initializers are recorded in raw_calls with no
  callee (so every name-keyed consumer skips them and the id passes
  remap their caller). A tail C# pass links the constructor whose
  parameter count fits, next to the existing edge to the type.
  `: this(...)` uses the own type, `: base(...)` the single resolvable
  base. Two fitting overloads, an unresolved base, or a type the caller
  did not bind give no edge.
- Constructors are left out of every name-keyed call index (in-file
  label map, global label index, member-call index, overload index,
  interface dispatch), so a constructor can never be picked for an
  ordinary call or shadow its type.
- AST cache schema 40.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 10332b79f5)
2026-11-07 17:20:08 +00:00
rohit-jsfreaky ebef2af2b9 fix(solidity): link a call attached by using A for T to the function
`using SafeCast for uint256; x.toUint48()` and `using EnumerableSet for
EnumerableSet.AddressSet; _set.add(a)` call the library function with
the receiver as its first argument, but the extractor parked
`x.toUint48` as a qualified call on a type named `x`, which never
exists, so no such call got an edge. On OpenZeppelin v5.4.0, 0 of the
228 calls solc resolves through a `using` directive were linked.

Record the directives in scope: a contract's own (`using` is not
inherited since 0.7), the file-level ones, and the `global` ones on a
type's declaration, as `using` metadata on the contract and file nodes,
and give library and free functions their `first_param_type`. The
resolver binds `recv.f(args)`, when the receiver's declared type is
known (the receiver typing of the previous commit, a base contract's
state variable or the return type of `g` in `g().f()`), to a function
`f` that a directive whose target is `*` or that type attaches, with
args + 1 parameters and the receiver's type as its first. The type must
match exactly, including user-defined value types and library structs
(`Trace208` inside Checkpoints reads as `Checkpoints.Trace208`, as a
caller writes it). An operator binding (`using {eq as ==} for T`)
attaches no member.

Fail closed: no edge when the receiver's type is unknown, a directive's
library name is ambiguous, or more than one function fits.

OpenZeppelin v5.4.0 (solc 0.8.28 AST as the answer key): using-for calls
0/228 -> 180/228; solmate: 0/10 -> 6/10. No other kind changes. Most of
the rest are chained calls (`slot.asBoolean().tload()`), calls written
inside a `?:` that tree-sitter parses as the member's object, and 7
calls made inside `_name` functions that share a node with their
`name` counterpart (the `_name` / `name` id merge), which land on that
merged node until the id merge is fixed.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 7bd9be0bee)
2026-11-07 17:19:52 +00:00
rohit-jsfreaky 8f3ce12426 fix(solidity): link a call on a typed receiver to the type's member
`IERC20 token; token.transfer(to, v)`, `IERC20(a).transfer(..)` and
`Ownable(x).owner()` got no edge: the extractor parked `token.transfer`
as a qualified call on a type named `token`, which never exists, and a
call on a conversion as a bare member call the shared pass drops. On
OpenZeppelin v5.4.0, 0 of the 74 such calls solc resolves were linked.

Bind `recv.f(..)` by name and arity through the receiver's declared
contract or interface type and that type's C3 linearization, the lookup
the compiler does. The type comes from the receiver typing the previous
commit adds, or from a base contract's state variable (`hevm.prank()`)
or the return type of `g` in `g().f()`. An interface method links to the
interface's declaration; no implementer is guessed. A type may be
imported through a file that re-exports it (`import {IERC20} from
"../ERC20.sol"`, the usual OpenZeppelin form), searched only when the
file declares and directly imports no type of that name.

Fail closed: no edge when the receiver is untyped, its type is not
exactly one visible contract/interface, the name/arity matches two
overloads, or a public state variable of that name (a getter) is found
first.

OpenZeppelin v5.4.0 (solc 0.8.28 AST as the answer key): typed calls
0/74 -> 71/74; solmate: 0/725 -> 716/725. No other kind changes. The 3
calls left on OpenZeppelin are made inside `_installModule` and
`_uninstallModule`, which share a node with `installModule` /
`uninstallModule` (the `_name` / `name` id merge), so they land on that
merged node until the id merge is fixed.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 752eaaf5fa)
2026-11-07 17:16:54 +00:00
rohit-jsfreaky 76d8179218 refactor(solidity): type the receiver of a member call
Read the declared type of `recv` in `recv.f(..)` and park the call as a
`member` raw call carrying that type, so a later pass can bind it through
the receiver's contract type or the `using` directives in scope. Nothing
binds `member` calls yet, so no edge changes.

A receiver is typed from a parameter, return variable or local of the
calling function (a name declared with two different types is ambiguous
and stays untyped), a state variable of the calling contract, an element
of a typed mapping or array, a field of a struct declared in the same
file, a conversion (`IERC20(a)`, `uint256(x)`, `payable(a)`) or a few
builtins (`msg.sender`, `keccak256(..)`, `abi.encode(..)`). The type is
normalized (`uint` -> `uint256`, whitespace) and a struct, enum or value
type declared in a contract is qualified with that contract's name, so
`Trace208` inside library Checkpoints and `Checkpoints.Trace208` in a
caller compare equal. A type name (`Lib.f()`) is not a typed receiver and
keeps its qualified-call path.

What only the cross-file pass can know is left to it: a state variable
node carries its `declared_type` and a function with one return value
its `returns` type, and `g(..).f()` records the call `g` it is the result
of. resolve_solidity_inherited_calls gains the helpers the binding passes
share: `receiver_types` (the extractor's reading, a base contract's state
variable, or the return type of `g`), `visible_types` (optionally through
re-exporting imports: `import {IERC20} from "./ERC20.sol"`) and a cached
`linearization`.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit abe5429cf5)
2026-11-07 17:15:50 +00:00
rohit-jsfreaky 122cede129 fix(solidity): keep _name and name apart in node ids
make_id strips a leading `_` (and folds case), so in one contract
`_grantRole(bytes32,address)` and `grantRole(bytes32,address)` minted
ONE id. add_node kept the first declaration and dropped the second: the
`_` function vanished from the graph, and every call it makes, and every
call to it, landed on its public twin. OpenZeppelin v5.4.0 has 38 such
pairs (`_grantRole`, `_transferOwnership`, `_safeTransferFrom`, ...),
which made 104 of graphify's `calls` edges ones the compiler does not
have.

Apply the rule C# got in #4415 (and Python in #3302): group the members
of a contract (functions, modifiers, events, errors, state variables,
structs, enums), the file's free functions and the file's types by the
id they would get, and run each through `_underscore_salted_nid`. The
one public name keeps the plain id and every other spelling of the
group is salted, so the outcome does not depend on declaration order. A
name without a colliding sibling keeps its id, so only the `_` spelling
of a clashing pair gets a new one.

OpenZeppelin v5.4.0 (solc 0.8.28 AST as the answer key): 3907 -> 3945
nodes, 38 new ids (all salted `_` functions), 0 existing ids changed;
wrong `calls` edges 104 -> 0; compiler-resolved calls found: same
803 -> 887, emit 119 -> 146, revert 403 -> 423, inherited 268 -> 279,
super 173 -> 185, library 205 -> 209. solmate has no such pair and is
unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 94a08d1d6d)
2026-11-07 17:14:26 +00:00
Vaibhav Gupta 1bfdcfffd2 fix(cache): keep stat-index keys root-relative under Windows long-path roots (#5035)
Since 99b8da78 (#4925), file_hash() and the word-count cache pass an
os_long_path() root to _ensure_stat_index(), which stored it as
_stat_index_anchor. On Windows that is the extended-length spelling
"\\?\C:\...", while the in-memory keys go through _normalize_path() and
drop the prefix. os.path.relpath() treats "\\?\C:" and "C:" as different
mounts and raises ValueError, so _flush_stat_index() kept every key
absolute; on load, relative keys were re-anchored with the prefix and no
longer matched the in-memory keys. A copied or moved corpus therefore lost
its stat-index hits, the portability #2199 added.

Normalize the anchor the same way as the keys. _normalize_path() is a
no-op off Windows, so other platforms are unchanged.

The three existing tests in tests/test_stat_index_portability.py fail on
Windows before this change and pass after it; CI runs on ubuntu-latest
only, which is why the regression was not caught there.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit fc7a6bda8b)
2026-11-07 17:14:18 +00:00
Bortlesboat 43360efb0c fix(cache): keep the \\?\ long-path spelling out of cache identity
99b8da7 and ff8ddf5 (#4925, #4937) open files through os_long_path(), but
on Windows its \\?\ spelling also leaked into cache identity.

file_hash() and cached_word_count() bound the stat index to the prefixed
root, so the plain cache_root that extract() passes read as a second root.
Every Windows `graphify update` that re-extracts warned "stat index
switched" (#3989) and flushed mid-run, and since no key was relative to the
prefixed anchor, stat-index.json was written with absolute keys and a moved
checkout re-hashed every file (#2199). The walked-parent match compared a
plain path with the prefixed root and never matched, so under a junctioned
or symlinked scan root an in-root alias took its target's salt and digest
(#2832), and the out-of-root salt carried a //?/ prefix. _normalize_path()
also stripped only \\?\, so the UNC form \\?\UNC\server\share became a
relative key that the flush pruned, and a corpus on a network or WSL share
always wrote an empty stat index.

Bind the index to the normalized root as before #4925, normalize the
resolved path and root before they become keys, salts or comparisons, and
map \\?\UNC\ back to \\. File I/O still goes through os_long_path(). CI
runs on Linux, where both helpers are the identity, so this only showed on
Windows.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 49616eb09c)
2026-11-07 17:14:17 +00:00
Deepjyoti-Sarmah 5212304ff8 test(watch): characterize the inotify overflow boundary
(cherry picked from commit 56bb24b39f)
2026-11-07 17:14:11 +00:00
Deepjyoti-Sarmah b0a9d775d1 test(watch): pin the event filter and fallback contract
(cherry picked from commit eb1914c087)
2026-11-07 17:14:11 +00:00
Deepjyoti-Sarmah a4db00821c fix(watch): keep read-only events out of the inotify mask (#5033)
(cherry picked from commit a5135ede7f)
2026-11-07 17:14:11 +00:00
Deepjyoti-Sarmah a4d4b03bc1 refactor(watch): detect watchdog event_filter support
(cherry picked from commit 7d94277bb4)
2026-11-07 17:14:11 +00:00
Deepjyoti-Sarmah f67daeba58 refactor(watch): extract the change-only event filter
(cherry picked from commit 52aacbb099)
2026-11-07 17:14:11 +00:00
Vaibhav Gupta 53ef377a36 fix(query): keep a same-label seed when it is the only match for a query term (#5027)
`_pick_seeds` caps seeds at one per normalized label so homonymous
symbols (dozens of `GET` handlers) cannot flood the BFS (#1766). The
per-term guarantee loop (#1445) applied the same cap, so a node that is
`best_seed_by_term[t]` was dropped whenever a higher-scoring node with
the same label was already seeded. When `t` is not part of that label,
the node won `t` through its source path, rationale or attributes, and
the seeded twin may not match `t` at all. The term was then left with no
seed, breaking the docstring's "at least one seed per distinct query
term" guarantee. Example: two `PreToolUse` classes in different plugins,
where only one path contains the query term `alpha`.

Narrow the cap in the per-term loop: skip a same-label winner only when
`term` is a substring of the shared normalized label. Then the seeded
twin matches `term` through that label (the same `t in norm_label` test
the scorer uses), so the term is already covered. #1766 still holds: a
second `GET` cannot be added for the term `get`. The first loop is
unchanged; a node it skips that is the only match for a term is now
added by the per-term loop.

Tests: the issue's 3-node repro (fails before the fix), and a degree
tie-break case where a second `GET` wins the term `get` per term. That
case is still capped, and it fails if the cap is removed entirely. The
existing #1766 per-term test cannot catch that, because its per-term
winner is already the first-loop seed.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 65c0d29225)
2026-11-07 17:14:10 +00:00
Yi-111-a 955c65de1e test: compare pending-queue paths as Path objects for Windows (#5039)
(cherry picked from commit 7ac78f83b1)
2026-11-07 17:14:04 +00:00
ayushcodes10 83ca144577 Normalize the source open mock through os_long_path before comparing
The hashing code opens the source file through paths.os_long_path,
which on win32 prepends the extended length backslash backslash
question mark backslash marker so a long path survives open. The
denied source mock compared that prefixed string against the plain
fixture path as ordinary Path objects, which never match on Windows
since neither Path equality nor resolve strips that marker. The mock
never raised, so the source failure branch silently exercised the
readable file case instead of the intended permission error, while
the sibling manifest branch already compared through resolve and
passed.

Normalize both sides through the same os_long_path helper the
source itself uses before comparing, so the two forms agree on every
platform.

(cherry picked from commit ff45f7049c)
2026-11-07 17:14:04 +00:00
ayushcodes10 499137470d Write the TS unicode fixture as UTF8 regardless of platform default
The regression test wrote its fixture through write_text with no
encoding, so it silently depended on the platform's default text
encoding. On a Windows machine whose default code page cannot encode
the accented character the fixture uses, the write itself raises
before the TypeScript extractor is ever called, failing the test for
a reason that has nothing to do with extraction.

Pass encoding equals utf8 explicitly so the fixture writes the same
way on every platform.

(cherry picked from commit 469904a0ce)
2026-11-07 17:14:03 +00:00
safishamsiandClaude Opus 4.8 16218bfc80 test(install): serialise the second wheel builder with an inline lock (#4603)
#4664 locked the test_wheel_packaging builder but not _build_wheel_names in
test_install_references, which also runs python -m build against the shared
build/ dir. Add an inline per-checkout flock (same mechanism) so two concurrent
runs on one checkout cannot collide; a cross-module import does not resolve
under pytest's import mode.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-05 13:02:18 +00:00
safishamsiandClaude Opus 4.8 c051a96ff3 chore: bump AST cache schema to 39 for the markdown namespace/member mentions (#4695)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-05 12:16:47 +00:00
viwe-monai 03838fe3af fix(markdown): recognise backslash namespaces and Type::member code-span mentions (#4610)
_code_span_mention accepted only the dotted and path-qualified forms, so the
separators other languages' docs write were dropped before the resolver saw
them: App\Services\Mailer (PHP namespaces) and Mailer::send() (PHP, Rust, C++
type-qualified members).

Both are now qualifier separators the way '.' already is, with Foo::CONST and
Foo::class left out (no node to land on) and a bare namespace root (App\)
dropped as the non-mention it is. A PSR-4 namespace root maps to the scan
directory and has no path segment, so when no candidate accounts for the whole
chain the resolver drops the leading qualifiers a candidate cannot account for,
falling back to the unique bare-name match; a qualifier that does match keeps
discriminating, so Mailer::send() still picks the right send().

(cherry picked from commit 8d6c3af9dd)
2026-11-05 12:16:21 +00:00
Oleksii Tumanov 17cf53666e feat(tree): cap directory children while retaining full totals
Apply max_children to single and merged directory roots after computing
complete descendant totals. Keep the existing file-symbol limit unchanged.

Refs #4766

AI-Assistance: OpenAI Codex
(cherry picked from commit 266865ab19)
2026-11-05 12:15:09 +00:00
safishamsiandClaude Opus 4.8 79cfb37fe0 test(install): serialise the second wheel builder under the shared lock (#4603)
#4664 locked the test_wheel_packaging builder but not _build_wheel_names in
test_install_references, which also runs python -m build against the shared
build/ dir. Reuse the same _wheel_build_lock so two concurrent runs on one
checkout cannot collide.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-05 12:14:38 +00:00
wanjinhao1 63cf60dd22 Fix #4603: stage fake install bundles in a temp package root, lock wheel builds
Assisted-by: AI coding agent (author: wanjinhao1)
(cherry picked from commit 60140356c0)
2026-11-05 12:12:04 +00:00
huangpz6 4c16a79817 test(hooks): isolate ambient venv and PATH in _detect_run
The emitted detector prefers an active virtualenv and the first python on PATH. Running the suite through uv run exposes the project .venv through both VIRTUAL_ENV and PATH, so the uv-tool machine fixture resolved to the project interpreter and test_shebang_parse_requires_leading_hash_bang failed locally. Scrub the venv variables and rebuild PATH from the stub bin plus os.defpath.

Co-Authored-By: TRAE <noreply@trae.ai>
(cherry picked from commit 6ead523c44)
2026-11-05 12:11:30 +00:00
Pratik Dhanave 892c452d8c test(reflect): characterize _is_stale across changed/unchanged/vanished sources
Add three characterization tests pinning the existing, correct behavior of
the learning-overlay staleness check (graphify/reflect.py::_is_stale) directly
at the helper level:

- unchanged source (stored fingerprint still matches) -> fresh (False)
- changed source content -> stale (True)
- vanished / unresolvable source path -> stale (True), the deliberate
  over-flagging safe direction for a re-verify hint

They use the writer's own _code_fingerprint to seed the stored fingerprint,
documenting that writer and reader agree on an unchanged file. No behavior
change.

(cherry picked from commit e80a50f2d9)
2026-11-05 12:11:27 +00:00
Wyatt Au d76b102905 docs: note the context-local semantics for spawned workers
(cherry picked from commit 83557a73f2)
2026-11-05 12:11:26 +00:00
Wyatt Au e93821ff3c fix: make the ambient scan root thread-isolated via ContextVar
_ACTIVE_SCAN_ROOT was a module global. Extraction runs concurrently
(ThreadPoolExecutor in tests, process pools in production), and
overlapping set/restore pairs in _safe_extract_with_xaml_root
interleaved: the second call saved the first one's root and restored it
last, leaving the ambient root set after extract() returned. Nine tests
downstream failed in any non-default order
(#4602, diagnosis by Deepjyoti Sarmah).

Replace the global with a contextvars.ContextVar: every thread (and
async task) gets its own value, so save/restore pairs nest correctly by
construction and the set/return-previous API is unchanged.

Proves the old failure: tests/test_scan_root_contextvar.py asserts each
thread sees its own root at the race window. under the global both
threads read the last setter's value, and the loser of the restore race
leaked the winner's root. Fails on the global, passes with the fix.

Fixes #4602

(cherry picked from commit 2c51667211)
2026-11-05 12:11:26 +00:00
ayushcodes10 d329bcdfdb Add regression tests for the unclassified share warning
Covers detect() directly: the warning fires once both the absolute
floor and the fraction threshold are crossed, and stays silent just
under either one on its own, a tiny sliver of unsupported files in a
large corpus, or a small corpus where two stray files already look
large by percentage alone. Also covers watch's own rebuild function,
one of the console paths that carries the warning through, and
GRAPH_REPORT.md's Corpus Check section printing or omitting the line
depending on whether detect() set it.

(cherry picked from commit 76d1d49174)
2026-11-05 12:11:24 +00:00
ayushcodes10 918b4b7558 Warn loudly when most of a corpus has no extractor
A file graphify cannot classify, no supported extension or shebang,
was already named in the console output and counted in
GRAPH_REPORT.md, added by an earlier fix. That is the right behavior
for the common case: a stray Dockerfile or license file is routine
and the existing count already covers it.

It reads as equally routine when the share is large instead, a
repository whose real business logic lives in a language graphify
does not parse at all. The graph still looks complete, since nothing
distinguishes "a handful of boilerplate files" from "most of the
codebase" in that same plain count, and a user has no reason to
suspect their graph is structurally incomplete.

detect() now compares the unclassified count against the total files
actually seen and sets a separate warning field once both an
absolute floor and a fraction threshold are crossed, so a tiny repo
with one stray unsupported file never trips it. The three places
that already reported the plain count, graphify extract, graphify
update and watch's rebuild path, and GRAPH_REPORT.md's Corpus Check,
all print this new warning right alongside the count when it fires,
and stay exactly as before when it does not.

(cherry picked from commit b0726d56ca)
2026-11-05 12:11:24 +00:00
Vivek1898 8316033ce0 fix(install): write the pi project skill to .pi/skills, where Pi reads it
graphify install --project --platform pi used the user-scope shape .pi/agent/skills inside the project. Pi only reads project skills from .pi/skills, so the skill never loaded and nothing said why. Give pi the explicit project path the other platforms already have.

Fixes #5011

(cherry picked from commit 8a911d2a9d)
2026-11-05 12:11:23 +00:00
safishamsiandClaude Opus 4.8 2b955d3b68 test: cold-start the stat index before every test (autouse)
#4801 made _rebuild_code's no-change gate read the process-wide stat index, so
across the full suite a warm index left by an earlier test (thousands of roots
hashed in one process) could serve a stale hash and make a rebuild skip
re-extraction - failing watch/reconcile tests nondeterministically depending on
ordering. Add an autouse conftest fixture that resets the stat index to its cold
init state before each test (#3989: cross-root callers in one process must use a
fresh process; a real update/extract always does). Product behavior unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-04 23:09:50 +00:00
safishamsiandClaude Opus 4.8 80b9a4caf4 chore: release 0.9.103 with the extractor, resolution, hooks and perf batch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-04 20:51:08 +00:00
safishamsiandClaude Opus 4.8 d944c3f074 chore: combined AST cache schema 38 for the C#, Solidity and YAML extractor fixes
#5003 (C# preprocessor blanking), #5005/#5001 (Solidity library + emit/revert/
require linking) and #4995 (YAML << merge precedence) each change per-file
extractor output; fold them into one schema-38 entry so warm caches re-run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-04 20:50:20 +00:00
rohit-jsfreaky b3d967519f fix(solidity): link Lib.f() library calls to the function they name
A dotted call `Lib.f(..)` was parked as a bare member call, which the shared
cross-file pass drops, and Solidity has no member pass of its own, so no
library call got a `calls` edge, not even `Lib.f()` inside Lib itself.

Park `Recv.f(..)` (a plain identifier receiver) as a `qualified` call, the
kind `revert Errors.Err()` already uses, and bind it through the one library
or contract of that name the caller's file declares or imports directly
(named, whole-file or `{A as B}` import), then the member by arity. Fail
closed when the name or (name, arity) is ambiguous; a value receiver
(`token.transfer()`) names no type and gets no edge. Free functions resolve
qualified calls too, `require(c, Lib.Err(..))` binds the error, and
`!Lib.f(x)` (parsed by the grammar as `(!Lib).f`) reads its real receiver.
Node ids are unchanged; AST cache schema 38 -> 39.

OpenZeppelin v5.4.0 vs solc 0.8.28 (unique caller/target pairs): library
0 -> 199 of 232, contract-qualified 0 -> 6 of 6, revert 401 -> 403; other
kinds unchanged. Remaining library misses are same-arity overloads (out of
scope), a call inside a modifier argument, and an existing `_f`/`f` node-id
collision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 28f882c5f5)
2026-11-04 20:49:27 +00:00
rohit-jsfreaky 206169981c fix(solidity): link emit, revert and require to the event or error they name
`emit E(..)` and `revert Err(..)` are statements, not call_expressions, so the
body walk skipped them and no function ever linked to the event or error it
uses. Bind them as calls by (name, arity): in the caller's own contract, through
the linearized bases (an interface's event, a base's error), or as `Lib.Err`
through a type the file declares or imports. Fail closed when ambiguous.
`require(c, Err(..))` is a plain call of the error and now resolves too.
OpenZeppelin v5.4.0 vs solc 0.8.28: revert 0 -> 386 of 403, emit 0 -> 116 of 119;
other call kinds unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 9a1632d4b2)
2026-11-04 20:49:08 +00:00
Pratik Dhanave 8317212754 fix(yaml): give earlier map precedence in a << merge sequence
A `<<: [*a, *b]` sequence merge was resolving keys to the LAST map in the
sequence, but the YAML merge spec (and PyYAML's safe_load / flatten_mapping)
give the EARLIER map precedence. _mapping_pairs fed the sources forward into a
last-write-wins dict, so for a key defined in both anchors the later anchor's
value and line won instead of the earlier one's.

Feed the merge sources in reverse, mirroring PyYAML's flatten_mapping (which
reverses the submerge), so the earliest map keeps the final value/line.

Regression test asserts services.web.common resolves to the first anchor's
mapping (L2), matching yaml.safe_load, not the second anchor's (L5).

(cherry picked from commit 55bff8985f)
2026-11-04 20:49:07 +00:00
rohit-jsfreaky 52a7acb602 fix(extract): blank C# preprocessor directives and #if branches that derail parsing
tree-sitter-c-sharp parses `#if`/`#elif`/`#else`/`#endif` with every branch
in place. Its error recovery around a directive can close the enclosing class
early, so every later member became a class-less node: it lost its `Type.`
owner, its field/receiver typing and same-class resolution, and its calls
were lost or wrong (e.g. `Writer.Flush -> Buffer.Append` was missing).

Before parsing, extract_csharp now blanks every directive line (including
#region, #pragma, #nullable and #define). The first branch of each #if group
is always kept. A later #elif/#else branch is kept as well, so members that
exist only there stay in the graph (#2631). It is blanked only when keeping
it would derail the parse:
- its `{}` or `()` do not net to zero on their own
  (`class A : B {` #else `class A {`), or
- it declares a member (name + arity) that a kept branch of the same group
  already declares (`void Write(Span<char>)` #else `void Write(string)`
  sharing one body).
Nested groups are decided first. The rewrite keeps the byte length the same
(removed bytes become spaces, CR/LF kept), so every remaining byte keeps its
line and column. A `#` line inside a comment or a multi-line string is not
treated as a directive.

Measured against the Roslyn answer key on Newtonsoft.Json, Dapper and
AutoMapper: 5544/7349 links (75.4%, was 70.8%), and 264 wrong `calls` edges
(was 288). No kind loses recall except `ctor` (-4): five `new JValue(...)`
calls inside JValue. Those methods now correctly belong to JValue, and the
graph keeps one edge per node pair, so the JValue -> method edge replaces
the calls edge. Keeping only the first branch scores 5545 but drops #else-only
members.

Bumps the AST cache schema to 38 so cached C# extractions re-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e1668ed0c6)
2026-11-04 20:48:49 +00:00
safishamsiandClaude Opus 4.8 92622867d1 fix(resolution): scope the #4994 collision match to the 6-hex salt shape
#4997's _collision_aware matched any alphanumeric id suffix, which also matches
a class member id (classid_methodname), so a type-annotated field following a
method had its reference stolen onto the method in TS/JS/C#. Restrict the
sibling match to the actual underscore-collision salt (a 6-char sha1 hex, per
_underscore_salted_nid) and add a method-then-field regression test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-04 20:48:30 +00:00
Houyun Sun b227f7200f fix(resolution): attribute a call inside _main to _main, not main
`ids.py:make_id` strips the underscore edges off every part, so a module that
declares both `_main` and `main` mints one plain id for the pair. The AST
extractor already deals with that: `_python_pre_scan_underscore_collisions`
salts the collision apart (#3302) and leaves the plain id on the unique public
spelling, which here means `main()` keeps `cli_main` and `_main()` gets
`cli_main_<hash>`.

The import-aware symbol pass never learned that rule. It walks the top-level
defs itself and rebuilds each caller id straight from the bare name, so `_main`
also arrived as `cli_main` — the public sibling's node — and every call inside
`_main` to an imported symbol was emitted a second time, sourced from `main()`
and marked EXTRACTED at a line that belongs to `_main`.

Resolve the caller against the final graph instead. When the id the walk
produced is shared by more than one declaration, pick the one whose line
encloses the call. Node ids, edges and raw_calls are all final by the time
this pass runs, so the salted spelling is available. A name with no collision
never enters the branch and keeps the exact behaviour it had.

Fixes #4994

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit de30ba0e86)
2026-11-04 20:39:21 +00:00
mathewgeejo 69954b537d fix(typescript): keep import types out of runtime dependencies
Recognize type-only import contexts without dropping real runtime imports. Invalidate stale AST cache entries and cover normalized generics, file suffixes, and source offsets. Fixes #4992.

Co-Authored-By: Codex <noreply@openai.com>
(cherry picked from commit 42b117e8b8)
2026-11-04 20:39:09 +00:00
rohit-jsfreaky 7fc5312e91 fix(hook): restore the nudge budget after a Claude Code compaction
_nudge_allowed caps soft nudges per session and per subagent (#3435). When
Claude Code compacts a long conversation (auto or /compact) it keeps the
session id, but the compacted context no longer holds the earlier nudges or
the graph context. The cap is already spent, so for the rest of the session
the agent reads and greps raw files and never hears about the graph again.

Claude Code fires SessionStart with source "compact" after compaction.
`graphify install` (Claude Code only) now also registers a SessionStart hook
with matcher "compact" that runs `graphify hook-guard compact`. It deletes the
session's .nudges counter, the counter of every subagent of that session
(<key>-<16 hex>) and the session's strict-mode .denied marker, so the next
qualifying Read/Grep nudges again and strict mode can redirect once more.
Other sessions' markers are untouched; startup, resume, clear and fork do not
reset. When a graph exists it returns a one-line SessionStart
additionalContext that names the graph and the query commands. Any error
prints nothing and exits 0.

Install merges the entry like the PreToolUse ones (other SessionStart hooks
are kept, re-install does not duplicate it); uninstall removes it from
settings.json and settings.local.json. The cap and the per-agent and stamp
rules are unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 53bf0a1d76)
2026-11-04 20:37:46 +00:00
rohit-jsfreaky fd1ee64528 fix(hook): give Bash file reads (cat, head, sed -n, ...) the read nudge
The Read|Glob matcher gives the read nudge, but Bash goes to `hook-guard
search`, which only reacted to search commands. `cat src/app.py`,
`head -50 src/app.py`, `tail`, `nl`, `less`, `more` and `bat` read indexed
code with no nudge at all, and `sed -n 1,80p src/app.py` got the generic
search nudge without the file's symbols. Claude Code reads files this way a
lot, especially with the Bash tool in auto mode.

`hook-guard search` now checks Bash commands for a file reader in an executed
position (the #3121 parsing, factored out of _bash_invokes_search into
_bash_commands so both use it) naming an existing in-project code file. Such a
call goes through the Read path: the same Read nudge with the file hint, the
stale variant, and the same per-agent budget. It is never denied, also in
strict mode. Targets outside the project or inside the graph output are
skipped (#1840, #4961), as are docs (`cat README.md` stays silent, as the
existing tests pin), non-graphed extensions, writes (`cat > x.py`, a stdout
redirect, `sed -i`), stdin reads (`echo x | cat`) and paths with shell
expansion. sed counts as a reader only with -n/--quiet/--silent; without it a
sed on a file stays a search, as before.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 13d133ea68)
2026-11-04 20:37:46 +00:00
Deepjyoti-Sarmah 82bde2b35b docs(4989): note the Python builtin call fix
(cherry picked from commit 54461e71d2)
2026-11-04 20:37:45 +00:00
Deepjyoti-Sarmah 084c3fd121 test(4989): pin Python builtin call shadowing
Covers the unimported builtin, the imported control case, module-only import evidence, a local same-named class, by-name dispatch, and unchanged non-builtin INFERRED resolution.

(cherry picked from commit 59eb928f51)
2026-11-04 20:37:45 +00:00
Deepjyoti-Sarmah 0a9491d3d3 fix(4989): require a symbol import for builtin-named Python calls
A bare Python name resolves through the caller module's own bindings. The cross-file resolver matched any bare callee by label, so a file that never bound NotImplementedError linked to a package class of that name. Module-level import evidence from the same file could even promote the wrong edge to EXTRACTED.

Accept a builtin-named Python callee only when the caller imports that exact symbol. The imported control case still resolves as EXTRACTED; non-builtin INFERRED resolution is unchanged.

(cherry picked from commit 9a2427d105)
2026-11-04 20:37:45 +00:00
Deepjyoti-Sarmah cb2befc171 refactor(4989): add a Python builtin name set
Fixed rather than derived from dir(builtins), so extraction stays deterministic across interpreter versions. Kept separate from _LANGUAGE_BUILTIN_GLOBALS: that set gates extraction, where dropping a raw call would also drop the import evidence for a same-named project class.

(cherry picked from commit 21279c932a)
2026-11-04 20:37:45 +00:00
Pratik Dhanave 13e05097a0 fix(markdown): don't drop a dotted mention whose method name is a builtin
The language-builtin exclusion ran for every non-path mention, so a dotted
mention like `Repository.open` was discarded before its qualifier evidence was
checked — even though the qualifier proves the reference. Builtin-named methods
(open/get/list/map/filter/update/...) are pervasive, so real cross-references
silently produced no edge. Apply the builtin filter only to bare single-name
mentions (len(names) == 1). Add a regression test.

(cherry picked from commit 85f344a64e)
2026-11-04 20:37:34 +00:00
Deepjyoti-Sarmah 50cea7f614 test(4978): prove the memo does not survive a rebuild
watch is a long-lived process, so a cache that outlived one reconcile call
would answer with a stale header dialect after an edit. Rebuild three times in
one process and assert every rebuild resolves the file again.

Moving the memo to module scope turns this test red and nothing else.

(cherry picked from commit 4024792e2d)
2026-11-04 20:37:33 +00:00
Deepjyoti-Sarmah fbfa4162ee test(4978): pin the production sniff cap and drop variants that cannot differ
The cap was asserted against a reference implementation, not against the
shipped sniffer, so read_bytes()[:CAP] could come back and every test would
stay green. Assert the exact read sizes on a file larger than the cap, for .h
and .m, and grow the .m pipeline fixture past the cap so its byte assertion can
fail. With an unbounded fh.read() both new tests go red.

The H1 and H4 variants can no longer differ now that the reconcile path does
not sniff .h at all, so test_cost_variants and the meaning differential were
asserting the same thing four times. The frozen node set is the guard that
still bites.

(cherry picked from commit 8db559def5)
2026-11-04 20:37:33 +00:00
Deepjyoti-Sarmah a561caa274 perf(extract): share one sniff head between the header probes
A .h resolution opened the same 256 KiB twice. Read it once and pass it to both sniffers.

(cherry picked from commit 653adf6acf)
2026-11-04 20:37:33 +00:00
Deepjyoti-Sarmah 3050664e04 perf(extract): read only the sniffed head of a header
_is_objc_header and _is_cpp_header sliced read_bytes() down to 256 KiB, so a 4 MB single-header library was fully read and allocated twice per call. read the head directly instead. Same bytes inspected, same answer, no full-file allocation.

(cherry picked from commit 60342b7ee1)
2026-11-04 20:37:33 +00:00
Deepjyoti-Sarmah 95ae649a6e perf(update): resolve AST ownership once per file in reconcile
_reconcile_existing_graph tested _get_extractor per node, and a .h resolution read the whole file twice inside the sniffers. Reconcile only needs to know whether the source is AST-owned, which every .h dialect always is, so the header sniff is skipped for that caller and the answer is memoized by identity.

Keying by identity also resolves source_file against the project root, so a relative path no longer makes both sniffs swallow an OSError when the process CWD is outside the project.

(cherry picked from commit cc65f4dbc4)
2026-11-04 20:37:33 +00:00
Deepjyoti-Sarmah 6b12463402 test(update): pin #4978 reconcile ask count and eviction set
Reconcile calls _get_extractor once per node, and for a .h that call reads the whole file twice. The suite counts asks, real extractor resolutions and bytes read per variant, and freezes the survivor node set so the perf changes that follow can prove they changed no decision.

(cherry picked from commit 2edb9f979c)
2026-11-04 20:37:33 +00:00
huangpz6 71eb28a770 fix(hooks): keep the toplevel anchor working when CDPATH is exported (#4977)
An exported CDPATH makes the cd builtin print the resolved directory to stdout. The git-dir captures only silence stderr, so they became two-line values and the toplevel anchor exited via '|| exit 0', silently skipping every generated rebuild. Prefix both cd calls with CDPATH= and add a regression that runs the real guard under an exported CDPATH.

Co-Authored-By: TRAE <noreply@trae.ai>
(cherry picked from commit 009f9fdb5f)
2026-11-04 20:37:33 +00:00
safishamsiandClaude Opus 4.8 59b5ab1151 fix(skillgen): use single-quoted encoding in the --update partial-list read
#4816's _partial line used escaped double quotes (encoding=\"utf-8\"), which
work in the bash-wrapped runbook but break test_update_manifest_preservation,
which execs the manifest block as raw Python. Match the single-quote style the
rest of the file already uses so the line is valid in both contexts, and
regenerate the skill artifacts.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 22:34:27 +00:00
safishamsiandClaude Opus 4.8 e3d7877c9b chore: consolidate the unpublished work into the 0.9.102 release
Fold the hooks/perf/TypeScript and this query/skill/install/watch batch into
a single 0.9.102 CHANGELOG section (0.9.102 and 0.9.103 were never published),
and keep the version at 0.9.102.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 22:26:30 +00:00
Alex Tumanov 5b8415f368 fix(query): narrow marker fallback and complete help
Refs #1654

AI-Assistance: OpenAI Codex
(cherry picked from commit 52404fc1a1)
2026-11-03 22:25:19 +00:00
Alex Tumanov 19eacc74a1 feat(query): read project budget and depth defaults
Resolve CLI query defaults from the selected graph project and keep
explicit options authoritative. Preserve execution and query-log agreement.

Refs #1654.

AI-Assistance: OpenAI Codex
(cherry picked from commit f3b5a09a39)
2026-11-03 22:25:18 +00:00
ayushcodes10 514fb6f6a9 Regenerate skill artifacts for the hub bypass check
Rendered from the fragment and generator changes via the skillgen
module, then blessed into expected/. No fragment or generator
source changed here, only its render.

(cherry picked from commit bfeabedf7e)
2026-11-03 22:24:23 +00:00
ayushcodes10 5260578567 Report code that reimplements a hub instead of calling it
A bridge or god node question's neighbour listing only shows code
that already has an edge to the hub, so a module that reimplements
the hub's own job instead of calling it never shows up there, even
though it depends on the exact same behavior. One real case: two
server modules that hard coded a date utility's offset instead of
calling the shared helper read as unrelated to the bridge, when they
were in fact the most useful finding the question could have
surfaced.

The query flow now adds a check for exactly this shape, scoped to a
hub or bridge question: after the normal answer, grep the corpus for
one or two literal, distinctive things the hub does, in files that
have no edge to it in the traversed subgraph, and report any hits
separately as bypasses. It also asks the answer to call out when a
shared utility's own community label actually names its heaviest
consumer, a labelling quirk that otherwise reads as if the consumer
were the bridge.

The aider and devin monolith skills carry their own copy of this
query section, so the same paragraph was added there too, right
where their own save result step already follows the answer.

(cherry picked from commit 26daf32bc5)
2026-11-03 22:24:23 +00:00
safishamsiandClaude Opus 4.8 0696dfbf86 test(js): pin the actual external-require CJS/ESM asymmetry (#4688)
The PR's parity test asserted an external CJS require emits no calls/inherits
edge, matching ESM. On the current tree an external require binding is a real
local node that new/extends resolve to, while an external ESM default mints
none - a pre-existing asymmetry outside #4688's intra-project ./ require fix.
Pin the real behavior so a future change is deliberate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 22:23:45 +00:00
Mpasha17 ba20b12bbc fix(js): ignore bare exports= and walk chained module.exports RHS
Bare `exports = X` only rebinds the local exports binding in CommonJS and
must not mint a default export. Chained `module.exports = exports = Foo`
must export Foo, not the intermediate name `exports`.

Co-Authored-By: Grok Bot
(cherry picked from commit 47cb49ef0a)
2026-11-03 22:21:54 +00:00
Mpasha17 6dcba3377e fix(js): resolve class extends through CJS require bindings
After #4634 stopped minting a module-scope node for
`const X = require('./m')`, `class A extends X` lost its inherits
edge entirely. Record whole-module require bindings and
`module.exports = Name` as symbol import/export facts so heritage
resolves to the required class, matching ESM default imports.

Fixes #4688

Co-Authored-By: Grok Bot
(cherry picked from commit d9132a85ca)
2026-11-03 22:21:54 +00:00
Deepjyoti-Sarmah 6096f63407 docs(watch): describe the three queue request kinds
(cherry picked from commit 10f932149b)
2026-11-03 22:21:42 +00:00
Deepjyoti-Sarmah 858aa9f423 fix(watch): record a contended incremental request instead of dropping it
An incremental rebuild derives its change set from the manifest inside the lock,
so it names no paths and had nothing to append to .pending_changes, while
.pending_full would have meant "re-extract everything". Losing the lock therefore
dropped the request, and the False it returned was indistinguishable from the
"queued, it will run" answer a caller gets for the other two kinds.

This is latent rather than an incident: no non-blocking incremental caller exists
today, because the CLI blocks on the lock and the watcher and hooks pass explicit
paths. The fix completes the design.

The request is now recorded as a .pending_incremental marker, and any holder that
drains it runs an incremental pass, including a holder whose own request was a
full one. Reported by review on #4769.

Fixes the latent drop for #4769's incremental kind.

(cherry picked from commit 3e6138c3bc)
2026-11-03 22:21:42 +00:00
Deepjyoti-Sarmah e10c7cef04 test(watch): pin the lock-queue contract for the existing request kinds
(cherry picked from commit 0966953248)
2026-11-03 22:21:42 +00:00
Deepjyoti-Sarmah f4d62e7b8c test(watch): make the default-path assertion robust to the no-change gate (#4740)
(cherry picked from commit 83f6fb8495)
2026-11-03 22:21:26 +00:00
Deepjyoti-Sarmah 789f2742b3 fix(watch): keep cross-file resolution edges for the changed set (#4740)
(cherry picked from commit 80eec26c14)
2026-11-03 22:21:26 +00:00
Deepjyoti-Sarmah 14485ab508 feat(cli): use the incremental path for update (#4740)
(cherry picked from commit 32a618526c)
2026-11-03 22:21:26 +00:00
Deepjyoti-Sarmah 83f6142342 feat(watch): derive changed_paths from the manifest in _rebuild_code (#4740)
(cherry picked from commit 3d629a621b)
2026-11-03 22:21:26 +00:00
Deepjyoti-Sarmah 694c2d7e1a refactor(detect): expose the changed set for a root
(cherry picked from commit df13dd00a0)
2026-11-03 22:21:26 +00:00
pei711 69c61eaaf3 fix(skill): thread force=IS_FORCE to to_json in Step 4 (#4777)
When to_json() refuses to shrink graphify-out/graph.json under the #479
shrink guard, the skill instructs the user to re-run with --force.
However, Step 4 in tools/skillgen/fragments/core/core.md invoked to_json()
without force=True, preventing intentional shrinks from ever succeeding.

Update Step 4 to instruct the agent on substituting IS_FORCE and pass
force=IS_FORCE to to_json. Regenerate committed skill artifacts and
expected/ snapshots via skillgen, and add regression tests in
tests/test_skillgen.py.

Fixes #4777.

Co-Authored-By: Gemini <noreply@google.com>
(cherry picked from commit 6776be6cc3)
2026-11-03 22:21:17 +00:00
gitmotion a1ae1ff243 docs(skillgen): say why the --update merge block leaves the partial list in place (#4807)
Deleting the list there broke the case where Step 9 runs after the update;
the comment keeps the next reader from moving the cleanup back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit df22be56d6)
2026-11-03 22:21:10 +00:00
gitmotion 6ed7044288 test(skillgen): fail on a Step 9 error, pin this run's nodes, cover two partial docs (#4807)
- Run each runbook block under `bash -e`. Step 9 runs cleanup commands after
  its Python, so a Step 9 that failed before saving the manifest still exited
  0, and the doc stayed queued from the merge: the Step 9 case passed without
  Step 9 having done anything.
- Give the partly-read docs new nodes of their own and assert those survive
  the merge. The seeded graph already had a node with the same id and source,
  so dropping this run's nodes before the merge still passed.
- List two partly-read docs, so a parse that keeps only the first entry fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 39af15ab83)
2026-11-03 22:21:10 +00:00
gitmotion 00ad4fde5a fix(skillgen): drop a leftover partial list when --update starts, not after the merge
Deleting .graphify_partial.txt in the merge block undid the fix whenever an
agent ran Step 9 after the update: Step 9 found no list and stamped the
partly-read doc, where before this branch it read the list and left the doc
queued. Step 9's manifest code handles --update mode, and agents do run it
after an update (#837).

The first --update block now deletes a list an earlier run left, before
detection. This run's list stays for the merge block and for Step 9, and a
stale one still cannot hold back a doc this run serves from the cache.

Tests: run the runbook's populate block too; add a case that runs the
rendered Step 9 after the merge; cover scan roots '.' and 'docs' with a nested
doc and both list-entry forms (absolute, root-relative); skip without bash;
drop BASH_ENV and ENV from the subprocess environment; derive the hosts from
the render instead of a hardcoded list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d19a2b112a)
2026-11-03 22:21:10 +00:00
gitmotion 87b1aae182 fix(skillgen): keep partly-read docs unstamped in the --update runbook (#4807)
Step B3.5 lists the files a subagent read only partway in
graphify-out/.graphify_partial.txt. A full build's Step 9 passes that list to
_stamped_manifest_files, so those files stay unstamped and the next --update
queues them again (#2225). --update does not run Step 9: its runbook writes the
manifest itself and did not pass the list. A doc read partway during an
--update was stamped as done, and kept its partial node set until its content
changed again.

The update runbook now reads the list the way Step 9 does and passes it as
partial_source_files. It also removes the list once the manifest is saved.
--update never runs Step 9, which deletes it after a full build, and only B3.5
rewrites it, so a later run that skips B3.5 would read it again: a doc it
names that came back as a cache hit would stay unstamped on every run.

Edited the shared update fragment, then regenerated the 14 per-host
references/update.md files and their expected/ snapshots. The new test runs
the rendered runbook's merge block on a seeded project and asks
detect_incremental what the next run would queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 257f3f77c0)
2026-11-03 22:21:10 +00:00
madhusudanpatnaik 67cf4967bf fix(install): leave a hand-written # graphify section in a global file
Every `graphify uninstall` now visits the user's global CLAUDE.md and
CODEBUDDY.md, also for users who never installed the skill there, so a
section they wrote under a `# graphify` heading must not go with
graphify's registration. In those files only a section carrying the
registration bullet graphify has always written (`- **graphify** (`...`)`
with the `/graphify` trigger, in every version since the first) is
removed; a hand-written one stays, and a file holding both is left as is
with a hint rather than guessed at. The project-scoped removal keeps its
existing behavior.

Also: a BOM no longer hides a block on the file's first line and is
written back as found, and a file without the heading is never decoded,
so an unrelated non-UTF-8 file draws no "skipped" warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a7bd4e61e4)
2026-11-03 22:20:47 +00:00
madhusudanpatnaik edc74052ee fix(install): remove the global skill registration on uninstall
A global `graphify install --platform claude` (or `windows`) registers the
skill with a `# graphify` block in ~/.claude/CLAUDE.md ($CLAUDE_CONFIG_DIR/
CLAUDE.md when that is set), and `--platform codebuddy` does the same in
~/.codebuddy/CODEBUDDY.md. `graphify uninstall`, `graphify claude uninstall`
and `graphify codebuddy uninstall` deleted the global skill but left the
block, so every Claude Code or CodeBuddy session kept being told to use a
skill that no longer existed. Only the project-scoped uninstall removed its
registration.

Remove the global registration wherever the global skill is removed,
resolving the file exactly as install does, CLAUDE_CONFIG_DIR included
(#2694); a test pins the two to the same file. The removal follows the
project-scoped rules: only the exact `# graphify` H1 block goes (#2062),
line endings are kept (#4360), a symlinked file is edited in place (#3805),
and the file is deleted only when nothing else was in it. Like install
(#3474), it skips an unreadable or unwritable file with a hint instead of
aborting the rest of the uninstall; the project-scoped removal shares that
helper, so it now degrades the same way. A project-scoped uninstall still
leaves the global skill and its registration alone (#2215).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 8ab30ab40a)
2026-11-03 22:20:47 +00:00
rohit-jsfreaky a50ad2b419 feat(query): rank source above tests and docs, and answer file-first
query scores node names only, so a test named after a bug (UsernameValidatorsTests) wins the
exact-name tier, and the answer is ordered by hop and degree, so hub files fill the budget.
On 177 SWE-bench Lite questions 43% of the start nodes were tests.

Inside query only, test, doc, config and sourceless nodes now count x0.3 unless the question
asks about them (reusing paths._is_test_path), and the answer is listed file by file, best
file first. path, explain, traversal, the budget and the per-term seed guarantee are
unchanged. Top-5 on 293 SWE-bench Lite and Verified questions: 49% -> 56% (26 gained, 4 lost).

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 9b2e076b76)
2026-11-03 22:20:46 +00:00
safishamsiandClaude Opus 4.8 b8ba9eb366 chore: release 0.9.103 with the hooks, perf and TypeScript batch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 21:42:17 +00:00
safishamsiandClaude Opus 4.8 1c0d3d853c test(ts): replace the flaky timing assertion with an absolute backtracking bound (#4976)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 21:40:13 +00:00
Ismael Briasco 60349fe74c fix(extract): preservar offsets CRLF y limitar búsqueda de tipos
Mapea las posiciones de bytes a texto normalizado en una sola pasada y
evita reiniciar la búsqueda en cada carácter de un identificador largo.

Co-authored-by: Codex <noreply@openai.com>
(cherry picked from commit 87f1514ebd)
2026-11-03 21:39:40 +00:00
Ismael Briasco 0ed3c32c55 fix(extract): preservar sintaxis TypeScript en plantillas e imports de tipo
La gramática puede perder declaraciones después de plantillas etiquetadas
con tipos o anotaciones calificadas por import. Normalizar sólo los tipos
identificados conserva las posiciones y evita relaciones dinámicas falsas.

Co-authored-by: Codex <noreply@openai.com>
(cherry picked from commit 7da2f1b910)
2026-11-03 21:39:40 +00:00
Shubham Padkonde 227028de75 fix(hooks): skip project hints for external searches
Only omit hints when recognized literal targets all resolve outside the project. Preserve advisory hints for mixed paths and uncertain shell syntax.

Fixes #4961

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 2ef48b214f)
2026-11-03 21:39:31 +00:00
Andre Brait 7433c0a805 fix(hooks): deny a single-file Grep only when the graph indexes it
A Grep pinned to one unindexed file (pyproject.toml, a config) spent the session's single strict deny on a target the graph cannot answer. Apply Read's indexed-file check to single-file targets; directory searches are unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 1b89dfa50c)
2026-11-03 21:37:25 +00:00
Andre Brait 2a5d442632 fix(hooks): include dedicated Grep in the strict orientation gate
Share Read’s existing one-denial-per-session gate with dedicated Grep, respecting the query stamp and project/output boundaries. Bash and Glob remain advisory. Pass --strict through installed search hooks and document both-mode silence for irrelevant targets.

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

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 6f38228510)
2026-11-03 21:36:55 +00:00
Andre Brait cb408949e1 fix(hooks): check extraction hashes before declaring newer files stale
A checkout can write unchanged source after the tracked graph. Consult the exact extraction-manifest row when timestamps look newer; keep real content changes, uncertain evidence and pending updates advisory. Reuse the manifest writer’s streamed digest and preserve conservative fallbacks.

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

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 8a8234a582)
2026-11-03 21:36:49 +00:00
ajbmachon 2fc643effd perf(extract): release edge keys and per-file rows once they are used
The alias de-duplication kept one JSON string per edge in the corpus; keep a
16-byte digest instead. Drop that table, and the per-file rows and raw calls,
as soon as call resolution has finished with them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 87f090744a)
2026-11-03 21:36:30 +00:00
ajbmachon 088a40766f perf(resolve): hold one parsed file at a time in symbol resolution
The JS, Python and Java passes kept every file's source and syntax tree
until the last pass ended, so resolution held the whole corpus in memory.
Merge the JS and Python passes into one loop per file; each fact list keeps
its order. Java pass 2 only needs the imports, so keep those instead of trees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 3b74a0afb3)
2026-11-03 21:36:30 +00:00
ajbmachon 787f5fd026 perf(load): do not hold graph.json rows and the graph at once
Loading kept every parsed row until networkx had copied it, and a separate
copy of each repeated string. Hand rows over as they are used and share
repeated strings. Drop the TypeError retry at these sites: networkx>=3.4 is
required, and a retry over consumed rows would return a partial graph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 34d86aafca)
2026-11-03 21:36:30 +00:00
safishamsiandClaude Opus 4.8 123da822a5 chore: release 0.9.102 with the go/kotlin/python/solidity/js, build-guard and perf batch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 19:47:52 +00:00
safishamsiandClaude Opus 4.8 924be16018 chore: combined AST cache schema 37 for the solidity/python/kotlin/go extractor fixes
#4985, #4972, #4956 (#4935) and the Go cluster #4966/#4853/#4934 each change
per-file extractor output; fold them into one schema-37 entry (#4956 shipped
without its own bump) so warm caches re-run the affected extractions.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 19:47:02 +00:00
nothariharan 6be19949d6 feat(go): dispatch interface method calls to implicit implementers
A call through an interface-typed field lands on the interface's method
node, and nothing joins it to the concrete method, because Go types
satisfy interfaces implicitly and the shared interface_dispatch pass
only reads `implements` edges. So the concrete method loses every caller
that goes through the interface.

The Go extractor now stamps interface type nodes with
metadata {"language": "go", "kind": "interface"}, and a new
graphify.go_dispatch pass infers implementers from method sets (every
method name the interface requires, own and embedded) and feeds those
pairs to resolve_interface_dispatch. Empty interfaces, type-set
constraints, interfaces embedding an interface outside the corpus, and
interfaces with more than ten structural implementers are skipped; an
unexported requirement only matches types in the same package. The AST
cache schema is bumped so cached Go extractions pick up the stamp.

(cherry picked from commit 97ccefff72)
2026-11-03 19:46:14 +00:00
nothariharan d90f9f5342 fix(go): resolve member calls on receivers typed from another package (#3368)
1695efae resolves a Go member call through the receiver's declared type,
but only when that type is declared in the caller's own package:
_go_single_type_name drops a qualified_type (`pkg.T`) because no bare
local name can stand for it. A dependency held as a field is almost always
typed from another package (`*plugincontext.Provider`, `plugins.Client`),
so the common case of #3368 still produced no calls edge, including when
the struct is declared in a sibling file (fdd25f7b).

The file's import of `pkg` is exact evidence of which `T` is meant. The
type table now keeps `pkg.T` as written, and _resolve_go_member_calls binds
it only to a `T` whose node carries the import path the caller imports
`pkg` from. Each Go type node records that path (`_go_package_path`, from
go.mod), and the incremental resolution context forwards it, so an
unchanged declaring file still answers on an update.

A sibling file's struct field (`_go_fields`) is stored as
`<import path>.T`, settled by the declaring file's imports: the method
file reading it, like Grafana's datasources.go reading
`HTTPServer.pluginClient plugins.Client`, need not import `pkg` itself.

Stdlib and out-of-corpus types stay unresolved and are not parked. The
qualifier also settles two packages declaring the same `T`, which the
bare-name path must leave alone.

Bumps _AST_CACHE_SCHEMA to 34 so cached Go extractions re-run.

(cherry picked from commit 048685ada1)
2026-11-03 19:45:14 +00:00
xiongjianxu 8ed0f30698 fix(go): resolve same-file member calls through receiver types
Resolve same-file member calls through declared receiver types, preserve lexical receiver bindings, and keep bare package calls distinct from methods.

Refs #4962

(cherry picked from commit 4872e284df)
2026-11-03 19:41:59 +00:00
Deepjyoti-Sarmah d7bff93019 fix(resolve): don't bind a bare call to a class its caller can't reach (#4935)
`class Screen : Activity() { fun title() = getString(1) }` got an INFERRED
`calls` edge to `Prefs.getString`, a method of an unrelated class. A bare call
can only name a member of the caller's own class, a superclass or an enclosing
class, but the corpus-wide name match accepted the only `getString` it found.
Activity is outside the corpus, so nothing in the graph says it declares
getString, and the guess landed on the wrong class.

When a class in the caller's chain extends a class with no source file, keep
only candidates that are not class members, that belong to the chain, or that
the file imports by name (`import pkg.Obj.member`, `import static`). Callers
whose whole chain is in the corpus are untouched, so a receiver lambda such as
`with(p) { getString() }` keeps the edge it has today, and top-level functions
still resolve. This mirrors the unresolved-base guard the C# resolver already
uses.

(cherry picked from commit f4723706a7)
2026-11-03 19:41:46 +00:00
Deepjyoti-Sarmah 3844e681f2 fix(kotlin): attribute calls inside an init block to the class (#4935)
An `init { ... }` block parses as `anonymous_initializer`, which the engine
never visited, so a call inside it produced no raw call at all. The block has
no node of its own, which left nothing to attach the edge to.

Property initializers already solved this in #2565 by pushing the expression
onto `initializer_nodes` with the enclosing class as owner. Do the same for
`init`, including the file-node fallback a property initializer in a nested
class gets, so the two ways of running code at construction agree.

This changes extractor output, so the AST cache schema needs the usual
maintainer bump; cached Kotlin results keep missing these edges until then.

(cherry picked from commit 21b79abe08)
2026-11-03 19:41:46 +00:00
Deepjyoti-Sarmah 209b2a5b4e fix(kotlin): resolve a Kotlin call to an overloaded method (#4935)
Java gives every overload of a method the same node id, because the id carries
no parameter types, so a type holds two `method` edges to one target.
`_resolve_kotlin_member_calls` counted list entries instead of distinct ids, so
`Logger.overloaded("a")` found two candidates, read them as an ambiguous name,
and wrote no edge. The same happens for overloads in a Kotlin `object`.

Count distinct ids. Two different methods of one name on one type still cannot
exist, and two same-named classes still stop at the receiver lookup, so the
god-node guard is as strict as before.

(cherry picked from commit 55f54d3091)
2026-11-03 19:41:46 +00:00
Deepjyoti-Sarmah be413f32a7 test(kotlin): pin the Kotlin/Java call edges that already resolve (#4935)
Before changing the resolvers, pin the shapes the fixes must leave alone: a
Kotlin call to a non-overloaded Java method, a property-initializer call
(#2565), two same-named classes staying ambiguous, and members inherited from
an in-repo base in Kotlin and Java.

(cherry picked from commit fc13ed5ab6)
2026-11-03 19:41:46 +00:00
Shubham Padkonde dce3af740e fix(extract): resolve Python module instance method calls
Recognize direct constructor bindings at module scope while rejecting shadowed, rebound and uncertain receivers. Preserve inferred provenance and invalidate old AST cache entries.

Fixes #4970

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 9ebe3d91fb)
2026-11-03 19:41:33 +00:00
rohit-jsfreaky 874173c583 fix(solidity): resolve ../ imports to the real file
A Solidity import was joined to the importer's folder without normalising it,
so `import "../utils/Errors.sol"` from contracts/proxy/ pointed at a dangling
contracts/proxy/utils/errors.sol stub whose id kept the checkout's absolute path.
Normalise the joined path like the other extractors do (os.path.normpath).
OpenZeppelin Contracts v5.4.0: 87 -> 681 of 681 Solidity imports_from edges reach
a real file; no node ids carry the checkout path any more.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 192966f075)
2026-11-03 19:41:32 +00:00
safishamsiandClaude Opus 4.8 ddf0c08bc1 chore: translate #4967 comments to English and restore the default-export docstring
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 19:41:16 +00:00
xiongjianxu 5bab54d8d6 fix(js): resolve calls through default-exported object methods
Refs #4963

(cherry picked from commit fadb09db1a)
2026-11-03 19:40:38 +00:00
safishamsiandClaude Opus 4.8 2460bab3b9 chore: translate the ignored-paths pruning comment to English (#4969)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 19:40:30 +00:00
xiongjianxu 90e1b5f343 fix(extract): report paths skipped by ignore rules
Refs #4965

(cherry picked from commit 71958934cf)
2026-11-03 19:40:14 +00:00
jinsoo a328198f84 perf(resolution): index edges by source file for the #3252 repoint (#4980)
The #3252 repoint step in _resolve_cross_file_imports scanned every
edge in the corpus once per Python file with import targets, so the
pass cost files x edges.

Index the edges by source_file once, the first time a file needs it,
and visit only the importing file's edges. Each index entry keeps the
edge's position in all_edges, so a file's edges are visited in the
same order as before. The loop only rewrites edge["target"], so the
index stays valid while it runs.

On a corpus with 4,115 Python files and 360,996 edges, graphify update
went from 3:36 to 2:55 with an unchanged graph topology.

The new test counts full passes over all_edges: 10 before the fix
(8 importing files + 2), at most 3 after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fjj5WaN6sDPLQ2gWGnkGob
(cherry picked from commit c35850fa83)
2026-11-03 19:40:06 +00:00
Deepjyoti-Sarmah f9fbd6daf0 test(build): cover edge repoint, incremental update and write-back for ghost folds (#4955)
An edge into a folded ghost lands on the survivor, an ordinary update
that brings a new AST node next to a saved semantic twin no longer
raises, and build_merge(dedup=False) followed by to_json round-trips
each of the three folds.

(cherry picked from commit 539fc6286f)
2026-11-03 19:40:05 +00:00
Deepjyoti-Sarmah 7fe71dda9f fix(build): don't count intentional ghost folds as drops in build_merge (#4955)
The #479 guard in build_merge excused one legitimate collapse, the #1799
doc twin. The #1145, #3344 and #3705 folds that build_from_json performs
on purpose looked like unexplained losses, so an on-disk graph holding
such a twin could not be updated through build_merge(dedup=False): the
saved nodes are stamped by shape on load, which makes the AST twin the
canonical node, and the fold runs even under dedup=False.

Excuse an id the fold mapped onto a survivor that is still in the graph.
A survivor that is gone excuses nothing.

(cherry picked from commit 9839bc9aec)
2026-11-03 19:40:05 +00:00
Deepjyoti-Sarmah fde54b56c3 fix(build): report ghost folds on the dedup remap channel (#4955)
build_from_json folds a semantic ghost into its AST twin (#1145), a
document node that names a file into that file (#3344), and a bare
method into its AST method (#3705). Entity dedup already reports its
folds as {merged-away id: survivor} on G.graph (#4940) so to_json's
shrink guard can excuse them; the ghost folds were never reported.
to_json re-derived the first two from labels and missed the third, so
a saved method ghost made it refuse to write.

Record the ghost folds on the same channel, and merge into it in build()
instead of overwriting it. to_json already pops the key before it
serialises the graph.

(cherry picked from commit 2e6831e85b)
2026-11-03 19:40:05 +00:00
Deepjyoti-Sarmah 7a64ccfb61 test(build): pin the build_merge guard behaviours that already hold (#4955)
Clean graphs, semantic-vs-semantic duplicates under dedup=False, ghosts
with their own rationale (#4896), ambiguous file labels and
prune_sources are all left alone by build_merge. Pinned first so the
guard change that follows cannot loosen them.

(cherry picked from commit 8d3c88f9a2)
2026-11-03 19:40:05 +00:00
safishamsiandClaude Opus 4.8 8e6a6d2129 docs: date the 0.9.101 changelog section
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 19:16:39 +00:00
safishamsiandClaude Opus 4.8 197db0140b docs: changelog for the build-guard, semantic-evidence and C++ extractor batch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 19:08:43 +00:00
safishamsiandClaude Opus 4.8 0a4408b177 chore: bump AST cache schema to 36 for the C++ extractor fixes
#4951 (type-alias exact-spelling binding + salted alias contains edge),
#4946 (receiver typing from parameters and fields), #4920 (split-header
owner binding via _cpp_qualified), and #4921 (local-callable suppression)
all change per-file C++ extractor output, so warm caches must re-run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 19:08:04 +00:00
azizur100389 bd318e933c fix(cpp): keep local callable values out of global call resolution
Refs #4917.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit a8cf1d4103)
2026-11-02 19:07:35 +00:00
azizur100389 9466cac7e5 fix(cpp): fail closed on conflicting qualified type identities
A pre-existing same-kind ID collision must not supply positive owner evidence. Add a namespace-collision regression.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit f1716db97c)
2026-11-02 19:06:42 +00:00
azizur100389 a1f7d89f1e fix(cpp): bind split-header definitions to their included owner
Refs #4916.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 405f5dfd4f)
2026-11-02 19:06:42 +00:00
madhusudanpatnaik b492c8f05b fix(cpp): bind alias references by exact spelling, keep a salted alias's contains edge
Two follow-ups to the declaration-id registry (#4854, #4904), both visible
on C++ aliases.

Since #4904 split case-only twins apart, `using Session = int;` (or
`typedef int Session;`) and `void session()` in one file are two nodes, but
DeclIdRegistry.lookup normalizes the name and walks kinds in a fixed order
with "fn" before "alias", so `Session s;` bound to session(). lookup now
prefers the one declaration spelled exactly like the reference and falls
back to the kind order only without one. Registering aliases as "type"
instead would merge them with a same-kind case twin: doctest's
`using string = basic_string<...>` and `class String` collapsed into one
node. On nlohmann/json this change moves 14 `std::string` references in
doctest.h from `class String` to the `string` alias they name; fmt, leveldb,
googletest, express, zod, okio, guzzle and 12 Swift, Java, C#, Scala,
Python and Ruby repos are unchanged.

The C++ alias site also decided whether it minted a node before the
registry could salt its id, so an alias whose id spells its file's own id
(`using cpp = int;` in a.cpp) got a node but no `contains` edge. Read that
off seen_ids after decl_node_fn, as the Swift alias site does.

AST cache schema 34 -> 35.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d0da57d8b1)
2026-11-02 19:05:55 +00:00
nothariharan d3b314d92e fix(cpp): type receivers per function and keep untyped receivers bound in-file
Review follow-ups to the previous commit.

The receiver table is one dict for the whole file, filled first-write-wins,
so `void g() { Response r; }` retyped `r` in `void f(Request& r)` and f's
`r.send()` went looking on Response. Build each function's table on its
own (a local still shadows a parameter there), then drop any name the file
types two different ways, including a field declared with different types
in two classes. An ambiguous receiver gets no type rather than a guess.

Defer a member call only when its receiver is typed. `auto w = make();
w.paint()`, smart pointers and range-for variables have no table entry, and
deferring them dropped the in-file edge they had on v8.

(cherry picked from commit 539e96f821)
2026-11-02 19:05:45 +00:00
nothariharan ffbdae50c2 fix(cpp): bind x.m() by the receiver's type, not the file's same-named method
A C++ member call with a variable receiver fell through to the file-wide
bare-name map, so `void render(Base* b) { b->draw(); }` in a file that also
defines `Derived::draw` produced an EXTRACTED edge to Derived::draw, the one
the static type rules out, and no edge to Base::draw.

Defer `x.m()` / `x->m()` to _resolve_cpp_member_calls like JS/TS already
do (#4598). With the parameter and field typing from the previous commit,
`b` is typed as Base and the call reaches Base::draw (INFERRED). An untyped
receiver now gets no edge instead of a name guess. `this->m()` and
`Foo::m()` keep their existing in-file binding.

(cherry picked from commit 971f564076)
2026-11-02 19:05:45 +00:00
abhay-codes07 92bb7fd189 test(cpp): make the shadowing test a real same-name block shadow with a decisive edge
Review follow-up: the old test declared a differently-named local (T2, not T),
so it never exercised shadowing, and its assertion passed on an empty result.
Now a parameter Thing T is shadowed by an inner-block local Other T, and the
call binds to Other::Ready — which resolves only if the local wins the
first-write-wins fold (locals before parameters); a params-first regression
leaves Thing (no Ready) and yields no edge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JJbLfztSxm2tH5cJwBbe9q
(cherry picked from commit 8d355f919e)
2026-11-02 19:05:45 +00:00
abhay-codes07 2128bca775 fix(cpp): type member-call receivers from parameters and class fields (#3215)
_resolve_cpp_member_calls types a receiver from cpp_type_table, which was
populated ONLY from local variable declarations - parameters never entered
it, so a call through `const Thing& T` / `Thing* P` / `Thing V` (the
dominant C++ idiom for passing state) was silently skipped while the
identical call through a local resolved. TS/JS have an explicit
augmentation pass for exactly this; C++ had none.

Two halves:

  * the per-file table now folds in the enclosing function's parameters
    (_cpp_parameter_types) and class/struct member declarations
    (_cpp_field_types), in C++'s own shadowing order - a local beats a
    parameter beats a field, enforced by the table's first-write-wins;
    the same precision rules as locals apply (class-like type nodes only,
    qualified names keyed by their simple tail, multi-declarator and
    builtin-typed entries contribute nothing);
  * the resolver's capitalized-receiver arm treated `T.IsOk()` as an
    explicit type name and bailed when no type called T exists - but a
    capitalized receiver is very often a VARIABLE (parameter T, field
    Inner). When the explicit-type lookup finds no unique type, it now
    falls back to the file's var->type table exactly like the lowercase
    arm, mirroring what the C# resolver already does for Pascal-cased
    locals; a table miss still bails rather than guessing.

_cpp_declarator_name learns field_identifier (fields use it where locals
use identifier). Chained receivers (B.Inner.IsOk()) stay deferred.

(cherry picked from commit 16a41b38c9)
2026-11-02 19:05:45 +00:00
safishamsiandClaude Opus 4.8 cfd9846667 fix(build): narrow independent-evidence test to genuine provenance (#4896)
#4927's _has_independent_semantic_evidence counted metadata and captured_at
as evidence, but extract.py attaches both to ordinary INFERRED mention
ghosts, so those ghosts would stop folding into their AST file-self twin and
proliferate as duplicates on real graphs. Keep only rationale, source_url,
author and contributor. Add a regression test that a metadata-only ghost
still folds.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 19:04:58 +00:00
Ethan-Ethan-Ethan 18813bbb41 fix(watch): handle multi-source AST aliases without semantic collision
Some AST extractors emit multiple records with the same ID, already coalesced by build. Re-key all those records consistently using the original AST ID, retaining coalescing while separating independently evidenced semantic nodes. Full/incremental coverage. Refs #4896 #4927. AI-assisted tests and implementation by OpenAI ChatGPT (GPT-6).

(cherry picked from commit 3304457602)
2026-11-02 19:04:02 +00:00
Ethan-Ethan-Ethan 8daebd8e0f docs: describe same-ID AST semantic preservation contract
Refs #4896 and #4927.

(cherry picked from commit 1dfae3bb31)
2026-11-02 19:04:02 +00:00
Ethan-Ethan-Ethan 0c786ea667 fix(watch): preserve semantic metadata on AST ID collisions
Keep old semantic IDs stable on full and incremental YAML AST extraction; source-qualified alias fresh AST identities and retarget fresh AST edges. Check same-ID provenance downgrades before publishing even when node count grows. Regression coverage includes colliding file nodes, sourceless AST placeholders and full/incremental re-extraction. Refs #4896 #4927. AI-assisted implementation and tests by OpenAI ChatGPT (GPT-6).

(cherry picked from commit fa4f0fad51)
2026-11-02 19:04:02 +00:00
Ethan-Ethan-Ethan 1c2b17d8e6 fix(build): retain YAML semantic provenance across AST upgrades
A full code rebuild can newly AST-extract YAML sources whose legacy semantic file-self nodes carry independent rationale. Preserve those records even on the same (source_file,label) key, and account for evidence-free twins by exact source identity after AST label disambiguation. Cover multiple same-basename YAML sources and maintain strict fail-closed behavior.\n\nRefs #4896, follow-up to #4927. AI-assisted implementation and tests: OpenAI ChatGPT (GPT-6).

(cherry picked from commit f6280e98f0)
2026-11-02 19:04:02 +00:00
Ethan-Ethan-Ethan 7612ac7c30 fix(build): preserve independently sourced semantic file evidence
Pass 2b's label-only file-node fold may delete distinct semantic records whose separate source documents explain the same named file. Preserve records with source-specific evidence, and mirror the predicate in the shrink guard so a true loss remains fail-closed. Add independent-rationale, cold-reload, edge, and simple-mention regression cases.\n\nRefs #4896; builds on #4778/#4779.\nAI-assisted implementation and tests: OpenAI ChatGPT (GPT-6).

(cherry picked from commit c381636027)
2026-11-02 19:04:02 +00:00
ayushcodes10 863a024b3b Add regression tests for the cross language alias gate
Covers both the clustered build path and the raw no cluster write
path with the reported Dart to Java shape: an unambiguous old stem
alias whose only claimant is in a different, known language family
than the dangling edge naming it must not resolve.

(cherry picked from commit 1776eed2bd)
2026-11-02 19:03:51 +00:00
ayushcodes10 7f7c0ed441 Gate the build alias index on language family
The alias index maps every old stem spelling of a node to its
canonical id, committing an alias only when exactly one node claims
it. That uniqueness check protects against two same stem files in
one language racing for the same bare alias, but nothing checked
whether the one claimant left standing was even in the same language
as the edge naming it. A dangling Dart type reference and an
unrelated Java file of the same name both collapse to the identical
bare old stem alias, and since only the Java file ever registers it,
the alias committed unconditionally and bound the Dart reference
onto the unrelated Java file, producing the only cross language edge
in the whole corpus.

Kept the alias index separate from the main normalized id map instead
of merging it in directly, and added a small language family check
consulted only when falling back to an alias: skip the candidate when
the edge's own file and the alias target's file are both in a known
and different language family, permissive whenever either side's
family is unknown so a legitimate same language or provenance less
alias still resolves exactly as before. Applied at both places the
alias index is consulted, the clustered build path and the raw no
cluster write path, so they keep resolving endpoints identically.

(cherry picked from commit 00acbbeb68)
2026-11-02 19:03:51 +00:00
azizur100389 f5c126d8a3 test(skill): cover deletion-only semantic manifest preservation
Refs #4914.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 02f09f1437)
2026-11-02 19:03:50 +00:00
Andre Brait 19f865361d fix(watch): preserve saved semantic evidence on AST id collisions
(cherry picked from commit 6e0de8f9f2)
2026-11-02 19:03:50 +00:00
Deepjyoti-Sarmah 7566615de3 fix(guard): a saved node dedup folded into a twin is not a lost node (#4940)
to_json refused a valid --update when entity dedup merged a re-extracted
node into a twin: the saved id was no longer in the new graph, so the
#479 guard called it lost and the previous graph.json stayed on disk.

Treat a saved id as present when dedup folded it into a survivor that is
in the new graph. A survivor that is itself gone excuses nothing, so a
real loss beside a merge is still refused and only it is named. The
node-count check gets the same allowance, counting N merged ids as N - 1
when the survivor is new this run and N when it is a saved id.

Full rebuilds were refused the same way and are fixed by the same change.

(cherry picked from commit 4c3b38ba6e)
2026-11-02 19:03:49 +00:00
Deepjyoti-Sarmah 4c81e6f5a9 feat(build): carry the dedup merge map on the built graph (#4940)
build() passes remap_out to entity dedup and stashes the result on
G.graph['_dedup_remap'], next to the existing _dedup_collapsed count.
take_dedup_remap() reads and removes it. to_json drops it before
node_link_data runs, because that would otherwise write G.graph into
graph.json. Nothing reads the map yet.

(cherry picked from commit 268513afff)
2026-11-02 19:03:49 +00:00
Deepjyoti-Sarmah e7bf2adb33 feat(dedup): report which ids deduplicate_entities merged away (#4940)
The write guard has to know whether a saved id disappeared because dedup
folded it into a survivor or because the node was lost, and dedup is the
only place that knows. Add an optional remap_out dict that is filled with
{merged-away id: surviving id}. Callers that do not pass it see no change.

(cherry picked from commit 89f34e1449)
2026-11-02 19:03:49 +00:00
Deepjyoti-Sarmah ba6d292bae test(guard): pin that the #479 write guard still refuses a real loss (#4940)
The guard compares saved semantic ids against the new graph. A fix for
#4940 must excuse ids that entity dedup folded into a twin without
excusing ids that are simply gone. These three cases pass today and
fence the guard's existing job before it is touched: an update with
nothing merged or lost writes; a saved node that vanished is refused and
named; a re-extracted node dropped after the merge is refused.

(cherry picked from commit 54423fc26f)
2026-11-02 19:03:49 +00:00
safishamsiandClaude Opus 4.8 2ab621790f test(cache): update order-independence salt test for case-preserving keys
#4937 made the file_hash salt case-preserving (dropped the .lower() on the
absolute-path fallback), but the existing order-independence test still
asserted the lowercased salt. Update its exp_abs to match the written-case
salt so it pins the new behavior instead of the retired one (#4925, #4937).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 18:10:44 +00:00
safishamsiandClaude Opus 4.8 cd1400f25f chore: release 0.9.101 with the hook, rust, llm, rebuild, watch and cache batch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 18:03:31 +00:00
safishamsiandClaude Opus 4.8 739f34d8ce chore: bump AST cache schema to 35 for the rust call-resolution and case-preserving cache fixes
#4944 resolves Rust module-qualified calls, #4945 links calls inside
expression-macro arguments, and #4937 keeps cache keys case-preserving
(which also shifts the POSIX salt digest for uppercase-bearing paths).
All three change cached output, so warm caches must re-run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 18:02:45 +00:00
Deepjyoti-Sarmah ff8ddf5458 fix(cache): open word-count files through os_long_path (#4925)
cached_word_count() had the same key-path-as-file-path mistake. Stat the raw long-path-safe file, key the index by the case-preserving identity, and pass the caller path to compute().

(cherry picked from commit 002d31e3d6)
2026-11-02 18:02:14 +00:00
Deepjyoti-Sarmah 99b8da78be fix(cache): open hashed files through os_long_path (#4925)
A cache key is not a file handle. Keep the raw caller path for is_file(), stat() and read_bytes(), and add the Windows long-path prefix only on that I/O path. The stat-index key comes from the normalized identity.

(cherry picked from commit 54e6ba2343)
2026-11-02 18:02:14 +00:00
Deepjyoti-Sarmah 5c4a858940 fix(cache): keep Windows cache keys case-preserving (#4925)
os.path.normcase lowercases a path on Windows, but case sensitivity belongs to the volume. A Windows process can reach a case-sensitive WSL share, where README.md and readme.md are two files. Normalize separators and strip the extended-length prefix, then keep the caller case in the key and salt.

(cherry picked from commit 78448a0405)
2026-11-02 18:02:14 +00:00
Deepjyoti-Sarmah 4d678b4ab9 test(cache): pin Windows case-sensitive path handling (#4925)
The regression needs Windows normalization and a case-sensitive filesystem. The fixture takes the win32 branch on a case-sensitive temp dir, then checks hashing, semantic cache round trips, case-variant siblings, aliases and the word-count stat index.

(cherry picked from commit bcd81af5b6)
2026-11-02 18:02:14 +00:00
nothariharan bce0d5624e fix(rust): scan only expression macros, and let a parsed call win the dedupe
Review follow-ups to the previous commit.

Any `name(...)` inside any macro was taken as a call, so DSL macros
(diesel `table!`, `quote!` with `#name(...)`, `html!`) produced calls the
code never makes. Scan only the std and log macros whose arguments are
plain expressions, and skip a name after `#`.

The in-file macro edge took the (caller, target) pair first, so a real
`compute(2)` later in the same function was deduped behind the INFERRED
token-pattern edge. Macro edges are now added after the function bodies
are walked, only for pairs no parsed call produced.

(cherry picked from commit f92f62e16f)
2026-11-02 18:02:14 +00:00
nothariharan fdb288fd5b fix(rust): link calls written inside macro arguments
Tree-sitter keeps a macro's arguments as a flat token tree, so
`println!("{}", f(x))`, `assert_eq!(f(), 1)` and `vec![f()]` had no
call_expression and the call produced no edge: `explain f` showed no
callers for a function used only inside formatting or assert macros.

Scan each macro invocation's token tree for an identifier followed by a
`(` group and treat it as a bare call. A name after `.` or `::`, a name
followed by `!`, uppercase names (constructors and variants) and the
builtin/trait-method blocklists are skipped. An in-file match is INFERRED,
since a token pattern is weaker evidence than a parsed call; anything else
goes to the cross-file pass like any other bare call. macro_rules! bodies
are macro_definition nodes and are not scanned.

(cherry picked from commit 309f9b1341)
2026-11-02 18:02:14 +00:00
nothariharan afb177911f fix(rust): keep module-path calls inside the caller's crate and out of local names
Review follow-ups on the rebased #2135.

- `crate::util::f()` stopped matching at `crate` without checking which
  crate the candidate is in, so in a workspace it bound to another crate's
  util.rs. A candidate must now share the caller's crate root (nearest
  Cargo.toml, else the directory above `src`).
- `crate::b::helper()` in a.rs went through the in-file bare-name lookup
  first and bound to a.rs's own helper. A module-path call binds in-file only
  for `self::f()` or an inline `mod m { .. }` declared in that file.
- Module names starting with `_` were rejected (`'_'.islower()` is False);
  only an UpperCamelCase segment means a type.
- Methods are skipped as candidates: a module path names a free function.

(cherry picked from commit ef748fd9f0)
2026-11-02 18:02:13 +00:00
Nicolas Cristobal 07f61e1bdd fix(rust): resolve module-qualified calls via qualifier-verified cross-file resolution
Unresolved scoped calls (module::function()) were dropped at extraction,
making the dominant idiomatic intra-crate call form invisible to the graph
(a real production caller showed 0 dependents while grep found it).

Keep the #908 bare-name guard, but stop discarding the qualifier — use it
as the verification key. The qualifier is verified right-to-left against
the candidate's file path: the last segment must BE the defining module
(<seg>.rs or <seg>/mod.rs), every remaining segment must match the
successive parent directory, stopping at crate/super/self. Candidates are
restricted to Rust sources, and a qualifier bound by a use from outside
the crate (use std::fs; fs::read()) is skipped at extraction via the
file's use roots. Exactly one survivor or bail. Uppercase qualifiers
(Type::method / Enum::Variant) keep their existing skipped behavior.
Emitted as EXTRACTED (confidence 1.0): the module is named explicitly in
source — the same reasoning as the qualified-class-method passes
(#1446/#1533). The verification lives in one shared helper
(rust_scoped_call_survivors) used by both cross-file passes, so scoped
entries can never reach bare-name resolution in either.

Real-world Rust crate (~200 files, 14k edges): +138 EXTRACTED,
-388 INFERRED (the #908 class shrinking), no regressions on
bare-name-called control symbols.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(cherry picked from commit 9cb9d5824f)
2026-11-02 18:02:13 +00:00
azizur100389 3d772b9778 fix(watch): evict excluded linked-worktree source records
Refs #4912.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 237840b578)
2026-11-02 18:02:08 +00:00
AndresDiagoM 7750ba8cef fix(watch): don't wait forever when msvcrt.locking is unsupported
On Windows, _rebuild_lock treated every OSError from msvcrt.locking as
"another rebuild holds the lock". On a filesystem that cannot byte-range
lock at all (the WSL share \wsl.localhost raises EINVAL on every call),
the blocking `graphify update` CLI slept in a `while True` forever, and
the non-blocking git hooks queued their change and returned, with no lock
holder ever left to drain the queue.

Only EACCES/EDEADLK now count as contention. Any other errno is treated
as "locking unsupported": the rebuild proceeds without a lock and a
warning on stderr names the lock file. That path does not take over
.rebuild.lock (no PID write, no unlink on release), because a WSL-side
flock holder may own it and unlinking it would let a second WSL-side
caller in on a fresh inode (#4273). An empty lock file this call created
only to probe the lock is removed again before the rebuild.

Fixes #4924

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f91cc874d1)
2026-11-02 18:02:07 +00:00
Deepjyoti-Sarmah 93b7a9c1e3 feat(extract): a flagless extract that ingests docs clears the code-only scope (#4923)
Running `extract` without --code-only on a corpus with docs, past the API-key
check, is an explicit move back to a full graph, so the recorded scope is cleared.
An aborted run (no key) and a corpus with no docs leave it alone, so a plain
`extract` cannot silently drop the scope.

(cherry picked from commit e0b76cdac3)
2026-11-02 18:02:02 +00:00
Deepjyoti-Sarmah b80cd8384b fix(rebuild): include the code-only scope in the no-change skip key (#4923)
The #4740 gate skips a rebuild when inputs and build state match. The scope
changes what a rebuild writes, so it has to be part of that state; otherwise
flipping the scope with unchanged files would be skipped as "No relevant changes".

(cherry picked from commit bfb5b86b56)
2026-11-02 18:02:02 +00:00
Deepjyoti-Sarmah 2207cf2265 fix(rebuild): keep a --code-only graph code-only on hook/update/watch rebuilds (#4923)
_rebuild_code now reads the recorded scope and skips the .md/.mdx/.qmd AST
quick-scan for a code-only graph. Doc nodes already in the graph are left as they
are, matching how --code-only already treats the semantic layer (#2923). No new
parameter: the hooks, `graphify update` and `graphify watch` all go through
_rebuild_code, so every entry point is covered.

(cherry picked from commit 1ddd8f103b)
2026-11-02 18:02:02 +00:00
Deepjyoti-Sarmah 9e6f271ae9 feat(extract): record the --code-only scope in .graphify_build.json (#4923)
Persist `code_only` beside `excludes` and `gitignore` (the #1886/#1971 pattern)
so a later rebuild can tell a code-only graph from a full one. Nothing reads it
yet; this commit changes no rebuild behaviour.

test_explicit_exclude_replaces_persisted_setting_with_custom_out asserted the
whole file equals {"excludes": [...]} after a --code-only run; the file now also
carries code_only, so the expectation includes it.

(cherry picked from commit a504674847)
2026-11-02 18:02:02 +00:00
Deepjyoti-Sarmah f3421ff133 test(rebuild): pin that a --code-only graph stays code-only across rebuilds (#4923)
A graph built with `extract --code-only` grew .md/.mdx/.qmd nodes on the next
hook, `graphify update` or full rebuild, because the rebuild has no CLI flag and
nothing recorded the scope. These tests drive the real CLI and a real post-commit
hook and assert on the resulting graph only, with controls proving a rebuild still
tracks new and deleted code and that a default graph still gets doc nodes.

They fail on this commit by design; the following commits make them pass.

(cherry picked from commit 6ee4c59e22)
2026-11-02 18:02:02 +00:00
nothariharan f3cdf6b651 fix(llm): write a held sliced file in chunk order, not completion order
Review follow-up. With max_concurrency > 1, slices finish in any order, and
the held results were joined in that order, so the cached entry's node
order changed from run to run and a cache-served build churned graph.json
(the #1632 problem). Join them by chunk index.

(cherry picked from commit 299fc1a36f)
2026-11-02 18:02:01 +00:00
nothariharan f2ef7024fe fix(llm): cache a sliced file only once every slice has succeeded (#4943)
An oversized document is split into FileSlice units, and each slice's
checkpoint saved under the parent file with merge_existing=True. Nothing
recorded that sibling slices were still pending, so after the first slice
the parent had a complete-looking entry. A run interrupted at that point
served the head of the file as the whole file, and check_semantic_cache
reported nothing left to extract.

Hold a sliced parent's results in memory until its last slice returns, then
write them in one save. A whole file in the same chunk is still checkpointed
right away. A slice that raises leaves its parent unsaved, and the parent is
added to the result's _partial_files, so the caller's final save stamps it
partial instead of writing the other slices' nodes as the complete file.

Entries written by earlier interrupted runs still look complete; a semantic
cache prompt or schema bump would be needed to invalidate them.

(cherry picked from commit dad35d8143)
2026-11-02 18:02:01 +00:00
Andre Brait dea2e695bc fix(hook): drop the self-claimed exemption from the search nudge
The search nudge ended with 'Grep works best once the graph or an earlier
read has pointed to the exact file and lines.' An agent can claim the
'earlier read' half for any grep, including the first exploratory one, so
the nudge excused the very search it fires on. Say instead what each tool
is for: the graph finds where something lives, and grep finds exact text
in files the graph has already named.

(cherry picked from commit 757737f684)
2026-11-02 18:02:01 +00:00
Andre Brait 049c8647df fix(hook): leave sed/awk flag clusters, continued pipes and stdin programs quiet
Review follow-up: `sed -Ei`/`-ni` edit in place, a pipe continued on the
next line or written `|&` still feeds the next command, and an awk or sed
program with no file operand reads stdin. None of them searches the
codebase. Quoted spans become one placeholder word, so a quoted program
still counts as an operand.

(cherry picked from commit 5ce9bfb04b)
2026-11-02 18:02:00 +00:00
Andre Brait c6040bdbd3 fix(hook): count sed and awk run on files as searches
The Bash search guard matched grep, rg, find and friends, so an agent that
had already been nudged could keep searching with `sed -n 40,80p file` or
`awk '/x/' file` and never be nudged again. Run on files, those are a grep
or a read of the codebase by another name.

They count only when they open files themselves: on the receiving end of a
pipe they reshape another command's output, and `-i` edits in place, so
neither case fires.

(cherry picked from commit 227b76acd2)
2026-11-02 18:02:00 +00:00
safishamsiandClaude Opus 4.8 32e5efe935 chore: bump AST cache schema to 34 for the merged go/python extractor fixes
#4933 (python bare-call), #4931 (go method-value via field) and #4932 (go
var-init type refs) were merged on GitHub but each changes AST-cached
output and deferred its schema bump; one combined 33->34 bump so cached
Python/Go extractions re-run. #4929 (namespace packages) is a post-cache
pass and needs none. Opens the unreleased 0.9.101 changelog.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 16:01:28 +00:00
Safi 96fa042152 Merge pull request #4932 from nothariharan/fix/go-package-var-type-references
fix(go): reference the types a package-level var initialiser names (#2360)
2026-11-01 16:00:28 +00:00
Safi 5f7d7e80ac Merge pull request #4931 from nothariharan/fix/go-field-method-value
fix(go): link a method value reached through a receiver field (#1566)
2026-11-01 16:00:24 +00:00
Safi 87fa551c57 Merge pull request #4933 from nothariharan/fix/python-bare-call-not-enclosing-method
fix(python): don't resolve a bare call in a method to a method
2026-11-01 16:00:20 +00:00
Safi 2fcbdc020d Merge pull request #4929 from nothariharan/fix/python-pep420-src-namespace
fix(python): resolve imports across PEP 420 namespace packages under src/
2026-11-01 16:00:16 +00:00
nothariharan 590c77d89c fix(go): reference the types a package-level var initialiser names (#2360)
#2360 walks a package-level `var` initialiser for calls owned by the file,
but the types named there were still dropped: `new(T)`, `new(*pkg.T)`, a
composite literal `pkg.T{}` / `&T{}`, and the declared `var x pkg.T`. A file
holding only a google/wire set, `wire.Bind(new(Iface), new(*Impl))`, then
referenced nothing and was reported as yielding no symbols.

The file now gets a `references` edge (context `variable_type`) to each such
type, collected with the same _go_collect_type_refs and ensure_named_node a
struct field uses, so `pkg.T` resolves through the import and an external
type is parked on its import path exactly as a field type is. A closure body
inside the initialiser is function code and is left alone.
2026-11-01 18:24:02 +05:30
nothariharan f3e50225ed fix(python): don't resolve a bare call in a method to a method
A bare `f()` in a Python method body reads locals, enclosing functions,
module globals, then builtins; methods are only reachable through
self/cls/the class. The call walk's bare-call fallback used the file-wide
label_to_nid map, which also holds method names, so a method calling an
imported or module-level function of its own name (`AsyncTemplate.get_build_status`
calling the imported `get_build_status`) got a false EXTRACTED self-loop.

When that fallback lands on a method and the call is not in the body of
that method's class, look the name up in a method-free map instead; with no in-file hit the call
goes to raw_calls and the cross-file resolver binds it through the import.
Module-function recursion and self/cls calls are unchanged.
2026-11-01 18:22:23 +05:30
nothariharan 6bb5913dac fix(go): link a method value reached through a receiver field (#1566)
61e864a7 records a method value passed as an argument (`routing.Wrap(s.Health)`)
as an indirect raw call, but only when its operand is a plain identifier. A
handler held as a field of the receiver, `m.UseMiddleware(hs.ContextHandler.Middleware)`,
has a selector operand, so it was skipped and the method got no edge.

The argument walk now also accepts `self.field.M` when `self` is the method's
own receiver, and records it the way the direct-call branch records
`self.field.M()`: the field as `member_receiver`, the receiver's type as
`field_owner`. _resolve_go_member_calls then types it through the caller's
table or the owner struct's fields in a sibling file (#3368) and emits the
INFERRED `indirect_call`. A field whose type is declared nowhere links and
parks nothing, as before.
2026-11-01 18:22:15 +05:30
nothariharan eaa4aba022 fix(python): resolve imports across PEP 420 namespace packages under src/
In a monorepo of namespace distributions (pkgsql/src/airflow/..., pkgpresto/src/airflow/...,
no __init__.py anywhere), the package-root pass skipped every file because it found no
initializer, so an absolute import across distributions dangled. The importing class lost
its base, its inherited self.method() calls were dropped, and imported functions fell back
to INFERRED name matches.

When no initializer is found, take the nearest src/ ancestor as the import root. Modules
directly under src/ and stdlib-named namespaces are left alone, and the existing guard still
leaves a module claimed by two src roots unresolved.
2026-11-01 17:15:08 +05:30
safishamsiandClaude Opus 4.8 f5155baddd chore: bump version to 0.9.100
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 00:43:59 +00:00
safishamsiandClaude Opus 4.8 24f342adfe chore: bump AST cache schema to 33 (scala + terraform); changelog for the second 0.9.100 batch
#4856 (scala extension-method scoping) and #4861 (terraform portable ids)
change per-file AST output and are AST-cached, so one combined 32->33 bump.
Fixes the stale 'schema 30' in ARCHITECTURE.md that #4861 introduced. Adds
the 0.9.100 changelog for the second batch; #4794 landed Concern A only
(parallel-edge preservation); its TS tagged-template masking is held pending
a real failing fixture.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 00:29:31 +00:00
ensell-yes 1954192a8c fix: preserve graph relations and tagged templates
(cherry picked from commit 016d9d6ad1)
2026-11-01 00:28:31 +00:00
yUm1k4 50e812321f fix(terraform): discard scope metadata outside scan root (#4858)
(cherry picked from commit 88fe59718c)
2026-11-01 00:25:03 +00:00
yUm1k4 14d1f4d2bd fix(terraform): preserve cached IDs across project moves (#4858)
Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 0335efb73f)
2026-11-01 00:25:03 +00:00
berce 20b002a518 fix(install): remove every platform's user skill on uninstall
(cherry picked from commit 253a6f2303)
2026-11-01 00:24:27 +00:00
safishamsiandClaude Opus 4.8 6667a491e8 fix(prompt): escape the backslash in the [^\\W] node-id rule (for #4799)
#4799's new wording put `[^\W]` in the non-raw _EXTRACTION_SYSTEM
string, which raises SyntaxWarning: invalid escape sequence '\W' (a
SyntaxError in a future Python). Escape it to `[^\\W]`; the rendered
runtime prompt is byte-identical (`[^\W]`) and the markdown fragments are
unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 00:23:31 +00:00
dupeisen 8dd649952c fix(prompt): describe the node-ID class ids.py actually produces
The extraction prompt told the model "Node ID format: lowercase, only
`[a-z0-9_]`", but `ids.normalize_id` keeps every word character after
casefolding, so a non-ASCII path keeps its letters:

    docs/tz/ЛЗ4_обоснование.md  ->  docs_tz_лз4_обоснование
    文档/中文名.md               ->  文档_中文名

Nothing can satisfy both halves of that instruction. For a non-ASCII path the
model improvised a stem — differently per chunk and per run — and
`_semantic_id_remap` had no canonical id to remap onto, so the AST node and the
semantic nodes for one file landed under different ids. #3103 reported this and
was closed without a fix; the wording is unchanged on v8 and lives in three
places, not one.

All three now state the rule the code implements: word characters only, which
is `[a-z0-9_]` for ASCII input while non-ASCII letters and digits are kept.
The ASCII half is unchanged, so no ASCII corpus produces different ids.

The rule text is in two skillgen fragments, so the committed skill artifacts are
regenerated with `python -m tools.skillgen` rather than edited by hand, per the
contributing guide. `tools/skillgen/expected/` is refreshed with `--bless`.
`--check` reports all 134 artifacts in sync.

Tests: tests/test_prompt_id_rule_matches_ids.py (5 tests) asserts that no prompt
surface claims ASCII-only ids, that `make_id` keeps Cyrillic and CJK, and that
ASCII input is still lowercased ASCII (the rule was not relaxed). The three
"no ASCII-only claim" assertions fail on unmodified v8; the two behaviour
assertions pass both ways, since `ids.py` was already correct — only the prompt
lied about it.

Fixes #4432

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit bf29da0292)
2026-11-01 00:22:31 +00:00
Divakant Pandey 8dff9e380c fix(scala): scope extension methods to their receiver type (#2044)
extension_definition has no name of its own, so the walk fell through to
the default recursion and every extension method became a file-level
function with no edge to the type it extends.

Handle it in _scala_extra_walk: take the receiver from the first
non-using parameter clause (head of a generic, last segment of a
qualified type; none for the extension's own type parameter) and walk
each body member under it. The receiver id comes from ensure_named_node,
so a same-file class keeps its one node and a type from another file gets
the sourceless stub the corpus rewire collapses onto its definition,
never a sourced duplicate (#1402). body is a repeated field, which is
why this doesn't go through the class branch.

The enum-case half of #2044 already landed in 35207e9b.

(cherry picked from commit e07794aa00)
2026-11-01 00:22:14 +00:00
akash kalita 611ea9e2dd test(llm): cover Claude prompt cache overrides and unsupported endpoints
Cover enabled, disabled, invalid, and unsupported caching scenarios in normal and deep modes. Isolate the override from ambient environment. Follow-up to Graphify-Labs/graphify#4855 and #4835.

Co-Authored-By: Codex <codex@openai.com>
(cherry picked from commit 1cb5830668)
2026-11-01 00:21:52 +00:00
akash kalita 1b35dc4c8e feat(llm): allow disabling Claude prompt caching
Build on Graphify-Labs/graphify#4855 for #4835. Preserve caching defaults, endpoint routing, and token accounting.

Co-Authored-By: Codex <codex@openai.com>
(cherry picked from commit 3e91ac2009)
2026-11-01 00:21:52 +00:00
akash kalita 40536ee77e docs(llm): document Claude prompt cache override
Follow-up to Graphify-Labs/graphify#4855 and #4835.

Co-Authored-By: Codex <codex@openai.com>
(cherry picked from commit 73779b8ccd)
2026-11-01 00:21:52 +00:00
Sfahad7 08af9b6aa8 docs: update language count and model backend wording in how-it-works
(cherry picked from commit ec03418b74)
2026-11-01 00:21:14 +00:00
dupeisen 35bf28a14f fix(affected): resolve the reference forms explain already accepts
`explain` resolves a `path::Symbol` reference (#3485) and a dotted Python name
(`pkg.mod.func`, #4366) to a single node. `affected` and `query --seed` answered
"No unique node match" for the very same string, so following the README's own
advice ("use the precise ID returned by the graph") forced a caller through
`explain` first merely to obtain an id.

`affected` also exited 0 on an ambiguous or unmatched seed, so a script could
not branch on the outcome the README documents (3 = ambiguous name, 4 = no
matching node) even though `explain` already follows it.

Both commands share `resolve_seed`, so the fix is one resolution path:

- `resolve_seed` now tries the qualified forms first, by delegating to the
  tiered matcher `explain` uses (`serve._find_node_tiers`). Only the two
  path-qualified forms are delegated: they carry their own disambiguating
  context, so a match is never a guess. A bare name keeps going through the
  existing tiers, where an exact-name tie must stay unresolved rather than be
  broken by graph-iteration order (test_resolve_seed_bare_name_tie_still_returns_none).
- New `resolve_seed_outcome` reports whether a failure was ambiguity or a miss,
  so the CLI can pick the documented exit code. The ambiguous case reuses
  `serve._ambiguity_message`, so the same name reads identically in `explain`
  and `affected`.
- `format_affected` takes an optional pre-resolved `seed`, so the CLI does not
  resolve the same query twice.

Tests: new tests/test_affected_seed_reference_forms.py (8 tests) covers both
resolved forms, the bare-name tie that must stay unresolved, and the three exit
codes. I verified the resolution assertions fail on unmodified v8. One existing
test asserted the old exit 0 for an unmatched absolute seed; its intent (#2706:
never resolve to a wrong node) is preserved and only the exit-code assertion
changed.

Fixes #4792

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 8537a59402)
2026-11-01 00:21:12 +00:00
Deepjyoti-Sarmah 992428e6d8 test(extract): drop unused helper from the #4874 fixture
(cherry picked from commit e360f14b8a)
2026-11-01 00:21:10 +00:00
Deepjyoti-Sarmah 5945b5a538 fix(extract): let JVM member calls bind across Java and Kotlin (#4874)
(cherry picked from commit cbb24a10bf)
2026-11-01 00:21:10 +00:00
Deepjyoti-Sarmah 128f08c3f4 test(extract): pin Kotlin member calls into Java (#4874)
(cherry picked from commit 986eb17c26)
2026-11-01 00:21:10 +00:00
Deepjyoti-Sarmah e4f02657f8 fix(extract): resolve Java/Kotlin imports through one JVM index (#4874)
(cherry picked from commit cc108a48c6)
2026-11-01 00:21:10 +00:00
Deepjyoti-Sarmah 4412039f53 test(extract): pin Java/Kotlin import and inheritance resolution (#4874)
(cherry picked from commit 4d0f82f95f)
2026-11-01 00:21:10 +00:00
Jason Daniel 0fff3d8e06 fix(llm): count cached prompt tokens in claude input_tokens (#4835)
With the system prompt cached, Anthropic reports those tokens in
cache_read_input_tokens and cache_creation_input_tokens, not in
input_tokens. _call_claude() read only input_tokens, so cost.json
under-counted every call by the whole system prompt (graphify review
on #4855).

Add both cache fields back into input_tokens, the same way the
claude-cli path already does. Token totals match what they were before
caching was turned on.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 2d4a579590)
2026-11-01 00:21:07 +00:00
Jason Daniel e0736ac6a0 fix(llm): cache the claude backend system prompt (#4835)
extract --backend claude sends one messages.create call per file, and
every call re-sent the same extraction system prompt at full input price.

Send the system prompt as one text content block with
cache_control={"type": "ephemeral"}. The first call writes the prompt to
Anthropic's prompt cache, and later calls read it at the cache-read price.
Output is unchanged.

Tests check the block shape in normal and deep mode, and that two files
send an identical block, since the cache only hits on an identical prefix.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit d10177516c)
2026-11-01 00:21:07 +00:00
berce 45e2917073 fix(kilo): remove the skill references on uninstall
(cherry picked from commit bb01ab02f6)
2026-11-01 00:21:05 +00:00
angus joseph barlow 00920b222f fix(export): report a partial backup as no backup and retry it (#3769)
backup_if_protected swallowed per-artifact copy2 failures, so a dated
snapshot whose graph.json never landed still printed the success line
and returned the path — a stale backup surviving the next overwrite
unwarned. The same-day early return also trusted graph.json alone, so
a snapshot missing a sidecar counted as complete forever.

Track failed artifact names, warn on stderr naming them, and return
None when any copy fails. Only early-return when graph.json matches AND
every present source artifact exists in the snapshot, so a partial
snapshot is retried on the next call. The never-raise, never-block
contract is unchanged; the hash check also moves inside the try so an
unreadable snapshot degrades to a warning instead of an exception.

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

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 4eaaa6747c)
2026-11-01 00:21:03 +00:00
safishamsiandClaude Opus 4.8 35bfdd6166 chore: extend schema 32 comment for R/elixir/dart/fortran; changelog for video + extractors
The four @ayushcodes10 extractor fixes (#4902 R, #4900 elixir, #4899 dart,
#4897 fortran) change per-file AST output and are AST-cached; they share
the global 31->32 bump already landed via #4908/#4895. Extend the comment
to credit them, and add the 0.9.100 changelog entries for #4842 and the four.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 23:50:43 +00:00
ayushcodes10 fe35d24530 Add regression tests for Fortran derived type inheritance
Covers a plain extends() clause and the combined abstract, extends()
form both emitting the inherits edge, plus a control confirming a
bare derived type with no extends() gains no spurious edge.

(cherry picked from commit ed08e009e8)
2026-10-31 23:49:25 +00:00
ayushcodes10 8e820e2e90 Emit an inherits edge for a Fortran derived type extends clause
The derived type handler only ever read the type name child of a
derived type statement and ignored the sibling base type specifier
that holds the extends clause, so type, extends(base) :: derived
never produced an inherits edge. Every other OOP capable extractor in
this codebase emits one for its own inheritance syntax, so Fortran
was the one silent gap, and polymorphic dispatch through an abstract
base type had no edge connecting a derived type to the base it
actually extends.

Read the base type specifier alongside the type name, resolve the
base through the same named node helper the inheritance base path
already uses elsewhere in this file, and emit the inherits edge.

(cherry picked from commit 201b8e8a50)
2026-10-31 23:49:25 +00:00
ayushcodes10 8652055ed2 Add regression tests for a multi constraint Dart mixin on clause
Covers a mixin on clause naming two superclass constraints, asserting
both get an inherits edge and the second one's generic argument
still surfaces as a reference, plus a control confirming a single
constraint on clause still resolves exactly as before.

(cherry picked from commit 7b3bf2fa30)
2026-10-31 23:49:14 +00:00
ayushcodes10 462b86213c Resolve every superclass constraint in a Dart mixin on clause
A mixin's on clause may list several comma separated superclass
constraints, unlike extends, which Dart only ever gives one target
since classes have single inheritance. The header parser read only
the single type name right after extends or on and stopped there, so
every constraint after the first in an on clause was silently
dropped: no node, no inherits edge, and its generic argument never
surfaced as a reference either.

Factored the generic argument reader into its own helper and added a
loop that, only for on, keeps consuming further comma separated
entries. Extends still only ever reads one entry, so its behavior is
unchanged. The later relation mapping block now walks every entry
collected this way instead of a single base class and generics pair.

(cherry picked from commit 5303a33d54)
2026-10-31 23:49:14 +00:00
ayushcodes10 e51618a9bc Add regression tests for a bare call scoped to its own module
Covers two modules in one file each defining a same named function,
asserting a bare call binds to the caller's own module rather than
the unrelated sibling. Both candidates share an identical label, so
the assertion checks the resolved target's node id directly rather
than a label pair, since a label only check cannot tell the two
apart and would pass either way. A control confirms a bare call to a
genuine sibling within the same module still resolves.

(cherry picked from commit 39ede03b0f)
2026-10-31 23:49:06 +00:00
ayushcodes10 e471f80b52 Scope a bare Elixir call to the caller's own module first
The in file resolver for an unqualified call built one flat label to
id table mapping a bare function name to a node id across the whole
file, with a later definition silently overwriting an earlier one
while the table was built. In a file with two modules that each
define a same named function, a bare call made from inside one
module resolved to whichever module's definition the walk reached
last, not to the caller's own sibling function, misattributing the
call to a completely unrelated module.

Removed the flat table. Extended the existing qualified call lookup,
already keyed by container and name for Mod.fun() calls, to also
register a top level def under its own file container, then resolve
a bare call by checking the caller's own container first and falling
back to the same import and use scope chain the cross file pass
already walks. This is the same scoping invariant already enforced
across files, now applied to the in file case too.

(cherry picked from commit 7286098d7d)
2026-10-31 23:49:06 +00:00
ayushcodes10 d48684c848 Add regression tests for the contains inheritance keyword
Covers a setRefClass that inherits via contains now getting its
inherits edge, plus a control confirming R6Class's own inherit
keyword still works alongside it.

(cherry picked from commit bf306cce2d)
2026-10-31 23:49:01 +00:00
ayushcodes10 80f2712c05 Recognize contains as an R class inheritance keyword
R6Class spells its superclass argument inherit, but setClass and
setRefClass both spell the identical argument contains instead. Only
inherit was checked, so a setRefClass or setClass that inherits via
contains silently lost its inheritance edge, with no error, since
both class constructor forms are routed through the same member
scanning function.

Recognize contains alongside inherit when looking for a class's
superclass argument, reusing the exact same base name lookup,
external class node creation and inherits edge already in place for
inherit.

(cherry picked from commit 9043a52bad)
2026-10-31 23:49:01 +00:00
safishamsiandClaude Opus 4.8 6629497fd1 chore: relock after the av<19 cap (#4842)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 23:48:22 +00:00
Cursor Agent 6a056e3a8c fix(video): keep PyAV below 19 so faster-whisper can open audio
faster-whisper 1.2.1 decodes with av.open(..., metadata_errors="ignore").
PyAV 19.0.0 removed that argument, and the video extra resolved av 19 on
Python 3.12+, so transcription raised TypeError before any audio was read.
PyAV 16.1.0 through 18.1.0 still accept the keyword. The compatible range
is av>=11,<19, on the same interpreter marker as faster-whisper. [all]
carries the same constraint. Relocking also records the package version
as 0.9.97, matching pyproject.toml.

Co-Authored-By: Grok <noreply@x.ai>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
(cherry picked from commit 01757166f9)
2026-10-31 23:47:51 +00:00
safishamsiandClaude Opus 4.8 16f18aff33 chore: extend AST cache schema 32 comment for PHP const-refs; changelog for 0.9.100
#4908 (case-collision ids) carried the 31->32 bump; #4895 (PHP class-level
initializer const refs) also changes AST output and shares that global bump,
so extend the comment to credit it. Opens the unreleased 0.9.100 section.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 23:45:51 +00:00
Deepjyoti-Sarmah bed3864d31 perf(resolve): index reference edges by source for #4909
The #4854 stub-binding pass scanned every edge once per import fact. That made a full rebuild O(imports x edges): 14m7s on a 21k-node TS corpus, versus 26.8s on 0.9.48. Group reference edges by their emitting source file once, then scan only that file's edges per import. The 21k corpus now rebuilds in 25.5s, and the written graph is identical.

(cherry picked from commit d6eec6db06)
2026-10-31 23:44:11 +00:00
Deepjyoti-Sarmah ecec030cf8 test(resolve): pin linear reference binding for #4909
(cherry picked from commit dd7fcd1264)
2026-10-31 23:44:11 +00:00
berce dc2ab47d84 fix(ids): keep a type and a function differing only in case apart
DeclIdRegistry reused the id of any declaration that normalized alike, so class Foo
and function foo collapsed into one node. Reuse now needs the same kind or the same
spelling, which keeps TS class + namespace merging. Bump the AST cache schema.

(cherry picked from commit 9c44667f5f)
2026-10-31 23:44:04 +00:00
Tanmay Shah 2c97ae1b55 docs(skill): say when a graph is worth building (#4829)
The skill goes straight to the build steps, so an agent choosing its own tool
for a one-off lookup gets no steering toward a plain search. A build can cost
minutes and tens of thousands of tokens when docs need semantic extraction.

Add a short passage before the steps: query a graph that already exists, search
directly for one targeted lookup, build when the corpus or question calls for
it. An explicit /graphify is still followed as asked. It is two paragraphs
because the lean core has an 800-line limit.

The passage goes in the core, aider and devin fragments, and generated files
are regenerated. It is an addition to the monoliths, so its two exact lines are
sanctioned in the round-trip check.

Fixes #4829

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f2e5b95bb1)
2026-10-31 23:43:29 +00:00
jitendarmahara 3a6a14e265 fix(extract): resolve PHP const-ref scope to real classes only
Address review on #4895: resolve the Scope::MEMBER class scope to an existing
local node instead of minting a stub, skip self::/static::/parent:: (which
otherwise linked to the member name), and reduce a fully-qualified scope to its
class segment so it no longer creates a synthetic raw-name target.

Adds edge-case tests for self/static/parent and fully-qualified scopes.

(cherry picked from commit d3e8f2f98a)
2026-10-31 23:43:23 +00:00
jitendarmahara 28c591b9b3 fix(extract): link PHP Scope::MEMBER accesses in class-level initializers
Class constant / enum-case accesses (`Role::Viewer`) in const values, property
defaults and parameter defaults (including promoted constructor properties)
produced no edge: the call-graph pass only walks function bodies, so these
class-level initializers were never visited. Emit their `references_constant`
edges from the enclosing class during the structural walk.

Adds regression tests covering all four positions plus a method-body control;
they fail before the change and pass after.

Fixes #4648

(cherry picked from commit f609a5931a)
2026-10-31 23:43:23 +00:00
Alex Tumanov 66481def88 fix(analyze): match isolated question reasons to graph layers
Keep code-only Suggested Questions focused on possible missing edges while
preserving the documentation-gap explanation for semantic graphs.

Fixes #4886

AI-Assistance: OpenAI Codex
(cherry picked from commit 2f942fd5cc)
2026-10-31 23:43:18 +00:00
Luke J ed34596a0c fix(hooks): decode git rev-parse paths as UTF-8
_hooks_dir and _rev_parse_path read git's path output with text=True and
no encoding, so Python decodes it with the locale codec. On Windows that
is cp1252, while Git for Windows prints paths as UTF-8. In a linked
worktree git returns an absolute path, so a non-ASCII directory such as
café comes back as café, and hook install creates and writes into that
phantom tree instead of the real .git/hooks.

Pass encoding="utf-8" to both calls. Linux and macOS already decode as
UTF-8, so their behaviour is unchanged.

AI-assisted: Claude Code (reproduction, regression test, PR description).
(cherry picked from commit 2836041acc)
2026-10-31 23:43:13 +00:00
safishamsiandClaude Opus 4.8 a0946f962a chore: bump version to 0.9.99
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 23:36:41 +00:00
safishamsiandClaude Opus 4.8 b2dfe474e2 docs(changelog): 0.9.99 - confidence_score in path/explain/neighbors (#4888)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 23:34:36 +00:00
safishamsiandClaude Opus 4.8 19b9e0fd6e test: reconcile confidence-score output tests with #4881/#4889 (for #4888)
#4888 was built on 0.9.97, before #4881 (path weakest-hop refactor),
#4889 (qualified C# method labels) and #4891 (also_seen) landed. Its
cherry-pick dropped the merge commit that reconciled expectations. Update
the per-hop confidence assertions to carry scores ([INFERRED 0.85]) and
the C# path/explain/neighbor labels to their owner-qualified form
(Exporter.Run, IReport.Build) - the correct composed output of all four
features. Resolved the serve.py conflict by keeping #4881's _path_weakest/
_path_confidence_line and adding only #4888's _confidence_tag, applied over
edge_evidence so parallel/also_seen evidence keeps its scores.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 23:34:21 +00:00
Cursor Agent 13260e3927 fix(serve): print confidence_score in path, explain and neighbors output
graph.json stores a confidence_score next to every INFERRED edge (C#
interface dispatch writes 0.85 / 0.75 / 0.65 by implementer count), but
`path`, `explain` and the MCP shortest_path / get_neighbors renderers only
printed the bare tag, so `[INFERRED]` hid whether an edge was a strong or
a weak inference.

A shared _confidence_tag() now renders a scored non-EXTRACTED edge as
`[INFERRED 0.75]` at all four sites. EXTRACTED stays bare (it is 1.0 by
definition), and a missing, non-numeric, boolean or non-finite score
keeps the bare tag instead of printing a guess.

Tests: tests/test_confidence_score_output.py runs the issue's Report.cs
repro through extract/build and checks CLI explain, CLI path, MCP path and
MCP neighbors; the four output tests fail without the fix.

Fixes #4882

Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
(cherry picked from commit 10559b31b4)
2026-10-30 23:31:15 +00:00
safishamsiandClaude Opus 4.8 f68ad40378 chore: bump AST cache schema to 31; changelog for the hari batch
Go (#4867/#4868/#4866) and Python (#4773) extractor changes alter
per-file AST output and are AST-cached, so one combined _AST_CACHE_SCHEMA
bump 30->31 forces stale caches to re-extract. Install (#4770/#4771) and
the skill reword (#4721) need no bump. Folded into the unreleased 0.9.99.
Each PR omitted its own bump / carried a stale number; the single combined
bump lands here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 23:28:53 +00:00
nothariharan 0581b222c0 docs(skill): resolve the 'do not skip steps' contradiction (#4061)
The fast path tells the agent to skip Steps 1-5 for an existing graph,
then the next paragraph said 'Follow these steps in order. Do not skip
steps.' Reword the latter to defer to the fast path in all three source
fragments (core.md, aider.md, devin.md), and add the reword to the
sanctioned monolith-diff predicates so --monolith-roundtrip accepts it.

Regenerated the 14 split-host skill artifacts and expected snapshots with
tools.skillgen; --check and --monolith-roundtrip both pass.

(cherry picked from commit 41141efaa8)
2026-10-30 23:27:52 +00:00
nothariharan 948938a647 fix(extract): resolve module.func values in Python dispatch tables (#1566)
A dict/list/set/tuple literal of bare function names already yields
`indirect_call` edges, but the same table written with the module
prefix, the usual shape of a plugin registry:

    from payments import card, cash
    PROVIDERS = {"card": card.card_charge, "cash": cash.cash_charge}

got no edge at all, because only bare identifiers counted as values.

Such a value now becomes an `indirect` member raw call, and the Python
member-call resolver binds it through its module arm only: the receiver
must be a module imported into the caller's own file, holding exactly
one callable of that name. It is emitted as the INFERRED
`indirect_call` (0.85, context `collection`) the bare-name path uses,
never to a class used as a value, and never when a parameter or local
shadows the module name. A module-level table resolves from the file
node. The AST cache schema goes to 26 so cached Python extractions
re-run.

(cherry picked from commit 28934b6316)
2026-10-30 23:27:41 +00:00
nothariharan fdd25f7b31 fix(go): type a receiver's field when its struct is declared in a sibling file (#3368)
1695efae types `s.field.M()` through the caller file's own go_type_table.
When the struct is declared in another file of the package, the usual Go
layout, that file has no binding for `field` and the call is dropped, even
for a same-package field type.

Each Go file node now carries the field types of the structs it declares
(`_go_fields`, keyed by struct id), and a self-rooted raw call names the
struct that owns the field (`field_owner`). When the caller's table has no
binding, the resolver reads the owner struct's fields, only when the owner
is a single type declared by a single file. The fields ride on the file
node, not the struct node: every method file emits the struct's id too,
and on an incremental rebuild that fresh copy shadows the declaring
file's. `_go_fields` is carried through the incremental resolution
context, and the AST cache schema goes to 30.

(cherry picked from commit f3b1e7d87a)
2026-10-30 23:26:30 +00:00
nothariharan 61e864a7b1 fix(go): link a method value passed as an argument as an indirect_call (#1566)
A Go handler or callback is registered by passing a method value:
`routing.Wrap(s.Health)`, `r.Get("/p", s.Health)`. The call walk looked
only at what a call expression invokes, so the method got no edge from
its registration and a handler reached only through its route had no
caller.

walk_calls now records each `x.M` argument (on a plain identifier, not an
imported package) as an `indirect` raw member call, typed the way a direct
`x.M()` is. _resolve_go_member_calls resolves it through the same receiver
type, single-declaration and single-method guards and emits an INFERRED
`indirect_call`, as Python and JS do. It is never parked for a merge: a
value argument is as often a field as a method. The AST cache schema goes
to 30.

(cherry picked from commit e724c0c44f)
2026-10-30 23:26:18 +00:00
nothariharan 1c4c3f2c63 fix(go): credit calls in a package-level var initialiser to the file (#2360)
extract_go walks only function and method bodies for calls. A package-level
`var` initialiser was recursed into and never registered as a body, so a
call there, most often inside a `var provider = func(...) {...}` closure
kept as a swappable hook, produced no edge and its callee lost the caller.

A package-level var_declaration is now walked by the existing walk_calls,
owned by the file node: the initialiser runs at package init and has no
enclosing function. A `var` inside a function is unchanged. The AST cache
schema goes to 30.

(cherry picked from commit a05773eb54)
2026-10-30 23:26:10 +00:00
nothariharan b4686ea4af fix(install): write the global OpenCode plugin to ~/.config/opencode (#3398)
A global `graphify install --platform opencode` passed Path(".") as the
plugin base and joined `.opencode/plugins/graphify.js` onto it, so the
"global" plugin landed in whatever directory the command ran from and
loaded only for that project. OpenCode's global plugin dir is
~/.config/opencode/plugins, with no `.opencode/` segment, so the base
path alone could not be swapped.

The plugin helpers now take the OpenCode config dir itself, chosen by
_opencode_dir(): <project>/.opencode for a project install and
~/.config/opencode for a global one. `graphify uninstall` removes the
global plugin as well, and the OpenCode 2 plugin refresh also checks the
global dir. The legacy `.opencode/plugins/graphify.js` entry that older
releases wrote into opencode.json is still matched by its old string.

The slash-command half of the issue no longer applies: v8 has no
_install_opencode_command.

(cherry picked from commit c5cb910b78)
2026-10-30 23:24:56 +00:00
nothariharan 2859f5b9b0 fix(install): give gemini its own global skill dir on Windows (#2800)
On Windows the gemini user-global skill went to ~/.agents/skills/graphify,
the same path the `agents` platform installs to. The two ship different
SKILL.md files, so installing either one overwrote the other, and
uninstalling either one deleted the other's skill, references/ and stamp.

The Windows branch came from #368 on the belief that Gemini CLI prefers
~/.agents/skills there. Gemini CLI reads both ~/.gemini/skills and the
~/.agents/skills alias on every OS (docs/cli/skills.md), with the alias
winning a name clash, so the branch bought nothing and caused the clash.
gemini now uses ~/.gemini/skills/graphify everywhere.

Because the alias wins, a copy an older Windows gemini install left in
~/.agents/skills would hide the new one. gemini install now prints a note
naming that folder instead of deleting it, since it may be a real
`agents` install.

(cherry picked from commit 037fc62cd9)
2026-10-30 23:24:56 +00:00
safishamsiandClaude Opus 4.8 193c9f36b3 feat(path): report the weakest of several equal-length routes (#4881)
Second half of #4881. 'path'/shortest_path returned an arbitrary route
among equal-length shortest paths (nx.shortest_path), so the reported
confidence could reflect a strong route while a weaker route of the same
length existed. Among all shortest paths (bounded at 256 to avoid
exponential enumeration), choose the one whose weakest hop is weakest and
note it was the weakest of N equal-length routes, so the confidence never
overstates the connection.

Factors _path_weakest out of _path_confidence_line and adds
_path_hop_datas / _path_confidence_key / _weakest_shortest_path in
serve.py, used by both the CLI path command and the MCP tool. No cache
bump (path rendering is post-extraction).

Refs #4881. Idea/report by @SyedFahad7.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 23:06:18 +00:00
safishamsiandClaude Opus 4.8 26818d0857 chore: bump version to 0.9.98
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:51:05 +00:00
safishamsiandClaude Opus 4.8 7e7556f09e docs(changelog): 0.9.98 - second batch (file/decl ids, dedup, cycles, js imports, extractors, serve/export/pdf)
13 PRs folded into the unreleased 0.9.98; dups #4869/#4852/#4871 to close
at release. One combined _AST_CACHE_SCHEMA bump (29->30) covers the
output-changing extractors and the file/declaration id change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:47:13 +00:00
safishamsiandClaude Opus 4.8 e71d5ed63e fix(powershell): strip only a known module/assembly extension from a using name
Follow-up to #4847. Its fix stripped any trailing dotted segment, so a
dotted module name with no file extension (using module Az.Accounts)
resolved to 'az' (dropping .Accounts). Restrict the strip to real
module/assembly suffixes (.psm1/.psd1/.ps1/.dll/.exe) so file names like
Helpers.psm1 still resolve to 'helpers' while Az.Accounts keeps its full
name. Adds a regression test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:46:30 +00:00
Deepjyoti-Sarmah d157b98ced fix(resolve): bind cross-file references to declared ids
`ensure_named_node` is per file, so a reference in b.ts to `Ts` declared in
a.ts was minted under an id derived from b.ts, and `@Ts class Other` ended up
pointing at b.ts's own file node (#4854).

The symbol-resolution pass now builds a corpus map of declarations keyed by
(resolved source path, normalized name) from the actual nodes, then uses the
JS/TS import facts to retarget a sourceless reference stub in the importer to
the declaration in the imported module. Keying by path makes the binding exact
when two modules export the same name; the old unique-label rewire could not
choose.

The pass is limited to JS/TS importers and `references` edges so it cannot
disturb CommonJS require bindings or the Python alias handling (Python
aliases are resolved by their own pass).

Refs #4854

(cherry picked from commit 6755a5a7ec)
2026-10-30 22:44:34 +00:00
Deepjyoti-Sarmah 0fa0db50f0 fix(extract): assign unique declaration ids at every file-stem mint site
A declaration whose normal id equals its file node's id took the file's
identity: add_node dropped it, the file carried its callable flags, and a
self-contains edge appeared (#4854). The cause is that file ids are the
path stem and symbol ids are stem + name, so `class Js` in `a.js` and the
file both normalize to `a_js`.

`DeclIdRegistry` assigns ids per file with an availability check:

- the file id is reserved;
- a declaration whose id is taken by the file, or by another declaration's
  salted id, gets `sha1(name)[:12]` appended;
- if that candidate is already in the node set or assigned to another
  declaration, a deterministic counter (2, 3, ...) appends until free;
- the same declaration re-resolves to its assigned id, so reopened classes
  and cfg twins stay on one node;
- a plain duplicate id owned by a real declaration (a prototype owner, a
  redeclared name) reuses that id instead of minting a second node.

Mint sites: the generic class/type and function sites, the JS/TS extra walk
(function, property, const, namespace), the C++ alias, and the prototypes /
exported objects. `ensure_named_node` resolves a declared name from the
registry and never returns the file's own id for a reference.

Standalone extractors with their own file-stem minting use the same registry
at their choke points: rust.py `file_item_nid`, go.py `symbol_nid` /
`type_symbol_nid`, and julia.py top-level declarations. C#/Python keep their
existing `_underscore_salted_nid` result and the new check runs on top of it.

Refs #4854

(cherry picked from commit bcea646b66)
2026-10-30 22:44:34 +00:00
Deepjyoti-Sarmah 41acf8496d test(4854): pin file/declaration id collisions and reference targets
The matrix covers JS, TS, Python, Java, PHP, Ruby, C++, C headers, Rust,
Go, C#, Swift, Kotlin, Scala, and Julia. Each case asserts the file and the
declaration both survive with distinct ids, no self-contains edge, and the
expected containment/ownership edge.

The reference cases go beyond the old cross_file_use fixture, which only
checked the import edge while the decorator reference still pointed at the
file node:

- intra-file decorator and cross-file decorator (including two modules that
  export the same name, where the imported module must win)
- cross-file inheritance
- a legal identifier equal to the salted id cannot steal it
- bundle.min.js keeps its class and method
- Rust struct keeps its node
- prototype methods attach to the salted class
- empty-normalizing names stay skipped (#1899)
- fresh and cache-hit extraction agree
- the AST schema bump documents #4854

The zoo skips a kind only when the control name shows the extractor does not
model that kind at all, so a newly added declaration kind that mints from the
file stem fails here instead of silently dropping a node.

Refs #4854

(cherry picked from commit 1517f89eb9)
2026-10-30 22:44:34 +00:00
ayushcodes10 a5a533a683 Add tests for typeless Go var declarations with composite literals
Cover the var x = T{} and var x = &T{} forms the receiver type table
now types, alongside a control proving a var bound to a plain call
result (no composite literal evidence) still resolves to nothing, just
as the := form already does.

(cherry picked from commit 46b3c002d0)
2026-10-30 22:44:24 +00:00
ayushcodes10 f20856a0ab Type Go var declarations initialized with composite literals
The receiver type table recognized x := T{} (short var declaration) as
evidence that x holds a T, but the same composite literal shape spelled
with var instead, var x = T{}, fell through silently: its var_spec node
has no explicit type field, and the table only read that field. A call
like g.Greet() would then resolve or not depending purely on which form
the author used to create g, with no difference in meaning between them.

Factor the composite literal inference shared by both shapes into one
helper and apply it to a typeless var_spec too, so var x = T{} and
var x = &T{} resolve exactly like their := counterparts. Bump the AST
cache schema so existing caches rebuild with the fix.

(cherry picked from commit 9cd04b030e)
2026-10-30 22:44:24 +00:00
ayushcodes10 bc564dd891 Bump the AST cache schema for the constructor fix
A cache keyed before this fix would keep treating function new as
unmatched, so bump the schema to force a re extraction on upgrade.

(cherry picked from commit 7e80213280)
2026-10-30 22:43:19 +00:00
ayushcodes10 d1d6a42e31 Add regression tests for SystemVerilog constructor methods
Covers function new getting its own node, method edge and parameter
type references, plus a control confirming a function with an
explicit return type still separates it from the method name
correctly now that the return type is optional.

(cherry picked from commit 8f90432379)
2026-10-30 22:43:19 +00:00
ayushcodes10 0406d9bed6 Make the return type optional in a SystemVerilog function header
The function header regex always required an explicit return type
before the method name. A new constructor never declares one, and a
plain function with an implicit one bit return also omits it, so
function new(...), the single most common method in a SystemVerilog
class, matched nothing at all: no node, no method edge, and its
parameter types never got extracted either.

Made the return type group optional and guarded the return type
reference emission so it only runs when a return type was actually
captured.

(cherry picked from commit 147284348f)
2026-10-30 22:43:19 +00:00
nothariharan 0d251fe577 fix(serve): a name spelled exactly wins a lookup tie that is only case
Since #2779 the Go extractor keeps `Run` and `run` apart, but node lookup
folds case: both land in the exact tier and every lookup is refused as a
same-file tie, even one spelled exactly like one of them. The get_node and
get_neighbors tools also lowercased the query before resolving it. A
case-only pair could be reached only by its opaque id.

When the exact tier holds names that are equal up to case and exactly one
label is written as queried, that node is the exact tier and the others
move to the front of prefix. A query in neither spelling, or one spelling
that two files share, is still refused. get_node and get_neighbors pass
the label as written; the tiers fold case on their own.

(cherry picked from commit 507c5f351a)
2026-10-30 22:43:06 +00:00
Tanmay Shah e677fb8093 fix(dedup): keep an AST definer's id when another file's node also defines it (#4859)
When a doc's own path prefixes a code entity's id (pkg.md beside
pkg/test_x.py, id pkg_test_x), both colliding nodes pass the definer key
of _collision_rank and the survivor fell to label length. A terse doc
label took the id, the node carried pkg.md as its source_file, and the
next re-extract of pkg.md deleted it although the code file never
changed.

Rank a non-AST definer right behind the other definers when an AST node
from a file with a different full stem also defines the id and the
non-AST node's own file has no AST definer. The rule applies to any such
non-AST definer, not only docs. The pairs are collected once per dedup
call (_outranked_by_ast), so the rank stays a total order independent of
arrival (#1851). The check is strict on _origin == "ast", like the
ghost pass in build.py, because fresh semantic chunks arrive unstamped.

Unchanged: collisions with at most one definer; a file's AST node and
its same-file semantic enrichment (#2091), even when another file also
has an AST definer; and same-stem twins (x.py/x.html, or slug twins such
as pkg/service.py and pkg_service.py), where an AST twin never outranks
the other. A twin can still be outranked by an AST node from a third
file with a different stem, like any other definer.

Fixes #4859

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit da897c27be)
2026-10-30 22:42:36 +00:00
ayushcodes10 fc2c354919 Add tests for inherited/inline form component nesting
Covers both extract_lazarus_form and extract_delphi_form with a shared
fixture containing an inherited block, an inline frame, and a plain
object sibling after both. Asserts the sibling still nests under the
right parent and that an event handler declared inside the inherited
block binds to that block, not to an ancestor.

(cherry picked from commit b1a37a8ed1)
2026-10-30 22:41:55 +00:00
ayushcodes10 d64b0be4c5 Recognize inherited and inline component blocks in Lazarus/Delphi forms
The lfm/dfm nesting parser only treated a line starting with "object" as
opening a component block. Real form files also declare components with
"inherited" (an ancestor form overriding one of its own components) and
"inline" (an embedded frame), using the identical "Name: Class ... end"
shape. Those blocks never pushed onto the containment stack, so their
closing "end" either silently did nothing or, worse, popped a level the
block never opened, misattaching every sibling that followed to the
wrong ancestor and letting event handlers declared inside the block
bind to the wrong component.

(cherry picked from commit 9dcc549048)
2026-10-30 22:41:55 +00:00
ayushcodes10 672469a342 Add a regression test for a forward referenced superclass
Covers a subclass listed above its own parent in one file, asserting
the parent mints exactly one node (not a split local node plus an
external stub) and that the inherits edge targets that local node.

(cherry picked from commit 0eff25276d)
2026-10-30 22:41:54 +00:00
ayushcodes10 a0dbd6f979 Bind a forward referenced Common Lisp superclass to its local node
ensure_class_ref checked a candidate superclass only against seen_ids,
which fills in file order as the walk reaches each defclass form. A
subclass listed above its own parent in the same file asked before the
parent's node existed, so the check wrongly treated the parent as an
external, cross file class and minted a sourceless stub for it instead.
The real parent then got its own node later under a different id,
splitting one class into two disconnected nodes with the inherits edge
pointing at the wrong one.

A new prescan collects every name a file defines via defclass up front,
mirroring the real walk's own recursion rule, so ensure_class_ref can
tell a forward referenced same file class apart from a genuinely
external one regardless of where in the file its defclass form sits.

(cherry picked from commit ba61a79b46)
2026-10-30 22:41:54 +00:00
ayushcodes10 f475138c33 Add regression tests for Solidity free function using sets
Covers using {freeAdd, freeSub} for uint; emitting a uses edge for
both functions, plus a control confirming the single library
using Lib for uint; form still produces its own uses edge unchanged.

(cherry picked from commit 25cab3e630)
2026-10-30 22:41:53 +00:00
ayushcodes10 a5e01bd206 Emit uses edges for a Solidity free function using set
using Lib for T; names the library directly as a child of the using
directive. using {f1, f2} for T; (free functions bound as members,
legal since 0.8.13) wraps each name in its own using_alias child
instead, so the direct child scan saw nothing and silently dropped
the whole directive, no edge at all for either function.

Also collect type_alias, identifier and user_defined_type grandchildren
nested under any using_alias child, and emit a uses edge for every
name found rather than just the first. The single library form is
untouched since it has no using_alias wrapper.

(cherry picked from commit bf15cc8c68)
2026-10-30 22:41:53 +00:00
ayushcodes10 c797e68f9d Add regression tests for PowerShell using module and assembly names
Covers using module Helpers.psm1 and using assembly System.Data.dll
resolving to the library name rather than its extension, plus a
control confirming using namespace keeps its existing last segment
behavior.

(cherry picked from commit 127f657793)
2026-10-30 22:41:52 +00:00
ayushcodes10 209768ea73 Strip the file extension from a PowerShell using module or assembly name
The using statement handler took the last dotted segment of the value
for all three forms: namespace, module and assembly. That is correct
for namespace, a dotted hierarchy where the last segment is the piece
wanted, but wrong for module and assembly, whose value is a file or
library name with an extension rather than a namespace path. using
module Helpers.psm1 resolved the import edge to psm1 instead of
helpers, and using assembly System.Data.dll resolved to dll.

Branch on the leading keyword: keep last segment splitting for
namespace, but strip the trailing extension for module and assembly,
matching the convention already used elsewhere in this file for
Import Module and dot sourcing.

(cherry picked from commit a84a01165e)
2026-10-30 22:41:52 +00:00
xunguangzlj-cloud 68e63edb1e test(pdf): keep the deterministic timestamp tuple statically sized
Co-Authored-By: Codex <noreply@openai.com>
(cherry picked from commit 634c113bd9)
2026-10-30 22:41:52 +00:00
xunguangzlj-cloud e579278fe3 fix(pdf): scope converted text cache to the resolved source path
Resolve PDF cache keys before memoizing converted text so equal relative paths in different working directories cannot reuse another corpus document. Preserve size/mtime invalidation and share conversion across relative and absolute aliases.

Co-Authored-By: Codex <noreply@openai.com>
(cherry picked from commit b3fe78fd30)
2026-10-30 22:41:52 +00:00
Alex Tumanov 8e9a3d95a9 fix(export): update Cypher node labels on re-import
Match generated Cypher nodes by typed ID and set the display label separately.

AI-Assistance: OpenAI Codex
(cherry picked from commit d643ce33c3)
2026-10-30 22:41:51 +00:00
Mpasha17 9b35e29ac5 fix(build): keep the reverse import of a two-file cycle in the undirected build (#4839)
The undirected build drops the reverse-direction duplicate of a same-relation
pair (#1061). For imports_from/re_exports that dropped edge is the second leg
of a two-file import cycle, so find_import_cycles never saw it and
GRAPH_REPORT.md said "None detected".

Stamp the kept edge with reverse_import when the dropped leg is a runtime
import, and have find_import_cycles add the reverse file leg for stamped
edges. The incremental reconcile treats the stamp as the target file's import,
so it is cleared or carried along with that file.

Co-Authored-By: Grok Bot
(cherry picked from commit 8a953f803a)
2026-10-30 22:41:50 +00:00
jitendarmahara 3ca53c70ac style(extract): trim inline comments on the #4860 import fix
(cherry picked from commit decd4b99de)
2026-10-30 22:41:50 +00:00
jitendarmahara fe55ad7cac fix(extract): resolve relative JS/TS imports with a ?query or #fragment
Relative ES module specifiers that carry a cache-busting query string or
fragment (`./foo.js?v=123`, `./foo.js#frag`) were resolved verbatim via
`start_dir / raw`, so the target file never matched. graphify emitted a
phantom `ref_..._v_123` node instead of an `imports_from` edge, and the
dependent per-symbol `imports` and cross-file `calls` edges were lost too.

Strip the `?query` / `#fragment` from the relative specifier in
`_resolve_js_module_path` before resolving, mirroring the existing Markdown
extractor normalization (markdown.py). Browsers and bundlers resolve the
module as if the suffix were absent. Only the relative branch is affected;
bare and alias specifiers are untouched.

Adds regression tests that fail before the change: unit coverage for the
resolver (query, fragment, both) and an end-to-end extract_js check that the
real file node receives the edge with no phantom, plus a guard that external
modules still resolve externally.

Fixes #4860

(cherry picked from commit 6a10fbe030)
2026-10-30 22:41:50 +00:00
safishamsiandClaude Opus 4.8 e56cdb56b0 docs(changelog): 0.9.98 - also_seen weaker evidence, csharp owner labels, path weakest-hop confidence, Type.Member path endpoints
Covers the SyedFahad7 batch: #4891 and #4889 merged on GitHub; #4892 and
#4893 landed via authorship-preserving cherry-pick (their CI matrix was
gated pending first-contributor approval, so brought in through the local
gate instead). Credit by GitHub PR-author login @SyedFahad7.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:31:50 +00:00
Cursor Agent 24ff9b2c52 fix(path): show an EXTRACTED weakest hop without a score (#4885)
EXTRACTED is 1.0 by definition, and the hop tags (#4882) print it bare, but
the path summary printed "score 1" when an EXTRACTED hop carried a stored
confidence_score. Its score is now ignored both when printing and when
ranking, so an all-EXTRACTED path names its first hop instead of whichever
hop happened to store 1.0. A non-finite score is treated as missing, as in
the hop tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
(cherry picked from commit 659e7db98e)
2026-10-30 22:30:33 +00:00
Cursor Agent 0068826adc feat(path): report path confidence as the weakest hop (#4885)
`graphify path` and the MCP `shortest_path` tool labelled each hop on its own,
so one INFERRED or AMBIGUOUS hop among EXTRACTED ones read as a list of
independent tags rather than marking the whole path. Both now end with one
summary line:

  Path confidence: INFERRED (weakest hop 2: dispatches_to, score 0.75)

A hop's strength is the weakest evidence it carries, its parallel edges and
also_seen entries included; hops are ranked by _CONFIDENCE_RANK, then by the
lowest confidence_score (a missing score never counts as weaker than a present
one), and ties name the first such hop. A hop with no recognised tag makes the
path "unknown" rather than letting the other hops vouch for it. The helper
lives in serve.py and the CLI calls it, so both entry points stay identical.

Fixes #4885

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
(cherry picked from commit 6e6e68a2a1)
2026-10-30 22:30:33 +00:00
Cursor Agent 007cbeccd8 fix(path): let exact names and file names win over a Type.Member reading (#4884)
Review follow-up on #4893.

The `Type.Member` lookup ran ahead of the ordinary tiers, and its not-found
refusal only knew that some type of that name existed. A file name has the
same shape, so `config.json` resolved to a `Config.Json()` method, and
`utils.py` was refused as "no type 'utils' declares 'py'" whenever a `Utils`
type existed and no node carried the bare file name as its label.

The member lookup now runs after the ordinary tiers, only when no node's own
id, label or source path matched exactly, and never for a query that names a
source file (case-insensitive, like the source-path tier). The refusal skips
the same queries, so it only fires for a genuine missing member.

Membership direction now comes from the edge's `_src`/`_tgt` markers, else
the stored arc of a directed graph. An undirected edge without markers is
skipped instead of counted both ways, which let a member pose as its type's
owner: `.Report()` "owned" `Builder`, and `Go.Missing` was refused because
`.Go()` looked like a type with members. The CLI loaders that read a graph
undirected stamp the markers on every link, so they keep resolving.

Tests: a `utils.py` endpoint, `config.json` next to `Config.Json()`, an exact
dotted node id, and undirected graphs with and without markers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
(cherry picked from commit c3ad17788b)
2026-10-30 22:30:24 +00:00
Cursor Agent aa5a00a16b test(path): regression tests for Type.Member endpoints (#4884)
Extracts the issue's Report.cs and checks that `Exporter.Run` / `Run` reach
`PdfReport.Build` through the calls and dispatches_to edges, never through the
file's contains edges, for the CLI and the MCP shortest_path tool. Synthetic
graphs cover a member in two files, same-type overloads, nested types,
direction, a namespace qualifier, a missing member, a literal dotted label,
and an owner that is not a type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
(cherry picked from commit 3bbbeed26c)
2026-10-30 22:30:24 +00:00
Cursor Agent dfd29c489d fix(path): resolve a Type.Member endpoint to the member, not the type (#4884)
A member's label is `.Build()`, so `PdfReport.Build` hit no exact tier and
token scoring picked the `PdfReport` class. `path "Exporter.Run"
"PdfReport.Build"` then printed a class-to-class route through the file as if
it joined the two methods, and `path "Run" "PdfReport.Build"` found nothing,
since no edge leads from a method back up to a class.

`_find_node_tiers` now resolves `Type.Member` (and `Outer.Inner.Member`)
through the type's `method` / `defines` / `contains` edges, after the dotted
Python form and only when no node is literally labelled with the query. The
hits form the exact tier, so `path`, `explain`, get_node and `query` share
them, and several hits are refused with their ids instead of guessed.

A `path` endpoint whose type exists but declares no such member fails closed,
like a `file::symbol` miss (#4264), instead of scoring its way to the type. A
namespace-qualified name is refused the same way, listing the bare type's
same-named members, since the file rather than the namespace owns the type.

Fixes #4884

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
(cherry picked from commit f3003eb31b)
2026-10-30 22:30:24 +00:00
Safi 2daf6874ae Merge pull request #4889 from SyedFahad7/cursor/csharp-method-owner-labels-5c23
fix(csharp): label C# methods with their owning type (#4883)
2026-10-30 22:29:52 +00:00
Safi 3801e527f4 Merge pull request #4891 from SyedFahad7/fix/4881-keep-weaker-evidence
fix(build): keep a collapsed edge's weaker evidence in also_seen (#4881)
2026-10-30 22:29:49 +00:00
d5895eae4b fix(csharp): label C# methods with their owning type (#4883)
Every C# method was labeled `.Name()`, so an interface method and each of
its implementations printed identically (`.Build()` x3) and only the line
told them apart.

The graph build now assigns C# methods an `Owner.Name()` display label,
taken from the source of the method's `method` edge, as the last step of
build_from_json and in both --no-cluster writers (same placement as the
#2032 file-label disambiguation). Ids and edges are unchanged, and a method
with zero or several owners keeps its bare label.

Extraction keeps emitting the bare `.Name()` form that call resolution,
interface dispatch, and the method-ghost index match on. Readers of a
persisted graph normalize back to it: incremental resolution context in
extract(), the build method-ghost and old-stem alias indexes, and the
analyze method-stub predicate.

Fixes #4883

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
2026-10-30 20:59:05 +00:00
3304de1623 fix(build): keep a collapsed edge's weaker evidence in also_seen (#4881)
A same-relation collision keeps the higher-confidence edge (#3711), and the
other copy was discarded, so an AMBIGUOUS or INFERRED duplicate (typically a
semantic-pass edge over an AST edge) left no trace in graph.json. The winner
now lists each other copy's confidence, confidence_score, source_file and
source_location in `also_seen`, weakest first, deduplicated against the
winner and each other so re-feeding graph.json through an update is
idempotent. A malformed `also_seen` read back from disk is sanitized.

When the incoming edge wins, fields only the loser carried are removed from
the stored edge: add_edge merges attribute dicts, so the displaced edge's
confidence_score used to stay on an EXTRACTED winner that had none.

`graphify path` (CLI and MCP shortest_path) unions the also_seen tags into the
hop label, as it already does for parallel edges: [AMBIGUOUS/INFERRED].

Fixes #4881

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Syed Fahad <sfahad2904@gmail.com>
2026-10-30 20:52:22 +00:00
safishamsiandClaude Opus 4.8 0a8cd4e1e3 chore: bump version to 0.9.97
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-27 18:08:07 +00:00
safishamsiandClaude Opus 4.8 e97582681f chore: bump AST cache schema to 29; changelog for the second 0.9.97 batch
OCaml and-chained bindings (#4822) and SystemVerilog task methods (#4774)
change per-file AST output and are AST-cached, so one combined
_AST_CACHE_SCHEMA bump 28->29 forces stale caches to re-extract. The
other PRs in this batch (js, build, detect, resolution, report, wiki,
query) operate on JS-bypassed suffixes or post-extraction, so they need
no bump. Folded into the still-unreleased 0.9.97.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-27 18:01:39 +00:00
safishamsiandClaude Opus 4.8 ef51a3837a fix(wiki): unlink the stale twin on case-sensitive filesystems, don't rename over the fresh file
Follow-up to #4798. Its case-only-relabel sweep ran the two-step rename
unconditionally whenever the on-disk name differed from the produced name
by case. That is right on a case-INSENSITIVE filesystem (APFS, NTFS)
where the two are the same inode, but on a case-SENSITIVE filesystem
(ext4, most Linux CI and production hosts) the run already wrote the
correct content to a distinct file, so renaming the stale lower-case twin
over it silently restored the old body: no missing file, no dangling
link, just wrong content. #4508 never existed on case-sensitive hosts, so
the PR turned a non-bug into a silent corruption there.

Guard the rename with target.exists() and not target.samefile(old): a
distinct inode is a stale twin and is unlinked; the same inode takes the
rename. Adds a content-level regression test (the PR's existence/link
tests pass on both filesystems even with the bug, so they could not catch
this); it fails on a case-sensitive host without the guard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-27 18:00:50 +00:00
dupeisen c65d46d507 fix(wiki): keep the article when a community is relabelled only by case
`to_wiki` writes each article through `write_text_atomic_if_changed`, then
sweeps the `*.md` files the run did not produce. On a case-preserving,
case-insensitive filesystem (APFS, NTFS) the write for `Groups.md` replaces the
contents of the existing `groups.md` entry without renaming it. The sweep then
compared names case-sensitively, saw `"groups.md" not in {"Groups.md"}` and
unlinked the file the same run had just written, so `index.md` linked to a
`Groups.md` that no longer existed.

Comparisons now fold case, and a case-only difference is renamed through a
temporary name so the new case reaches disk. The two-step rename is required
because a case-insensitive filesystem treats source and destination as one
file. `_unique_slug` already folds case when it dedups colliding labels; this
was the remaining case-sensitive comparison.

Tests: tests/test_wiki_case_only_relabel.py (4 tests) covers the article
surviving, the new case landing on disk, no dangling link in `index.md`, and a
genuinely stale article still being swept. The first three fail on unmodified
v8; the fourth passes both ways, which is the guard against over-correcting the
sweep.

Fixes #4508

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 194c7fdbc4)
2026-10-27 17:59:24 +00:00
AndresDiagoM c9c658dd11 fix(build): count label-only AST file twins in the shrink guard (#4778)
build_from_json Pass 2b (#3344) folds a document's mention of a file
(label = the file's path, source_file = the document) into the one AST
file node that label names. _lost_saved_semantic_nodes only knew the
(source_file, label) fold from #4391, so on cluster-only the folded
mention was reported as a lost semantic node. to_json's node-count check
then refused as well, because the saved graph held mention and twin as
two nodes.

The guard now mirrors Pass 2b: a missing semantic node whose label names
exactly one AST file node in the new graph is folded, not lost. Two or
more matches stay lost, as Pass 2b leaves them unmerged. The helper
reports each fold with its twin's id, and to_json discounts only folds
whose twin was already in the saved graph, so a twin new to this run
cannot hide some other node's loss.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d6e286dba4)
2026-10-27 17:59:14 +00:00
ayushcodes10 07e11926b5 Add regression tests for SystemVerilog class task methods
Covers both repaired shapes directly on the shared fixture: a task
method now gets its own method edge and its parameter type is
referenced the same way a function parameter already is, and a type
declared purely as that task's own local variable no longer shows up
as a false field reference on the enclosing class.

(cherry picked from commit 57a359b70b)
2026-10-27 17:58:47 +00:00
ayushcodes10 02e404451f Model a SystemVerilog class task method like a function one
A class method declared task instead of function got no node and
no method edge at all: the class body scanner only ever searched
for a function header, so a task method vanished completely, along
with every parameter type reference it would otherwise have
carried.

The same scanner also stripped only function bodies before looking
for class fields, so a task method's own local declarations stayed
in that scanned text. A locally declared variable of a custom type
inside a task then read as if it were a field of the enclosing
class, since nothing distinguished a task local from a genuine
field once the function strip left it behind.

Added a task specific header pattern mirroring the function one
minus the return type, harvested task methods the same way
functions already are, and stripped task bodies out of the field
scan the same way function bodies already are.

(cherry picked from commit adb15127c3)
2026-10-27 17:58:47 +00:00
ayushcodes10 572fc7e889 Add regression tests for OCaml and chained modules and classes
Covers both repaired chains directly: a module and a class pair
each keep both of their own members, nothing from the second
dropped. A control confirms a lone module or class with no chain
still resolves to its own name and line.

(cherry picked from commit ddf32c80e4)
2026-10-27 17:58:46 +00:00
ayushcodes10 754bbb6da5 Walk every binding in an OCaml and chained module or class
module A = struct ... end and B = struct ... end nests every
binding under the one module_definition node, the same way a
mutually recursive class chain nests every class_binding under one
class_definition. Taking only the first binding of either silently
dropped every module or class after it, along with everything
defined inside it.

Both walks now visit every binding in the chain instead of
returning after the first, each keeping its own line rather than
the shared definition node's line, which only ever matched the
first binding anyway.

(cherry picked from commit 246204ec0b)
2026-10-27 17:58:46 +00:00
barlowa124 fa76a1d503 fix(detect): prune a linked worktree whose main checkout is in the scan root (#4683)
A workspace folder holding a repo and a linked worktree of it as siblings
was indexed twice: every file in the worktree counted as a second copy,
roughly doubling the graph and leaking the copy's paths into reports.

The name-based rules (.worktrees/, <dot>/worktrees/) and .git/info/exclude
cannot cover this layout — the worktree's directory name is arbitrary, and
a workspace root that is not itself a repo has no info/exclude to read.

A linked worktree is unambiguous on disk: its .git is a file pointing at
<main>/.git/worktrees/<name>, whose commondir points back to <main>/.git,
so the main checkout's root is the common dir's parent. When that main
root resolves inside the scan root, the worktree is pruned and recorded
in pruned_noise_dirs.

Deliberately unchanged: scanning the worktree itself still indexes it; a
worktree whose main is outside the root stays (it is the only copy);
submodule gitdirs (no commondir) and bare-repo worktrees (shared git dir
not named .git) are untouched. No git subprocess is used.

Co-Authored-By: Devin <noreply@devin.ai>
(cherry picked from commit 0e1dc8afd4)
2026-10-27 17:58:45 +00:00
Deepjyoti-Sarmah a47deee3af fix: drop inline comments from pnpm workspace globs and skip globs pathlib rejects (#4681)
A quoted workspace value now ends at its closing quote, and an unquoted one
at the first `#` after whitespace, as in YAML. A glob that Path.glob rejects
(ValueError on 3.12 for `**` inside a component, NotImplementedError for an
absolute glob) is skipped with a warning instead of failing the run.

Fixes #4681

(cherry picked from commit ed10daf8e8)
2026-10-27 17:58:44 +00:00
Deepjyoti-Sarmah a9a0d01f43 test: pnpm workspace globs with inline comments and globs pathlib rejects (#4681)
An inline YAML comment after a pnpm-workspace.yaml glob stays in the glob,
so the workspace package is not found and imports of it stay unresolved.
On Python 3.12 a `**` glob with a comment, or a workspace glob pathlib
rejects, raises out of extract() and the whole run fails.

(cherry picked from commit 955fa23e0d)
2026-10-27 17:58:44 +00:00
Thomas Lin 9af467494f fix(build): enforce relation invariant in raw writes
Keep --no-cluster persistence aligned with build_from_json by folding legacy relation aliases and dropping edges that still have no relation.\n\nCo-Authored-By: ChatGPT <noreply@openai.com>

(cherry picked from commit 241aaf0733)
2026-10-27 17:58:43 +00:00
Thomas Lin 51c991bb03 fix(build): drop edges missing relation
Fail closed after relation aliases are folded when an edge still has no relation, rather than persisting an uninterpretable schema-invalid edge.

Refs #4809

Co-Authored-By: ChatGPT <noreply@openai.com>
(cherry picked from commit cacb75ee4b)
2026-10-27 17:58:43 +00:00
ayushcodes10 55a2b6ab53 Add regression tests for the community wikilink fix
Covers a label shaped like a source file, confirming the link now
drops the same suffix the export does and never keeps it, and a
label with no word characters at all, confirming the link uses the
same unnamed fallback the export falls back to rather than naming
something after pure punctuation.

(cherry picked from commit d98054058b)
2026-10-27 17:58:42 +00:00
ayushcodes10 4f9e07c889 Stop the report's community wikilink from drifting from its file
The Community Hubs section builds an Obsidian wikilink from a name it
sanitizes itself, meant to match the real _COMMUNITY_*.md filename the
export writes from the same label. The two had drifted apart: the
report's own copy never stripped a trailing qmd suffix, never fell
back to unnamed for a label with no word characters, never added the
dot prefix a leading dot label needs, never capped an overlong label
the way the export does, and folded only a carriage return or line
feed to a space rather than every control character. Any one of those
left the link pointing at a filename the export never actually wrote
once a vault was built.

A community's label can plausibly be any of these shapes, since the
deterministic fallback name is simply its highest degree member, and
that member can be a source file complete with its own extension.

Delegate to the export's own stem function instead of keeping a
second, independent copy, so the two can never grow apart again. The
one case this still cannot match exactly is the maximum path aware
length budget the export computes from the real output directory,
since generate has no path to recover that; this was already a
separately tracked, longer standing limitation and nothing here makes
it worse.

(cherry picked from commit b5a0a1edff)
2026-10-27 17:58:42 +00:00
andresdiago 79995641ac fix(query): drop "get" filler verbs from query terms
"get" survived stopwording, so a question like "how does X get
authorized" exact-matched framework hubs such as a NestJS Get decorator
import and made it a BFS seed. #1602 guards short low-degree leaves, not
hubs. Add get/gets/got/getting next to work/works/working; node text,
find_node/explain and the all-stopwords fallback are unchanged.

Fixes #4684

Co-Authored-By: OpenAI Codex <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 02e9ce97c8)
2026-10-27 17:58:41 +00:00
smngvlkz c4858593c2 keep js nested functions scoped so same-named calls elsewhere don't bind to them
(cherry picked from commit deb5a1cf56)
2026-10-27 17:58:41 +00:00
safishamsiandClaude Opus 4.8 20dbabb47e chore: add anyio floor to the [all] extra too
The anyio>=4.14.2 security floor added to [mcp] must also appear in
[all], which is the union of every other extra (enforced by
test_all_extra_is_the_union_of_every_other_extra). Keeps [all]
installable with the same floor.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-27 17:33:05 +00:00
safishamsiandClaude Opus 4.8 d8764b4903 docs(changelog): 0.9.97 - security redaction + anyio floor, CommonMark markdown, yaml keys, razor/terraform/cobol/blade/pascal/vbnet/fortran extractor fixes, cli help
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-27 17:27:04 +00:00
safishamsiandClaude Opus 4.8 cc22523c03 chore: bump AST cache schema to 28 for the 0.9.97 batch; floor anyio
The 0.9.97 extractor batch changes per-file AST output for Markdown
(#4790/#4787), YAML (#4784), rationale redaction (#4647), Razor (#4820),
Terraform (#4819), COBOL (#4824), Blade (#4823), Pascal (#4825), VB.NET
(#4821) and Fortran (#4795). Those files are AST-cached, so one combined
_AST_CACHE_SCHEMA bump 27->28 forces stale caches to re-extract. Each PR
omitted its own bump by design, leaving the single combined bump to land
here.

Also floor anyio>=4.14.2 in the mcp extra, above CVE-2026-63374 (the
IDNA 2003/2008 hostname-validation bypass, CVSS 9.3). anyio is only
transitive today and the lock already resolves 4.15.1, but the direct
floor stops a future re-resolution from regressing below the fix. This is
why PR #4780 (a stale, conflicting lock-only rewrite) is not needed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-27 17:26:16 +00:00
Kauhsik Raj 38046fcfa7 fix(security): close redaction gaps in rationale labels
Follow-up to #4566. Credential shapes that still reached rationale labels
in 0.9.93:

- URL userinfo with an empty user (`redis://:pw@host`) or `@` / `/` in the
  password
- PEM private-key body after the BEGIN line
- tokens glued to identifiers by `_` (`AKIA..._prod`, `token_ghp_...`)
- Slack `xoxe-` tokens and JWTs with a short payload segment
- Common Lisp docstrings, which never went through redaction

Rationale labels from every extractor are now redacted centrally in
`_safe_extract`, so a new extractor can't skip it. `sk-` now requires a
digit so hyphenated prose isn't redacted. Bumps `_AST_CACHE_SCHEMA` so
labels cached with credentials re-extract, and terraform reuses
`REDACTED_MARKER`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 147f78628b)
2026-10-27 17:24:54 +00:00
safishamsiandClaude Opus 4.8 a0cea18ddc fix(cli): show usage for a lone 'explain --help/-h' too
Follow-up to #4830, which fixed the same papercut for 'query'. 'explain'
is also a free-text command exempt from the generic --help intercept, so
'graphify explain --help' ran a literal node lookup for the string
'--help' ("No node matching '--help' found") instead of printing usage.
Intercept the exact standalone '--help'/'-h' the same way; a longer
target that merely contains '--help' as a substring still runs as a
lookup. Adds two regression tests mirroring the query ones.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-27 17:24:24 +00:00
Artur Chepenko 97518adbca fix(cli): graphify query --help/-h shows usage instead of running a literal query
A lone "--help" or "-h" with nothing else after `graphify query` was taken
as the literal question text and traversed the graph for it, since --help
is intentionally not intercepted for free-text commands (query, explain,
path, etc.) in __main__._run_cli - a longer question that happens to
contain "-h" as a substring must still run as-is, not be swallowed as a
help request.

This only narrows that to the exact, standalone case: `graphify query
--help` or `graphify query -h` with no other arguments now prints the
command's usage line, while a real free-text question containing
"--help"/"-h" anywhere else still runs normally.

(cherry picked from commit fd839926b7)
2026-10-27 17:22:42 +00:00
dherreraj 281f7395f0 fix(markdown): track fenced code blocks by CommonMark rules (#4787)
The heading parser flipped one boolean on every line starting with
three backticks. So a ~~~ block's lines were parsed as headings, an
inner fence closed a longer outer one (the usual way a doc shows a
fenced example), a backtick run followed by text closed the block,
and a line starting with an inline triple-backtick span opened a
"block" that hid every heading after it.

Track the open fence as (character, run length): a block opens on a
run of 3+ backticks (info string without a backtick) or 3+ tildes, and
closes only on a run of the same character, at least as long, with
nothing after it. Leading whitespace stays accepted at any depth, as
before, so a fence nested in a list item keeps working.

(cherry picked from commit 7b26bc545d)
2026-10-27 17:22:30 +00:00
dherreraj 0d909f18fa fix(markdown): parse ATX headings per CommonMark (#4790)
The heading regex took the whole rest of the line as the label and
required the `#` in column 0. So `## Setup ##` became a "Setup ##"
node (shown as-is by GRAPH_REPORT.md, query and explain), and a heading
with 1-3 spaces of indent got no node, its children attaching to the
previous heading instead.

Match up to three spaces of indent (four is still an indented code
block) and strip an optional closing run of `#` preceded by whitespace.
A `#` that belongs to the text (`C#`, an escaped `\#`) stays, and a
heading that is nothing but hashes mints no node. Node ids for
closing-sequence headings are unchanged, since _make_id already drops
the `#`.

(cherry picked from commit 529e51fadc)
2026-10-27 17:21:42 +00:00
ayushcodes10 217f6da2da Add regression tests for cross file Fortran call resolution
Covers the fix directly: a call to a subroutine implemented in
another module lands on the sourceless stub a single file extract
produces, and on the real node once both files run through the
corpus wide rewire together. A control confirms a same file call is
completely unaffected, still resolving to its own sourced node.

(cherry picked from commit a6e9014163)
2026-10-27 17:21:31 +00:00
ayushcodes10 a306df6db7 Resolve a Fortran call through the subroutine it actually names
A call statement's target id was computed straight from the calling
file's own stem, so a subroutine implemented in another module,
reached through its own use statement, never matched that module's
real node. The edge pointed at an id nothing in the corpus ever
defines, dangling permanently no matter how the called file was
actually written.

Resolved the callee the same way a cross file parameter or return
type already is: the same name in this file wins when it exists
here, otherwise a sourceless stub carries the name for the corpus
wide rewire to collapse onto the real definition once both files
are extracted together. A same file call keeps resolving to its own
node exactly as before.

(cherry picked from commit 5dd81093b7)
2026-10-27 17:21:31 +00:00
ayushcodes10 d2cff2c230 Add regression tests for VB.NET operator declarations
Covers the repaired shape directly: a class overloading an operator
now gets its node, its method edge, and the call its own body makes
to a named helper resolves. A control confirms a plain class with
only Sub and Function members keeps resolving exactly as before.

(cherry picked from commit fa8372d13c)
2026-10-27 17:21:30 +00:00
ayushcodes10 f1b3d54daa Extract a VB.NET operator declaration as a method member
The member loop recognized only method and constructor declarations,
so a class overloading an operator lost it entirely: no node, no
method edge from the class, and since its own body was never
walked either, a call made from inside it, a common shape that
delegates to a named helper, vanished with no edge at all.

An operator declaration is now harvested the same way a method is,
labeled as its own operator kind so it stays distinguishable from
an ordinary method, and its body is walked for calls the same way
every other member's already is.

(cherry picked from commit f44a0e3193)
2026-10-27 17:21:30 +00:00
ayushcodes10 95f5c8a76d Add regression tests for Pascal record methods and operators
Covers the repaired shape directly, against both the tree sitter
path and the regex fallback: a record gets its own node, a plain
method and an operator overload both land as method edges owned by
the record rather than falling back to the module.

(cherry picked from commit eb19efb82f)
2026-10-27 17:21:30 +00:00
ayushcodes10 d5808b1bcf Recognize a Pascal record as a type with its own methods
The regex fallback's type header only matched class and interface,
so a record, the usual shape for an advanced record with methods in
modern Delphi and Free Pascal, never minted its own node at all. Its
method implementations still parsed, but with no owning type to
attach to they fell back to being attributed directly to the
module as free functions instead of as method edges on the record
that actually declares them.

Separately, neither the declaration nor the implementation header
pattern recognized an operator overload, the usual way a class or a
record overloads an operator, so one was dropped regardless of
which kind of type declared it.

Record now joins class and interface in the type header pattern,
and operator joins procedure, function, constructor and destructor
in both the declaration and the implementation header patterns, plus
the keyword set that already lists every one of those routine kinds.

(cherry picked from commit 73c2f83ebf)
2026-10-27 17:21:30 +00:00
ayushcodes10 d94f59c713 Add regression tests for Blade wire:click binding
Covers all three repaired shapes directly: a call with its own
arguments binds the bare name, a directive carrying a modifier like
prevent still binds, and a magic action such as set is left
unbound rather than fabricating an edge to nothing.

(cherry picked from commit 0f7ce0c449)
2026-10-27 17:21:29 +00:00
ayushcodes10 e7f0405934 Bind the bare method name from a Blade wire:click directive
The bare wire:click= pattern never matched a Livewire event
modifier at all, so wire:click.prevent= or wire:click.stop= bound
nothing, the whole directive silently vanishing. A call written
with its own arguments, deleteItem(5), bound to that literal
argument bearing text as the method name, a node no real method
ever matches, since the arguments are not part of the name. A
magic action like $set or $emit is Livewire's own runtime behavior,
not a method the component defines, so binding one fabricated an
edge to something that has never existed.

The pattern now accepts any dotted modifier, the bound text is cut
at the first identifier so a call's own arguments are dropped, and
a value starting with a dollar sign is left unbound rather than
turned into a method name that will never resolve.

(cherry picked from commit 07fb4ea363)
2026-10-27 17:21:29 +00:00
ayushcodes10 0116d9261e Add regression tests for COBOL nested program scope
Covers the repaired shape directly: a paragraph physically back in
the enclosing program after a nested program's own END PROGRAM now
attributes to the enclosing program, not the nested one. A control
confirms two unrelated sibling programs each closed with their own
END PROGRAM still resolve their own paragraphs to themselves.

(cherry picked from commit 9b6704f540)
2026-10-27 17:21:29 +00:00
ayushcodes10 7dea8f19ca Restore the enclosing COBOL program after END PROGRAM
A contained program's own PROGRAM ID switched the active program
with no record of what it switched from. Once that nested program
reached its own END PROGRAM, every paragraph physically back in
the enclosing program kept attributing to the nested one forever,
since nothing ever switched back.

Each PROGRAM ID now pushes the program it is nested under onto a
stack, and END PROGRAM pops back to it. A top level program nests
under nothing, so its own END PROGRAM leaves the stack as it found
it, and two unrelated sibling programs each closed with their own
END PROGRAM are unaffected either way.

(cherry picked from commit 846bb28287)
2026-10-27 17:21:29 +00:00
dherreraj 04f1986cb4 fix(yaml): give YAML keys their own line and their written spelling (#4784)
extract_yaml walked the objects safe_load_all constructs, which drops
two things the graph needs:

- line marks: every key node and contains edge fell back to L1, so
  query/explain cited line 1 for every key (extract_json records real
  lines);
- the written key: YAML 1.1 resolves a bare `on` to True, so every
  GitHub Actions workflow got a `True` node (`<stem>_true`, children
  `<stem>_true_push`), and the `on` entry of _CONFIG_YAML_KEYS could
  never match.

Walk the composed node tree instead (yaml.compose_all with SafeLoader,
same documents in the same order, nothing constructed). Keys come from
the scalar text with their start_mark line; `<<` merges are expanded
the way flatten_mapping does, with an explicit key overriding a merged
one in place and taking its line. safe_load_all still runs first, so an
unsafe tag still errors out before anything is walked, and the config
gate and document labels keep using the constructed values, apart from
the top-level key probe, which now sees the written keys.

(cherry picked from commit 2abe53375d)
2026-10-27 17:21:28 +00:00
ayushcodes10 9107155253 Add regression tests for aliased Terraform provider identity
Covers the repaired shape directly: two aliased blocks of the same
type get distinct nodes with their own attributes, a reference
naming an alias resolves to that exact block and never dangles, a
bare reference with no alias still resolves to the plain id, and a
local literally named provider keeps resolving through its own
value rather than the new alias rule. A plain, single, unaliased
provider block is checked as the unaffected common case.

(cherry picked from commit aa5aa7a45f)
2026-10-27 17:21:27 +00:00
ayushcodes10 1ccc0c16b9 Give an aliased Terraform provider its own node
A second provider block for the same type, distinguished only by
its alias, minted the exact same id as the first, so its own
attributes silently overwrote whatever the first block already
recorded. A provider reference naming the alias, aws.west, read as
a plain head and attr pair the same way a resource reference does,
so it pointed at a node nothing ever minted and dangled.

The alias now folds into the provider block's own id, so each
aliased block gets its own node and attributes. A provider
reference is read through its own address rule instead of falling
through to the generic one, resolving to the exact aliased block it
names, or to the plain id when there is no alias to read. A local
literally named provider, the one name this new rule could
misread, is still walked only by its own value, so it keeps
resolving as an ordinary local rather than as a provider assignment.

(cherry picked from commit 1badebb23c)
2026-10-27 17:21:27 +00:00
ayushcodes10 506d6ff5fb Add a regression test for Razor implements interfaces
Covers the repaired directive directly: two @implements lines on
one component each mint their interface and both land on the
implements relation.

(cherry picked from commit fcb4177026)
2026-10-27 17:21:26 +00:00
ayushcodes10 b69b7510c2 Extract implements interfaces from a Razor component
A component lists one @implements per line for every interface it
satisfies, the same way a class heritage clause does, but only
@inherits ever became a reference. Every @implements interface was
silently invisible, with no edge and no reason given.

@implements now resolves the same way @inherits already does, just
onto the implements relation instead.

(cherry picked from commit 644c68ec97)
2026-10-27 17:21:26 +00:00
safishamsiandClaude Opus 4.8 dac063456b fix(watch): fall back to Timer timeout when watch() runs off the main thread
#4724 wrapped each watch-loop rebuild in _rebuild_timeout(), which arms
SIGALRM. signal.signal() only works on the main thread and raises
ValueError('signal only works in main thread') anywhere else. watch()'s
dispatch loop is run in a worker thread both under test
(test_watch_handler_honors_graphifyignore, gh-928) and when embedded, so
that ValueError escaped the loop's 'except TimeoutError' guard and tore
the watcher down before _rebuild_code ran: a non-ignored .py write never
triggered a rebuild.

Gate the SIGALRM path on threading.current_thread() is main_thread();
off the main thread, use the existing signal-free Timer fallback, which
bounds the rebuild just the same. Adds a behavioral regression test that
runs _rebuild_timeout() off the main thread and asserts it yields without
raising.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-26 12:50:53 +00:00
safishamsiandClaude Opus 4.8 290b7f0b30 chore: bump version to 0.9.96
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-25 19:25:41 +00:00
safishamsiandClaude Opus 4.8 27bc17b5aa docs(changelog): 0.9.96 — add the 18-PR backlog batch (llm/extract/dedup/python/rust/vbnet/ts/js/watch/robot/perf)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-25 18:41:21 +00:00
safishamsiandClaude Opus 4.8 830de39f94 fix: schema 27 + adapt #4726 to _method_of + close #4748 false-skip
- Bump _AST_CACHE_SCHEMA 26 -> 27 for the VB.NET (#4725), Python injected-field
  (#4726), and Rust use-crate-scope (#4699) extraction-output changes; each PR
  shipped a stale 25->26 bump.
- #4726: its method-result block passed the list-valued method_index.get(...)
  straight to _emit_call, which silently dropped the edge since #4734 made
  method_index list-valued; route it through _method_of for the exact method.
- #4748: _inputs_unchanged now treats a scanned file with no manifest row as
  changed (unstamped_is_changed=True). A file whose extraction previously failed
  was otherwise skipped forever once fixed, shipping a stale graph; inverted the
  test that pinned the old behavior.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-25 18:40:19 +00:00
Deepjyoti-SarmahandClaude Opus 4.8 3e1a423fe1 fix(rust): scope a use to the crate it names (#4699, #4712)
Applied from PR #4712 (authorship preserved); stale cache-schema bump dropped for the combined bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-25 17:26:01 +00:00
keny11300 a5ea8bbd6b fix(python): resolve calls through injected fields and method results
Carry unchanged typed bindings through self.field assignments and associate
method-result receivers with the exact resolved producer call. Preserve
INFERRED provenance, fail closed on ambiguous or rebound values, and retain
return-type context during incremental CLI and watch rebuilds.

Bump the AST cache schema and cover the four missing task-service calls,
cache reuse, incremental rebuilds, and negative resolution cases.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 9f42b5eca9)
2026-10-25 17:25:50 +00:00
Lalit Madan f1a11d33ac fix(cache): invalidate stale VB.NET stubs (#4725)
Bump the AST cache schema so same-version entries written before VB.NET external stubs gained source_file/source_location fields are re-extracted instead of replayed with validation warnings. Add a warm-cache regression test that fails against schema 25 and passes after invalidation.

(cherry picked from commit c7a689075f)
2026-10-25 17:25:49 +00:00
Lalit Madan bd07170790 fix(vbnet): emit sourceless stubs for external namespaces and types (#4725)
Fixes #4725. In VB.NET extractions, external namespaces (Imports), types,
and events emitted by add_node with source_backed=False omitted the
'source_file' field entirely. This caused validate_extraction to fail
with 'missing required field source_file' schema warnings.

Set source_file='' and source_location='' for sourceless stubs, aligning
VB.NET with Graphify's global external stub convention while preserving
the source_file on the referencing edges.

(cherry picked from commit eda67d0d12)
2026-10-25 17:25:49 +00:00
Deepjyoti-Sarmah 8e62a16ebe test(watch): pin that a partial rebuild output is never stamped (#4740)
(cherry picked from commit adb5090a81)
2026-10-25 17:25:35 +00:00
Deepjyoti-Sarmah 4f8f990020 fix(watch): only stamp build state after rebuild outputs are finalized (#4740)
(cherry picked from commit d91688a801)
2026-10-25 17:25:35 +00:00
Deepjyoti-Sarmah a84557733b perf(update): skip extraction when no relevant inputs changed (#4740)
(cherry picked from commit 79c812d0b9)
2026-10-25 17:25:35 +00:00
SinghAman21 51088ed3bf fix(dedup): preserve cross-document reference stubs
(cherry picked from commit bef629d9e3)
2026-10-25 17:25:34 +00:00
SinghAman21 58417ee754 fix(dedup): prefer specific source path on ID collisions
(cherry picked from commit 6f6270a428)
2026-10-25 17:25:34 +00:00
ayushcodes10 e3bcbcff35 Add regression tests for duplicate test case names
Covers the fix end to end: two test cases sharing a name each get
their own node at their own line, and each keeps only the calls its
own body actually makes. A control checks that a file with no
duplicate name keeps the exact plain id it always had.

(cherry picked from commit cabd73c20d)
2026-10-25 17:25:16 +00:00
ayushcodes10 e7ddccb127 Give each duplicate Robot test case its own node
Robot Framework only warns on two test cases sharing a name in one
suite, it still runs both, unlike a duplicate keyword definition,
which Robot itself rejects. Stem qualifying the node id by name
alone collapsed both test cases onto one node at the first one's
location, so the second test's own keyword calls landed on the
first test's id and line instead of its own, and the graph had no
way to show that two tests with that name even existed.

Every test case name in a file is now counted up front. A name used
only once keeps the plain id it always had. A name used more than
once salts every one of its own ids by its own line number, so each
occurrence gets its own node, its own location, and keeps its own
calls, and the outcome does not depend on which occurrence the walk
visits first.

User keywords are unaffected by this change and remain intentionally
merged across the whole corpus when they share a name, since Robot
itself treats a duplicate keyword definition as a real conflict, not
a tolerated duplicate the way a repeated test case name is.

(cherry picked from commit 28f0f94a5f)
2026-10-25 17:25:16 +00:00
danieldutu 78de58a557 fix(watch): bound each watch rebuild with GRAPHIFY_REBUILD_TIMEOUT, with a Timer fallback where SIGALRM is missing (#2173)
graphify/watch.py:2845 calls _rebuild_code(watch_path) with no timeout. A hung
rebuild blocks the watch loop with no upper bound. The hooks bound their
rebuild by GRAPHIFY_REBUILD_TIMEOUT (graphify/hooks.py:200-228), and their
SIGALRM path does not exist on Windows.

I added _rebuild_timeout() to graphify/watch.py and wrapped the watch loop's
_rebuild_code call in it, with the same two paths as the hooks. With SIGALRM,
the handler kills multiprocessing.active_children() and raises TimeoutError;
the loop logs it and continues. Without SIGALRM, a daemon threading.Timer
kills the children and calls os._exit(1). A timeout of 0 disables the guard.

tests/test_hooks.py gains one AST test of the fallback shape. It fails when
graphify/watch.py is reverted to v8.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit aa315b2473)
2026-10-25 17:25:15 +00:00
Peace Bakare c205f45472 fix(detect): prune MSBuild obj/ and bin/ output on build evidence
A C# project scanned after `dotnet build` pulled generated sources
(GlobalUsings.g.cs, AssemblyInfo.cs) and build-copied config from obj/
and bin/ into the graph; `dotnet new` writes no .gitignore to stop it.

bin/ is real source in Rust and script trees, so gate both names on
MSBuild artifacts as out/ is (#3347): restore output or
FileListAbsolute.txt for obj/, *.deps.json, *.runtimeconfig.json or
*.pdb for bin/. Ignore obj/ and bin/ under tests/fixtures, which C#
editor tooling creates by restoring the fixture projects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 2d311f6dcc)
2026-10-25 17:25:14 +00:00
ayushcodes10 209b7e3935 Add regression tests for external require call visibility
Covers the repaired shape directly: a call through a require of an
external package keeps its edge on the binding node instead of
losing it. A control confirms a resolvable local require still
suppresses its own binding node exactly as before, so the fix
cannot regress the case it was never meant to touch.

(cherry picked from commit 152a953404)
2026-10-25 17:25:13 +00:00
ayushcodes10 383d715c83 Keep a require of an external package visible on its binding node
Suppressing the local node a require binding used to mint fixed a
call landing on the binding instead of the required class, for a
specifier that resolves to a file in the corpus. A require of an
external package has no such file to redirect a caller to, so the
same suppression just left the use with nothing to land on at all,
a real loss from the one, admittedly wrong, edge it had before.

The node is now suppressed only when the specifier actually
resolves locally; an external package keeps its binding node
exactly as it did before the shadowing fix, so a call through it
stays visible rather than silently disappearing.

(cherry picked from commit eef1631c18)
2026-10-25 17:25:13 +00:00
Deepjyoti-Sarmah 08725465e0 test(ts): chained decorator edges and warning region line (#4711)
(cherry picked from commit 95f25b6047)
2026-10-25 17:25:13 +00:00
Deepjyoti-Sarmah 6533f57e85 fix: recover chained TS decorators and report the lossy parse region (#4711)
tree-sitter-typescript 0.23.2 cannot parse a member access on a call in
decorator position. For `@(Link().toMany())` it wraps `Link().` in an ERROR
and parses `toMany()` as a sibling, and `_ts_decorator_name` returned None for
any parenthesized expression, so the decorator contributed no edge at all.

Read the outermost call of a parenthesized decorator, including one recovered
past an ERROR, and leave a genuinely unparseable expression (an invalid
`@(A, B)`) without a name.

The partial-parse warning also reported the first ERROR line, which is often an
earlier single-line recovery that kept its symbols. Report the multiline
region the warning gate selects on instead.

(cherry picked from commit 3b8d4c4c52)
2026-10-25 17:25:13 +00:00
smngvlkz e0fb925378 leave an odd-shaped cost.json alone instead of crashing
(cherry picked from commit 39c14aa550)
2026-10-25 17:25:12 +00:00
smngvlkz 968115c0cc save extract token usage to cost.json like the skill does
(cherry picked from commit 745be83ddb)
2026-10-25 17:25:12 +00:00
smngvlkz 360056a98a fix ollama context size for non-latin text and the real system prompt size
(cherry picked from commit 0eb9ba2dfa)
2026-10-25 17:25:12 +00:00
smngvlkz 59b01dcd3a word the hook reminders as facts so agents stop reading them as prompt injection
(cherry picked from commit 08a4c448c8)
2026-10-25 17:25:11 +00:00
Ivan Dachev 0ba0ed1dbe fix(python): member-call pass binds only Python callers and targets
`_resolve_python_member_calls` folded labels across the whole corpus, so a
Swift `Inner.go()` bound a Python `Inner`, a Python `Inner.go()` bound a
Swift `Inner`, and `SwiftArray.make()` bound a Swift `Swift.Array`. The pass
now skips callers and targets whose effective suffix (`.graphifyrc`
overrides honoured) belongs to another extractor, and counts only Python
classes for the single-definition guard. Extensionless files, unknown
suffixes and raw calls without a file still pass, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 1d590e4356)
2026-10-25 17:25:11 +00:00
Ivan Dachev 12f0fd6f15 fix(dedup): no id-collision warning for shared module nodes
Every Swift file that imports a module (`import Foundation`) mints the
same module node id by design, and the extractors already exempt
module/namespace nodes from collision disambiguation.
deduplicate_entities still reported each such group as a lost-node ID
collision, printing a spurious WARNING for every extra importing file.
That noise trains users to ignore the real data-loss warning.

_report_id_collision now stays silent only when every member of the
group is a module (or namespace) node of the same type under the same
label. A module colliding with a namespace, with any other type, or
with a differently named module still warns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 0565d66408)
2026-10-25 17:25:09 +00:00
Deepjyoti-Sarmah 5cd4edcc24 fix(extract): report AST cache hit rate over the file total, not uncached set
(cherry picked from commit c0f3c527c7)
2026-10-25 17:25:08 +00:00
Md Anish Ahamad 5e4efda78d fix: resolve XAML codebehind independently of directory order
`_xaml_codebehind_path` falls back to scanning siblings for a
case-insensitive filename match when the exact `.xaml.cs` name is absent.
On a case-sensitive filesystem more than one sibling can match at once
(`App.xaml.cs` alongside `app.xaml.CS`), and `iterdir()` yields them in
filesystem order, so it returned whichever happened to come first:

    iterdir order ['app.xaml.cs', 'App.xaml.CS'] -> app.xaml.cs
    iterdir order ['App.xaml.CS', 'app.xaml.cs'] -> App.xaml.CS

The resolved file is parsed by `extract_csharp`, so the symbols and edges
taken from it, and the node ids built on them, changed with directory
layout rather than with the inputs.

Sort by `p.name` rather than sorting the paths. `WindowsPath` comparison
is case-insensitive, so a bare `sorted()` leaves two case-variant names
comparing equal and a stable sort hands back the original filesystem
order, which is the thing being fixed. The regression test compares the
resolved name rather than the Path for the same reason: comparing Path
objects would hold on Windows even when the two orders resolved to
different files.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
(cherry picked from commit 35f7dfc6ed)
2026-10-25 17:25:08 +00:00
ethereal49 336312ca12 fix(llm): send DeepSeek output cap as max_tokens
DeepSeek documents max_tokens and ignores max_completion_tokens. Route
both the extraction and lightweight labeling/dedup OpenAI-compatible
requests through the same backend-specific request-field mapping so
GRAPHIFY_MAX_OUTPUT_TOKENS and per-call limits take effect.

Fixes #4739

Co-Authored-By: Codex <noreply@openai.com>
(cherry picked from commit ae2bb1c664)
2026-10-25 17:25:07 +00:00
safishamsiandClaude Opus 4.8 79fce4dd94 docs(changelog): 0.9.96 — add the llm/watch/prs/export/build/python/zig/dart fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-25 16:55:24 +00:00
safishamsiandClaude Opus 4.8 7b5036662a build(cache): bump schema to 26 for the Zig and Dart extraction changes (#4755, #4741)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-25 16:53:54 +00:00
ayushcodes10 d5f45ba3cc Add regression tests for anonymous Dart extensions
Covers the fix directly: an unnamed extension now mints its node
and its extends edge to the type it extends. A control confirms a
named extension still resolves to its own declared name and never
falls into the anonymous fallback label.

(cherry picked from commit 94e787df80)
2026-10-25 16:53:44 +00:00
ayushcodes10 8738b7baf0 Detect an unnamed Dart extension declaration
An extension declared without a name, extension on String, never
matched the pattern meant to catch it at all, so it never minted a
node or an extends edge. The name and its generics were captured as
one optional group together with the space that follows them, but
that trailing space was written as its own separate run demanding
at least one space of its own before on. A single space between
extension and on, the only space present once the name is absent,
could never satisfy both runs at once, so the whole pattern simply
failed to match and the fallback label it already carried for this
exact case was dead code.

Folded that trailing space into the same optional group as the name
itself, so nothing demands it when the name is missing. A named
extension keeps matching exactly as before.

(cherry picked from commit 57901ddcad)
2026-10-25 16:53:44 +00:00
ayushcodes10 05782647be Add regression tests for Zig method and free function calls
Covers both directions directly, each with a free function and an
unrelated struct method sharing one name: a bare call now resolves
to the free function rather than the method, and a member call on
the receiver resolves to its own method rather than the free
function.

(cherry picked from commit cfabd6f757)
2026-10-25 16:53:43 +00:00
ayushcodes10 c2dd119b8e Stop a Zig call crossing between a method and a free function
A call's own shape already told the extractor whether it named a
method or a free function, it just never asked. The lookup matched
either label for every call regardless of whether the call carried
a receiver, so a bare call to a name only declared as a struct
method landed on that unrelated method instead of resolving to
nothing, and a member call could just as easily land on an
unrelated free function sharing the receiver's method name. Both
directions depended entirely on which declaration the file happened
to list first.

The call site already computes whether it is dotted; that flag now
picks which single label the lookup accepts, so a bare call can
only ever bind a free function and a member call can only ever bind
a method, exactly like the written call shape promises.

(cherry picked from commit e07a4aaf31)
2026-10-25 16:53:43 +00:00
Rudy Celekli 6e75b42147 fix(python): bind a member call to the method it spells, not a folded twin
`run` and `_run` are two methods of one class (#3302 gave them separate
ids), but _resolve_python_member_calls indexed methods through _key,
which strips `_` and folds case. Both landed on one entry, the later
`method` edge won, and `Worker.run()`, `w.run()` on a typed receiver and
an inherited `self.run()` all drew a calls edge to `_run`. Keep every
method under the folded key and, when several share it, pick the one
named exactly as the call, as the module arm already does (#4577). A
call that matches none of them exactly is not guessed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 3c97842421)
2026-10-25 16:53:42 +00:00
Rudy Celekli 91c8954345 fix(llm): evidence-check a code node whose confidence is a mis-cased EXTRACTED
_bind_node_evidence flags a code node with no evidence in the source only
when the model presented it as solid, matching confidence against
(None, "", "EXTRACTED") case-sensitively. build._fold_confidence (#4529)
treats a case variant as that enum value and corrects its spelling, so a
node the model wrote as "extracted" reaches graph.json as EXTRACTED, but
skipped the evidence check and kept no verification flag. Compare
case-insensitively. A hedged value in any case (inferred, ambiguous) is
still left unflagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 554d227b28)
2026-10-25 16:53:42 +00:00
Rudy Celekli dfd4ea95ec fix(build): coerce numeric hyperedge members under the members/node_ids aliases
_coerce_non_string_ids (#2326) str-coerces numeric node ids, edge
endpoints including the legacy from/to aliases, and only the canonical
`nodes` hyperedge member list. A hyperedge that spells its members with a
tolerated alias (#1561) kept bare ints, while its nodes became "1"/"2"/"3".
_normalize_hyperedge_members then folded the alias onto `nodes`, every
member matched no built node, and the whole hyperedge was dropped. The
same input keyed `nodes` survives. Coerce the alias lists too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 6af5f5a75c)
2026-10-25 16:53:41 +00:00
Rudy Celekli 4c7d710f75 fix(export): list every parallel relation in an Obsidian note
graph.json is reloaded as a MultiGraph when it carries parallel edges
(#4500), but the vault note's Connections list read edge_data(), which
returns only the first parallel edge. A pair joined by both `imports` and
`calls` therefore lost one relation from the exported note. List one
bullet per edge via edge_datas(), sorted so the note stays byte-stable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit edd1f476da)
2026-10-25 16:53:40 +00:00
Rudy Celekli db8b04a331 fix(prs): treat every unfinished CheckRun status as pending CI
GitHub's CheckStatusState has six values: REQUESTED, QUEUED, IN_PROGRESS,
COMPLETED, WAITING and PENDING. Only COMPLETED carries a conclusion.
_parse_ci matched IN_PROGRESS and QUEUED alone, so a WAITING run (a job
held by a deployment protection rule), a REQUESTED run or a PENDING run
read as NONE on its own, and any sibling check that had already passed
masked it as SUCCESS. A PR still waiting on a gated job was then sorted as
ready instead of pending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 38442f16ff)
2026-10-25 16:53:40 +00:00
dherreraj 171617dc1b test(watch): lock the #1915 gate for semantic-backed paper Markdown (#4750)
Review follow-up on #4751. A paper-classified .md that already has a
semantic layer must not gain an AST heading layer now that papers enter
the quick-scan; cover the full and incremental rebuild. Also correct the
comment: only formats with an AST extractor (.md/.mdx/.qmd today)
qualify, so a paper-classified .txt still gets no nodes, as on v8.

(cherry picked from commit daf0be456a)
2026-10-25 16:53:39 +00:00
dherreraj 51d248b8bb fix(watch): quick-scan Markdown that detect() classifies as a paper (#4750)
A .md/.txt whose opening text matches enough _PAPER_SIGNALS (an arXiv id,
"arxiv", an Abstract heading) is classified as `paper`, and the AST-only
rebuild behind `graphify update` and the hooks read only the `code` and
`document` buckets. Such notes got zero nodes, silently, while an
otherwise identical file kept its heading structure.

Feed the `paper` bucket through the same AST-extractor filter as
documents. Binary papers (PDF) have no AST extractor and stay out; a
paper that already has a semantic layer is still excluded from the
quick-scan by the #1915 gate, so nothing is double-represented.

(cherry picked from commit 0c5e62e976)
2026-10-25 16:53:39 +00:00
dherreraj 245c952f1a fix(llm): don't report a failed chunk's files as model omissions (#3616)
The #1890 dispatch/return reconciliation diffed every dispatched file
against the returned source_files and explained the whole gap with one
sentence: "The model returned a response but omitted them". For files
whose chunk raised (a provider error, a missing optional SDK), no
response ever existed, so the final warning contradicted the chunk
failure printed above it and pointed the operator at model output
instead of the real error.

Record the files of every chunk that raises, in the serial and pooled
paths, and split the uncovered set: files from failed chunks get
"Their chunk failed before returning a response (see errors above)",
the rest keep the existing omission wording. uncovered_files is
unchanged, so both still re-dispatch on the next run.

(cherry picked from commit deb42aa5e6)
2026-10-25 16:53:38 +00:00
safishamsiandClaude Opus 4.8 34b96bcb31 security(deps): raise pillow/pypdf floors and refresh the lock to patched transitive deps
Triage of the 87 open Dependabot advisories: the real user-reachable
exposure is pillow (image parsing on untrusted files; 4 critical + 22
high, fixed in 13.0.0) and pypdf (PDF DoS, fixed in 6.19.0). The rest are
transitive/dev-tree (pyjwt, virtualenv, certifi, urllib3, anyio, fsspec,
soupsieve, cryptography) and clear with a lock refresh.

- pillow >=13.0.0 on Python 3.11+, >=12.3.0 on 3.10 (Pillow 13 drops 3.10;
  no upstream fix exists for 3.10).
- pypdf >=6.16.1 -> >=6.19.0.
- uv lock --upgrade pulled patched transitive versions (pyjwt 2.15.1,
  cryptography 50.0.2, certifi 2026.10.23, urllib3 2.8.0, virtualenv
  21.14.13, anyio 4.15.1, fsspec 2026.9.0, soupsieve 3.0.4).

Full suite green (8725 passed, 1 pre-existing macOS-only failure).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 23:04:49 +01:00
nothariharan 92741d162b docs(security): refresh the threat-surface table (#4643-#4645, #4657, #4566, #4329)
Document mitigations that landed after the last SECURITY.md update:
- URL validation now rejects embedded credentials, port 0, and missing hostnames.
- ingest writes via lstat and refuses to replace an existing entry (symlink escape).
- credential-shaped text is redacted before it reaches graph.json.
- uninstall --purge refuses the project, home directory, and filesystem roots.

(cherry picked from commit 61f9bc82c4)
2026-10-23 18:20:06 +01:00
nothariharan 85567c95af docs(readme): list the antigravity-windows platform (#4655)
install.py defines antigravity-windows (the Windows shell variant of the
Google Antigravity platform), and the CLI help already lists it, but the
README platform table only had 'Google Antigravity'.

(cherry picked from commit ab742a3058)
2026-10-23 18:20:06 +01:00
nothariharan aa8ca7370b docs: document GRAPHIFY_CLAUDE_CLI_MODEL (#2861)
The claude-cli backend defaults to Opus, so community naming can burn
Opus quota silently. Document the env var in the README environment
section and mention it in the label/cluster-only --model help.

(cherry picked from commit f6d8a9b6b0)
2026-10-23 18:20:05 +01:00
nothariharan e8b1bb571f docs(readme): list the optional [watch] extra (#1203)
graphify watch needs watchdog, but the README extras table omitted the
[watch] extra, so users following the install docs hit 'watchdog not
installed'. Add the row alongside the other extras.

(cherry picked from commit ff015b9a74)
2026-10-23 18:20:04 +01:00
nothariharan 7174d3b972 docs(readme): document labeling batch limits, --missing-only, and html node limit (#3859)
- README: add a compact 'Labeling and rendering limits' section covering
  --batch-size vs context window, --missing-only, .graphify_labels.json.sig,
  export html --node-limit / GRAPHIFY_VIZ_NODE_LIMIT, and the Leiden->Louvain
  fallback.
- CLI help: state the ~16k default sizing for --batch-size and the 5000
  default for export html --node-limit.

Docs/help strings only; no behavior change.

(cherry picked from commit 4bbb93789b)
2026-10-23 18:20:02 +01:00
safishamsiandClaude Opus 4.8 b111c5cea9 docs(changelog): fold the batch into the still-unreleased 0.9.95 (now 21 PRs)
0.9.95 was gated but never shipped, so the follow-on batch belongs in it,
not a separate 0.9.96. pyproject stays at 0.9.95.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:20:00 +01:00
safishamsiandClaude Opus 4.8 2a0cacb60c docs(changelog): open 0.9.96 with the install-security, type-alias, csharp-overload, tree, and other fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:16:39 +01:00
safishamsiandClaude Opus 4.8 18e52c4bb8 build(cache): bump schema to 25 for the type-alias, C# overload, and package.json-link extraction changes
Covers #4578/#4579/#4580/#4581 (Python/Go/C++/Rust aliases + Rust union),
#4591 (#4584, C# overload nodes), and #4572 (#4569, package.json dep link).
Each PR shipped a stale 20->21 bump against an older base; this is the single
reconciled bump on top of HEAD's 24.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:15:41 +01:00
Deepjyoti SarmahandClaude Opus 4.8 e76019466d fix(json_config): link a package.json dependency's manifest entry to its ref node (#4569, #4572)
Applied from PR #4572 (authorship preserved); stale cache-schema bump dropped for one combined bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:15:25 +01:00
Mpasha17andClaude Opus 4.8 87151e40ac fix(csharp): give each method overload its own node and bind calls by argument count (#4584, #4591)
Applied from PR #4591 (authorship preserved); stale cache-schema bump dropped for one combined bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:15:24 +01:00
madhusudanpatnaikandClaude Opus 4.8 14514b37f6 fix(rust): extract type aliases and union items as type nodes (Refs #4285, #4581)
Applied from PR #4581 (authorship preserved); stale cache-schema bump dropped for one combined bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:15:22 +01:00
madhusudanpatnaikandClaude Opus 4.8 3bab26798e fix(cpp): extract namespace-scope using/typedef aliases as type nodes (#4580)
Applied from PR #4580 (authorship preserved); stale cache-schema bump dropped for one combined bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:15:21 +01:00
madhusudanpatnaikandClaude Opus 4.8 8cfda7f1ce fix(go): extract type A = B aliases as type nodes (#4579)
Applied from PR #4579 (authorship preserved); stale cache-schema bump dropped for one combined bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:15:20 +01:00
madhusudanpatnaikandClaude Opus 4.8 291248ef49 fix(python): extract explicit type aliases as type nodes (#4578)
Applied from PR #4578 (authorship preserved); the PR's stale cache-schema
bump is dropped in favour of one combined bump for the alias cluster.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:15:06 +01:00
Neal 44079cbd9b fix(detect): skip binary media word counting
Co-authored-by: Codex <noreply@openai.com>
(cherry picked from commit 62663244fb)
2026-10-23 18:12:48 +01:00
omsenjalia 73876cbdc7 fix(cache): read and write AST cache entries via extended-length paths on Windows
Under a deep root, the cache entry
<root>/graphify-out/cache/ast/v<ver>-s<schema>-g<grammars>/<64 hex>.json,
and mkstemp's even longer <hash>.<random>.tmp temp name, overrun Windows
MAX_PATH. save_cached raised FileNotFoundError and `graphify extract`
failed with "AST extraction failed" (e.g. any project under the default
%TEMP% of a long user name).

Move detect._os_path (the \?\ helper from #1655) to paths.os_long_path
so cache.py can share it, and use it for the entry and temp file in
save_cached and load_cached. detect._os_path stays as an alias. Keys are
unaffected: _normalize_path still strips the prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit abf9c9f6ab)
2026-10-23 18:12:47 +01:00
AromalBiju1 cbcd8dd601 fix(tree): don't count untagged nodes as a repo when choosing merged layout
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit a751df5f89)
2026-10-23 18:12:46 +01:00
AromalBiju1 97f18cb7b0 fix(tree): group merged graphs by repo tag so repos get their own roots
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 873795a05b)
2026-10-23 18:12:46 +01:00
m.fotohi 8a19705383 fix(install): use unique temp paths to prevent symlink attacks during skill install
(cherry picked from commit b2d3ffec7a)
2026-10-23 18:12:46 +01:00
safishamsiandClaude Opus 4.8 53d3d80346 fix(deps): declare pyyaml as a base dependency
The 0.9.95 YAML structural extractor (#4706) imports PyYAML, but it was
only a transitive dependency, so a fresh `pip install graphifyy` produced
zero nodes from .yaml/.yml files (the extractor degrades gracefully but
silently). manifest_ingest and markdown also use it via guarded imports.
Declare it like tree-sitter-json so the feature works out of the box.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 16:16:07 +01:00
safishamsiandClaude Opus 4.8 ae2b453b7d chore: bump version to 0.9.95
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 16:14:52 +01:00
safishamsiandClaude Opus 4.8 4f99094579 docs(changelog): 0.9.95 — add the security, affected, build, cross-repo, hooks, objc, and sql fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 16:13:31 +01:00
safishamsiandClaude Opus 4.8 3b213769f0 fix: bump cache schema to 24 (#4705, #4677), clean recovered SQL labels, add security tests
- Bump _AST_CACHE_SCHEMA 23 -> 24: #4705 (ObjC NS_CLOSED_ENUM) and #4677 (SQL
  CREATE TABLE ERROR-node recovery) both change extraction output, and neither
  PR included the bump, so a warm ObjC/SQL cache would serve stale results.
- #4677: display the recovered table label through _clean_ident (consistent
  with the routine/trigger recoveries) while keeping the id keyed off the raw
  name so FK edges still resolve to it.
- Add regression tests the #4708/#4709/#4710 security PRs shipped without
  (multicast/unspecified SSRF block, Obsidian tag injection, Google shortcut
  frontmatter escaping).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 16:12:55 +01:00
08raviyadav e69cc9d89e Recover CREATE TABLE statements dropped into ERROR nodes by unsupported column defaults (fixes #4613)
(cherry picked from commit d496e9113e)
2026-10-23 16:11:21 +01:00
Jason Daniel 8a29ab62cb feat(objc): extract NS_CLOSED_ENUM declarations as enums (#4401)
Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit c0d1001005)
2026-10-23 16:11:20 +01:00
Dextheking1 fedc4e82ed google_workspace: use full YAML scalar escaping for shortcut frontmatter
(cherry picked from commit 9907005e93)
2026-10-23 16:11:11 +01:00
Dextheking1 bf48d2b83e export: sanitize obsidian frontmatter tag values
(cherry picked from commit 420cc5c2be)
2026-10-23 16:11:10 +01:00
Dextheking1 02f62e769d security: block multicast and unspecified IPs in _ip_is_blocked
(cherry picked from commit cd96fbea26)
2026-10-23 16:11:09 +01:00
dherreraj 5c3c47ebea fix(hooks): run the rebuild from the checkout's top level (#3258)
The rebuild bodies read graphify-out/ and its .graphify_root relative to
the cwd, but git does not always start hooks at the top level. With
GIT_DIR exported and no GIT_WORK_TREE (a nested git call from another
hook or tool), git takes the caller's cwd as the work tree and
`git rev-parse --show-toplevel` echoes that subdirectory. A stray
graphify-out/ left there by an earlier run then roots the rebuild at the
subdirectory; for .claude/worktrees/ that walks every linked worktree.
The #3265 guard rejects a `..` marker, but its fallback is the same cwd.

Add a shared _TOPLEVEL_ANCHOR snippet right after _WORKTREE_GUARD in all
four hooks. In the standard layout it cds to the parent of the absolute
common .git dir; with GIT_WORK_TREE or a separate git dir it keeps git's
own --show-toplevel. GIT_DIR is rewritten to its absolute form so later
git calls still resolve. The block already runs in a subshell, so the cd
does not leak into chained hooks.

(cherry picked from commit e6193ab816)
2026-10-23 16:11:08 +01:00
xiongjianxu d709f67941 fix(cross-repo): bind ObjC split decl/impl across repos to its definition
An ObjC class whose @interface(.h) and @implementation(.m) live in
different repositories surfaces as two same-named candidate type nodes
that _merge_decl_def_classes folds within a repo but cannot across the
boundary (its id embeds the directory, #1556). The cross-repo member-call
pass then tripped the single-definition guard (len(candidates) != 1) and
dropped the call edge even though exactly one candidate DEFINES the
selector.

Scoped to lang == "objc": when more than one same-named candidate
survives, union their members and bind the selector to the sole candidate
that DEFINES it (a method node with definition_file set, or a .m/.mm
source). Two candidates that both define it are two unrelated classes and
stay ambiguous, so the guard still catches the collision it was meant to.
Other languages, the C# resolver path, and the single-candidate path are
unchanged.

Co-Authored-By: Claude Code <noreply@anthropic.com>
(cherry picked from commit a82a375c2d)
2026-10-23 16:11:07 +01:00
nothariharan 7598c5dcee fix(build): resolve a raw graph's import endpoints through the alias index (#4670)
`extract --no-cluster` and the clustered path disagreed on where a
framework-style `#import <Kit/ToolEvent.h>` lands. The clustered path
re-pointed the edge at the header's real file node (`kit_event_toolevent`);
the raw path minted an external stub for the header's bare basename
(`toolevent`) and left the edge on it, so the two write paths of one
extractor produced different graphs for the same corpus.

The raw path only had a normalization map. Normalization cannot bridge
`toolevent` and `kit_event_toolevent` - they are not the same string
modulo case and punctuation - so re-pointing was impossible. The
clustered path resolves it through the pre-migration alias index, which
maps a file's old-stem spellings onto its canonical id (#1504/#1509).

Move that index into a shared `_alias_index` helper and use it in both
paths, so the clustered and the raw write path resolve an endpoint the
same way. The raw path now re-points endpoints BEFORE it mints stubs, so
an import that names a real file is no longer frozen onto a stub minted
for its unresolved spelling; only a genuinely external import
(`<Foundation/Foundation.h>`) still mints one (#2873).

An alias is committed only when exactly one node claims it, so two files
sharing a bare stem stay ambiguous and the import keeps its stub rather
than binding to whichever same-stem file was seen first.

Tests: two unit tests over `finalize_raw_graph_endpoints` (an old-stem
alias resolves to the real file node; an ambiguous alias stays
unresolved) and one end-to-end test that `extract --no-cluster` and the
clustered path agree on the import target. The new tests fail without
this change.

(cherry picked from commit acbec5f5c3)
2026-10-23 16:11:06 +01:00
Deepjyoti-Sarmah fb90065380 test: affected <path> on a shared basename with a second L1 node (#4698)
Pins the resolver against the node shapes #2032 and the rationale pass
produce, plus end-to-end runs of the issue's repro and the comment
control that was never broken.

(cherry picked from commit 3b04706956)
2026-10-23 16:11:06 +01:00
Deepjyoti-Sarmah 7aae85ec6e fix: resolve affected <path> for disambiguated file labels (#4698)
A path query matches every node in the file, so resolution ends in
_prefer_file_node. Two of its passes compare the label to the bare
basename, which #2032's disambiguation rewrote to a unique path suffix
(alpha/hooks.py); the third pass trusts L1 uniqueness, which a module
docstring (a rationale node on line 1) or a one-line top-level
definition also occupies.

Accept a label that names its own source_file, using the
_is_file_node_label predicate build/analyze already share. Runs before
the L1 fallback, so extra L1 nodes no longer decide the result.

(cherry picked from commit b80626ed3b)
2026-10-23 16:11:06 +01:00
safishamsiandClaude Opus 4.8 d67b5a0faf docs(changelog): 0.9.95 — add the YAML structural extraction feature (#4706)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 15:55:13 +01:00
safishamsiandClaude Opus 4.8 1834b3e703 fix(yaml): handle multi-document streams, gate data YAML, bump cache schema (#4706)
Three fixes on top of #4706's YAML extractor:
- Multi-document YAML (`---` separators) returned zero nodes because it used
  yaml.safe_load, which accepts only one document; k8s manifests, Helm output,
  and CI pipelines (the headline use cases) were silently empty. Use
  safe_load_all and give each document a distinct node (labelled by kind+name
  for k8s) so two docs in one file do not merge their keys.
- Add a _is_config_yaml gate mirroring extract_json's _is_config_json: a
  top-level data array, an OpenAPI/Swagger spec, a JSON-schema-in-YAML, and a
  flat all-scalar bundle (i18n) are skipped as data instead of minting up to
  500 orphan nodes. A mapping with any nested value, a recognized config name,
  or a .github/workflows path is still walked.
- Bump _AST_CACHE_SCHEMA 22 -> 23 (the PR reclassifies .yaml/.yml and adds a
  new extractor, so cached YAML must re-extract).
- Tests: multi-doc, data/OpenAPI/array skip, the safe_load ACE guard, and caps.
- Clearer missing-PyYAML hint (pip install pyyaml).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 15:54:58 +01:00
nothariharan 9c5d56f28f test(watch): use the markdown language alias for the document override
The rcfile language table maps 'markdown' -> .md; 'md' is not a recognized
alias, so the override was ignored and the watch test never saw a document.

(cherry picked from commit c1890f376a)
2026-10-23 15:51:09 +01:00
nothariharan e4d8235378 test(yaml): add structural extraction coverage and update document tests (#2214)
- Add tests/test_yaml_extraction.py (classification, key nodes, contains edges,
  stable ids, scalar/empty documents).
- Drop .yaml/.yml from the oversized-document slicing parametrization: they are
  code now, not documents sent to the semantic pass.
- Point the language-override lifecycle test at .md so it still exercises a
  document override (yaml is no longer a document).

(cherry picked from commit b69b32e2f1)
2026-10-23 15:51:09 +01:00
nothariharan 6a21696caa fix(detect/extract): structurally extract .yaml/.yml config files (#2214)
YAML files were classified as documents, so code-only / AST-only runs
(graphify update) produced zero nodes from them. Move .yaml/.yml into the
code path like .json: add a PyYAML-based structural extractor (extract_yaml)
registered in _DISPATCH, add the suffixes to CODE_EXTENSIONS, drop them from
DOC_EXTENSIONS and the splittable-text set.

Deterministic ids derived from the file path; top-level and nested keys become
nodes with contains edges, capped at 500 pairs / depth 6 to avoid exploding on
data-heavy YAML.

(cherry picked from commit 2e5565a684)
2026-10-23 15:51:09 +01:00
safishamsiandClaude Opus 4.8 d4f3cf7f51 docs(changelog): open 0.9.95 with the module-import over-promotion fix (#4707)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 15:39:02 +01:00
nothariharan a8ce86f02e test(extract): pin #2945 module-import over-promotion regression
Adds a regression test that fails on the pre-fix resolver: a caller that
imports a module for a different symbol and calls a same-named function must
keep the edge INFERRED, never EXTRACTED.

(cherry picked from commit 7d41be8891)
2026-10-23 15:38:48 +01:00
nothariharan ac4b5e33dd fix(extract): don't promote module-imported same-named calls to EXTRACTED (#2945)
When an ambiguous bare call resolves to a candidate solely because the
caller imported the candidate's source module (not the symbol itself), the
edge was promoted to EXTRACTED, falsely certifying a same-named symbol that
was never actually imported. Keep the resolution (for graph connectivity) but
mark it INFERRED. Symbol-level (from X import Y) imports still promote to
EXTRACTED.

(cherry picked from commit e73ca4e4a7)
2026-10-23 15:38:48 +01:00
safishamsiandClaude Opus 4.8 c588b72d93 chore: bump version to 0.9.94
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-22 17:06:40 +01:00
safishamsiandClaude Opus 4.8 c3dad319ee docs(changelog): 0.9.94 — add the SQL, markdown, mcp, cross-repo, and ObjC fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-22 13:50:44 +01:00
Deepjyoti-Sarmah b8d9f12385 fix: fold SQL table stubs across files and bind schema-qualified names
The stub rewire skipped dotted labels, but a SQL table is schema.name,
so dotted labels from .sql files now count as definitions. SQL stubs
that share a normalized name and bind to nothing fold into one node
(the smallest id, so file order doesn't matter). .sql joins the
language families, so a SQL read no longer binds to a same-named
definition in another language.

(cherry picked from commit 55bc540bbe)
2026-10-22 13:49:38 +01:00
Deepjyoti-Sarmah 8e8a7c3808 test: one node per SQL table across files
A table no file defines, read from N files, becomes N per-file stub
nodes, and a schema-qualified read never binds to its definition in
another file. A SQL read of `Orders` also binds to a Python class
Orders. Guards cover same-file binding and different schemas.

(cherry picked from commit 1dfc710497)
2026-10-22 13:49:38 +01:00
Deepjyoti-Sarmah 9ce1404719 fix(sql): end the statement at GO batch separators
GO is a client-tool command, not SQL, and tree-sitter-sql has no rule
for it. Before parsing, each GO [n] line found on the masked text
(comments and strings blanked) becomes `;` plus spaces, so byte
offsets and line numbers don't move. A go line after a comma, or
before a comma or `)`, is a column and stays.

AST cache schema 20 -> 21 so cached .sql extractions re-run.

(cherry picked from commit 2293c31d79)
2026-10-22 13:49:33 +01:00
Deepjyoti-Sarmah 01715accd5 test(sql): GO batch separators without a semicolon
A GO line with no `;` before it is read as an identifier, so the next
statement lands in an ERROR node and its table is lost. Guards cover
`;`-terminated batches, GO inside a block comment, a column named go,
and GO after a keyword line such as SET NOCOUNT ON.

(cherry picked from commit f00ecc42c9)
2026-10-22 13:48:29 +01:00
Deepjyoti-Sarmah 518bd3f066 fix(sql): strip T-SQL brackets and read routine bodies (#4635)
tree-sitter-sql has no T-SQL bracket identifiers and no create_procedure
node, so bracket names were mangled and procedures only got a node from
the regex recovery, never an edge. Labels and lookup keys now drop the
brackets (ids are unchanged). Each recovered routine's body, up to the
next CREATE/ALTER, a GO line or EOF, is scanned on the masked text:
FROM/JOIN give reads_from, and INSERT/UPDATE/DELETE/MERGE/SELECT INTO
give writes_to. Alias updates resolve to their table; CTEs, variables
and temp tables are skipped.

AST cache schema 20 -> 21 so cached .sql extractions re-run.

(cherry picked from commit 70f521dba9)
2026-10-22 13:48:14 +01:00
Deepjyoti-Sarmah 608722208d test(sql): T-SQL bracket names, procedure reads and writes (#4635)
Bracket names like [dbo].[Orders] come out as the label `dbo].[Orders`,
stored procedures get no reads_from edges in any dialect, and
INSERT/UPDATE/DELETE/MERGE make no edge. Guards cover aliases, CTEs,
temp tables, variables, comments, strings and body boundaries.

(cherry picked from commit a2a666c6d7)
2026-10-22 13:47:26 +01:00
safishamsiandClaude Opus 4.8 7a0b031088 docs(serve): correct _resolve_single_node docstring to name explain (#4618)
The landed docstring listed only the get_node/get_neighbors MCP tools,
but the CLI `explain` command also routes node lookup through this
resolver (cli.py), so a substring-only near-miss now refuses there too.
Name explain in the docstring so the shared surface is accurate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-22 13:47:19 +01:00
nothariharan c6d4c25135 fix(mcp): a substring near-miss is no longer the answer (#3917)
`get_node` / `get_neighbors` share `_resolve_single_node`, which takes the
first node of the winning tier. The substring tier matches a query anywhere
inside a label, so `get_node(label="MailController")` on a codebase with no
`MailController` returned `EmailController` as if it were the exact symbol,
with no hint that the name does not exist.

The resolver now splits the two fuzzy tiers by intent. A prefix match still
resolves, because the caller started typing the real name (`email` ->
`EmailController`). A substring-only match is a search hit, not the symbol
the caller named, so it returns `No exact match for '<query>'` followed by
up to five closest names with their source location, plus a `path::symbol`
retry example. `get_neighbors` inherits the same answer through the shared
resolver, so both tools report one lookup the same way (ADR-0001).

Exact, source-exact and prefix resolution, the ambiguity refusals, the
dotted/Python and `path::symbol` forms and scoring are unchanged. The other
near-miss case in the issue (`get_node(label="edit")` with several `.edit()`
methods) already refused as Ambiguous under ADR-0001; tests cover both.

Tests: the issue's MailController repro, prefix shorthand, exact-over-substring
precedence, the five-candidate cap.

(cherry picked from commit d3875f4f1c)
2026-10-22 13:47:04 +01:00
xiongjianxu 775ddb9d5a fix(cross-repo): point a cross-repo call edge at its call site, not the caller's header
A cross-repo `calls` edge took its `source_file` from the caller node
(an ObjC method node is minted at its `@interface` in the `.h`) while its
`source_location` is the call-site line, recorded in the `.m`. Pairing the
two pointed `source_file:source_location` into the wrong file — often past
the end of a short header.

The park payload now carries the call-site file alongside the line, and
`link_cross_repo_member_calls` prefers it, falling back to the caller
node's file for pre-#3152 graphs. The parked path is relativized in the
same extract-time pass that relativizes node source_files, so it never
leaks the absolute checkout path into graph.json.

Co-Authored-By: Claude Code <noreply@anthropic.com>
(cherry picked from commit 3281d42492)
2026-10-22 13:46:54 +01:00
xiongjianxu 3a4beec195 Stop re-queuing declined-by-design code files every incremental (#2879)
The #2543 heal re-queues any manifest-stamped code file that has a
registered extractor but zero nodes in graph.json, treating it as a
poisoned stamp. A file the extractor declines by design (data JSON such
as .xcassets Contents.json, #1224/#2879) is exactly that shape — stamped,
zero nodes — yet legitimate, so the heal re-queued it on every incremental
run forever.

extract() now surfaces the declined files (skipped_sources), save_manifest
marks their row ast_empty: true (preserved across unchanged incrementals,
dropped once a file starts producing nodes), and the heal skips rows
carrying the marker. A pre-fix manifest has no marker, so such a file is
re-queued exactly once, re-stamped with the marker, and left alone after.

Co-Authored-By: Claude Code <noreply@anthropic.com>
(cherry picked from commit c930591f08)
2026-10-22 13:46:54 +01:00
xiongjianxu 6e6d5dbbfd fix(extract): resolve ObjC member calls when a class splits across header/impl dirs
`_merge_decl_def_classes` folds an @interface/@implementation pair into one node
only when both live in the SAME directory (the id embeds the directory path,
#1556). A class whose `.h` sits in `include/` and `.m` in `src/` therefore mints
two same-labelled nodes that never merge, so `[w render]` saw two type-def
candidates, tripped the member-call resolver's single-definition god-node guard
(`if len(type_defs) != 1: continue`), and emitted NO edge -- the same corpus
resolved fine when the pair shared a directory. Header/impl directory splits are
common layout, so this hit ordinary code.

Replace the three per-arm god-node bails with a shared `_resolve_member_target`
that unions the candidates' members and binds the selector to the sole candidate
that DEFINES it (an @implementation in `.m`/`.mm`, or a merged node carrying
`definition_file`). A header-only node is a bare declaration and does not count,
so the split pair resolves to its one real definition. Two unrelated same-named
classes that each define the selector still yield two definitions and stay
ambiguous -- the guard holds for the genuinely-ambiguous case it was meant for.

Co-Authored-By: Claude Code <noreply@anthropic.com>
(cherry picked from commit 510934c686)
2026-10-22 13:46:53 +01:00
nothariharan a287c0795a fix(markdown): keep owner evidence when the edge already exists
The review bot flagged a real hazard in the owner-evidence bookkeeping: a
mention whose `references` edge is already in the graph returned early, so
the document never recorded that it cites the target. A later bare method
mention in the same document then lost its owner and was dropped.

`_add` now records the cited target before it decides whether the edge has
to be written, so the evidence survives an edge that is already there.

The pipeline cannot reach that state today (the resolver is handed a fresh
edge list, and the incremental context only carries contains/method/
inherits/imports edges), so this is hardening rather than a fix for a
reachable failure. The regression test drives the resolver directly with a
pre-existing class edge.

(cherry picked from commit 37efe877cf)
2026-10-22 13:46:52 +01:00
nothariharan 0620458b04 fix(markdown): a bare method name needs its class cited (#4609)
`resolve_markdown_mentions` linked any bare, parenthesis-less code span to
the corpus's single `_callable` carrying that label, and methods qualify.
A prose word in a code span (`redis` the server, `data`, `message`) then
became `heading --references--> SomeClass.word()` at INFERRED 0.95, on a
method that has nothing to do with the sentence. On the reporter's corpus
44 of 1,906 mention edges were words of this kind.

A bare single-name span is now resolved in three passes. Explicit evidence
(a cited path, a dotted qualifier chain, or a trailing `()`) resolves as
before. Bare mentions that do not name a method keep resolving, and their
targets are recorded per document. A bare mention that names a method is
kept only when its owner class is already cited in the same document, so
`redis` no longer links to `Cache.redis` while `successWithWarnings` next
to `HandlerResult` still does. Ambiguity, built-ins and the case-sensitive
label match are unchanged.

Tests cover the issue repro, the owner-cited case, the `()` case, a free
function, and the cross-document guard.

(cherry picked from commit 6bba91fc65)
2026-10-22 13:46:52 +01:00
safishamsiandClaude Opus 4.8 b19eefa8f0 docs(changelog): 0.9.94 — add the ObjC-id, hook-quoting, IPv6, ingest-symlink, and --help fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-22 13:17:22 +01:00
safishamsiandClaude Opus 4.8 de35292406 fix(cli): derive the --help platform list from _PLATFORM_CONFIG + add a drift guard (#4655)
#4655 added amp/copilot/kilo/kimi to the hand-maintained --help install
line but still omitted antigravity-windows, so it disagreed with
_print_install_usage. Derive the list from the same
[*_PLATFORM_CONFIG, "gemini", "cursor"] expression the install usage
uses so the two cannot drift, and add test_help_lists_every_install_platform
to catch any future platform that is not advertised.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-22 13:16:25 +01:00
Ziyu Dong dd45dfc2b0 fix(cli): list amp and every --platform value in graphify --help
The top-level help left out the `amp install` / `amp uninstall`
subcommands, and its `install --platform` list omitted copilot, kilo and
kimi, although all of them are accepted (`_PLATFORM_CONFIG`) and
documented in the README platform table. `graphify install` with a bad
platform already prints the full list, derived from `_PLATFORM_CONFIG`;
only the hand-written banner had drifted.

(cherry picked from commit 6480046271)
2026-10-22 13:14:03 +01:00
madhusudanpatnaik c0ac375b11 fix(extract): keep the checkout path out of ObjC category ids
An ObjC category (`@interface Foo (Cat)` in `Foo+Cat.h`) keys its class
node and methods off the base stem `Foo`, so they fold into `Foo.h`'s
class (#1556). extract() turns an id minted from an absolute input path
into the repo-relative form only when it starts with its own file's stem
prefix (`.../Foo+Cat`), so these ids kept the absolute form. A category
on a class outside the corpus (`NSString (Extra)`) got a node id with
the checkout path in it, and so did the methods of a category on an
in-corpus class. graph.json then carried the path (#502), two checkouts
of one repo gave different graphs, and an incremental rebuild in a moved
or copied checkout added duplicate nodes.

The remap now also registers a category file's base-stem prefix, after
the file's own prefixes. On SDWebImage, AFNetworking and Kingfisher,
334 / 51 / 17 ids carried the checkout path; now 0, two checkouts give
identical graphs, and absolute and relative input agree. Every edge,
compared by label and file, is unchanged. Through the CLI, SDWebImage's
graph drops 125 duplicate category nodes (a leaked copy beside the clean
copy reached through its include/ symlink) and one false reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 11fe66a3cf)
2026-10-22 13:13:03 +01:00
Ziyu Dong b9f95739ca fix(serve): accept the bracketed Host header of an IPv6 HTTP bind
`--transport http --host ::1` put the bare literal into the DNS-rebinding
allowlist (`::1`, `::1:8080`), but clients reaching http://[::1]:8080
send `Host: [::1]:8080`, so every request was rejected with 421 and the
server was unusable on an IPv6 loopback bind. Bracket an IPv6 literal
before building the allowlist; foreign Host headers are still rejected.

(cherry picked from commit 831b25703c)
2026-10-22 13:12:57 +01:00
Ziyu Dong b324c34f78 fix(ingest): never write a text capture through an existing entry
Binary captures pick their filename with lstat so they never replace an
existing directory entry (#4393). Text captures (webpages, tweets, arXiv)
still used Path.exists(), which follows symlinks: a dangling symlink named
like the capture reported "free" and write_text() followed it out of the
corpus directory. The loop also stopped at 999 numbered names and then
overwrote the last one. Share the lstat-based selection between both
paths.

(cherry picked from commit 3e483ca077)
2026-10-22 13:12:56 +01:00
Amar Kumar Thakur 0aa256f95f fix(codex): quote a spaced exe path in the PreToolUse hook command
The claude and gemini hooks (since #522/#1987) double-quote a resolved graphify path containing spaces, but _install_codex_hook embedded the resolver output raw. On a checkout path like 'D:/Project V2/.venv/Scripts/graphify.EXE', every shell that runs the hook (Git Bash on Windows to cmd.exe to POSIX sh) word-splits the command at the first space: the guard can never fire, and #2165's subcommand-parsing test splits at the same space and fails.

Mirror _claude_pretooluse_hooks/_gemini_hook with the same two-line guard: bare-name (project-scoped, #3129) installs are unaffected, as is any absolute path without spaces. test_codex_hook_command_is_a_real_cli_subcommand now parses hook commands with shlex.split instead of naive .split(), and a new regression test installs all three hosts under a spaced resolver output, proves argv[0] survives intact, and re-verifies uninstall recognition of the quoted entry.

(cherry picked from commit 87e997d3a0)
2026-10-22 13:12:56 +01:00
safishamsiandClaude Opus 4.8 c7f16f9426 docs(changelog): open 0.9.94 with the URL-security and extraction fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-21 19:35:13 +01:00
safishamsiandClaude Opus 4.8 0e7cf1ec4b fix(js): narrow the require-binding guard to literal require callees (#4634)
#4634 suppressed the module-scope node for a require binding so it no
longer shadows the required class. But its guard used
_find_require_call(value), which matches ANY identifier(...) call, so it
also dropped real `const x = factory()` nodes (e.g. express(), NextAuth(),
wrapper()) and regressed #2604/#2552 (10 test failures). Add
_js_value_is_require, which name-checks the callee is literally `require`
the same way _require_imports_js already does, and gate the binding on it.

Bump _AST_CACHE_SCHEMA 20 -> 21: the require-binding change alters
extraction output (drops the shadow node, redirects the calls edge).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-21 19:34:27 +01:00
lab 1207 ae5493c182 fix(extract): a require binding does not shadow the required class
A \const X = require('./m')\ binding is an import, not a module-scope data
binding. The node it produced in the importing file shadowed the class the
required file exports, so \
ew X()\ bound to the local node and the
required class got no incoming edge.

(cherry picked from commit 66bb69114a)
2026-10-21 19:33:10 +01:00
ayushcodes10 85537d9c01 Add regression tests for the member call defer fix
Covers the issue's own repro, a delegating wrapper that no longer
self loops and an unrelated same named sibling that no longer steals
the edge, plus three controls: a bare unqualified call still
resolves by name, this dot calls still bind through the caller's own
class, and a TypeScript typed receiver still resolves through its
declared type. A fourth control checks that a factory object's own
sibling methods still call each other, the one legitimate case that
keeps resolving locally instead of deferring.

(cherry picked from commit 49c645d2ff)
2026-10-21 19:33:01 +01:00
ayushcodes10 74bed49f46 Defer a JS/TS member call instead of guessing by name
A member call whose receiver is neither this nor self reached the
per file bare name map, the same way an unqualified call does. A
delegating wrapper like history.appendFrame(entry) inside a function
also named appendFrame then bound to itself, an EXTRACTED self loop,
and the same map could just as easily bind it to any other same
named function in the file instead of the receiver's own method.

Every such member call now defers, exactly like it already does for
Python, Java and C#. The deferred call still reaches the receiver
typed resolver, which binds it correctly when the receiver's type is
known, and otherwise leaves it unresolved rather than guessing. A
plain call with no receiver, and this dot calls resolved through the
caller's own class, are both untouched.

One case keeps resolving locally rather than through that resolver,
since the resolver only sees whole file state and could still bind
it to a same named member on an unrelated object: a method assigned
onto a local factory object calling a sibling through that very
object, such as store.get() from inside store.set. The receiver name
there reconstructs the caller's own owner id exactly, so it is read
straight off the owner rather than guessed.

(cherry picked from commit 24b1f28fd4)
2026-10-21 19:33:01 +01:00
Jay Hemnani cc488b9076 fix(manifest_ingest): read only a POM's own dependencies
_parse_pom collected every <dependency> in the file with
".//dependencies/dependency", including <dependencyManagement> entries,
which only pin versions, and the <dependencies> of build plugins. Each
became a depends_on edge, so a parent POM that manages its modules'
versions depended on every module.

Read <dependencies> under <project> and under <profiles><profile>, where
Maven takes a project's dependencies from.

(cherry picked from commit 534177d1ea)
2026-10-21 19:33:01 +01:00
Rishi Gupta 2b07311b0d test(security): reject URLs with embedded credentials
(cherry picked from commit 09494cb720)
2026-10-21 19:32:46 +01:00
Rishi Gupta 822fbb04c2 fix(security): reject embedded URL credentials
(cherry picked from commit 2fac78e8ed)
2026-10-21 19:32:46 +01:00
Rishi Gupta 52dea94b01 test(security): cover malformed URL ports
(cherry picked from commit 57d6217281)
2026-10-21 19:32:19 +01:00
Rishi Gupta 53bfe14613 fix(security): reject malformed URL ports
(cherry picked from commit 55a4fbcddc)
2026-10-21 19:32:19 +01:00
Rishi Gupta 8f6ad0f61e test(security): cover hostless HTTP URLs
(cherry picked from commit fad73d94d9)
2026-10-21 19:32:11 +01:00
Rishi Gupta 724a184bdd fix(security): reject HTTP URLs without a hostname
(cherry picked from commit 6f4782affa)
2026-10-21 19:32:11 +01:00
Syed Fahad 847a93f3ca docs: use discord.gg/graphify for the community invite
README, translations, support docs, and the GitHub templates were handing out a coded invite. It still joins the same server. Use the vanity URL.

(cherry picked from commit 7331198fc4)
2026-10-21 16:22:06 +01:00
479 changed files with 46254 additions and 4777 deletions

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@ body:
[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
[Discord](https://discord.gg/graphify). If you have found a bug, please
open an issue instead so it can be tracked.
- type: textarea
id: question
+1 -1
View File
@@ -4,7 +4,7 @@ contact_links:
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
url: https://discord.gg/graphify
about: Join the Discord to ask questions and discuss ideas in real time.
- name: 📖 Documentation
url: https://docs.graphify.com
+1 -1
View File
@@ -33,7 +33,7 @@ jobs:
return;
}
const discord = 'https://discord.gg/XDnKVpzdXB';
const discord = 'https://discord.gg/graphify';
const discussions = 'https://github.com/Graphify-Labs/graphify/discussions';
const body = isPR
+5
View File
@@ -40,3 +40,8 @@ paper/
# macOS Finder metadata
.DS_Store
# MSBuild restore/build output: editors with C# tooling restore the fixture
# .csproj files on open
tests/fixtures/**/obj/
tests/fixtures/**/bin/
+126
View File
@@ -33,6 +33,12 @@ Signatures below are the real ones - `tests/test_architecture_doc.py` imports ev
| `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 |
Detection counts words from text and converted documents. Supported raster images,
audio and video stay in the discovered corpus, but their raw bytes are never decoded
for word counting; detection also bypasses any older cached counts for them. SVG
remains text-readable, and PDF/Office files retain their existing text converters.
This avoids reading and splitting entire binary media files just to size the corpus.
### Calling `extract()` from your own code
`extract()` takes a **list** of paths, and `root` is keyword-only and optional:
@@ -49,6 +55,15 @@ Always pass `root`. Node ids and `source_file` values are derived relative to it
## Extraction output schema
Terraform/HCL per-file AST results record the scope used to mint their node IDs.
After a cache hit, extraction consumes that scope to rewrite node IDs and edge
endpoints relative to the current scan root, including when the cache was copied
from another checkout. Module-source topology is still resolved against the
current permitted corpus. The scope marker is internal and is not exported in
the graph. AST cache schema 33 retires entries without this marker; the semantic
cache is unchanged. Existing graphs with stale absolute Terraform IDs need a full
code rebuild: `graphify extract . --code-only --force`.
Every extractor returns:
```json
@@ -64,6 +79,35 @@ Every extractor returns:
`validate.py` enforces this schema before `build()` consumes it.
Validation reports list/object enum values as schema errors. Graph assembly
repairs structured `file_type` values to `concept` and structured `confidence`
values to `INFERRED`, without fabricating a confidence score, so malformed
semantic fields cannot abort an otherwise usable build.
JS/TS calls through default imports of directly default-exported object literals reuse existing static method nodes.
Members match the imported module path, exact label and source line. Lexically shadowed receivers, constructor calls,
spread, computed keys, accessors, duplicate keys and dynamic aliases are not inferred. These files bypass the per-file
AST cache, so resolving these cross-file calls does not require an AST cache schema bump.
## Semantic provenance during file-node folding
`build_from_json()` normally folds an evidence-free semantic mention of a
filename into its unique AST file-self node (Pass 2b, #3344); references to
that mention are rewired to the AST node. A cross-source semantic record that
contains its own `rationale`, source URL, author/contributor, capture time,
or metadata is **not** a disposable mention: a label-only fold would discard
its explanation or attribution. Such records remain separate even when their
label matches a unique AST file node. This is intentionally conservative:
a richly annotated mention may remain distinct until an explicit
provenance-preserving merge is available. The saved-semantic-node shrink guard
uses the same rule and still rejects any unexplained loss. Same-source AST/semantic twins that are evidence-free keep their
existing exact-path merge rule (#4389/#4391), but an independently evidenced
semantic YAML/document record is retained across a later AST extractor
upgrade. If AST disambiguation path-qualifies a file-node label, the shrink
guard accounts for a plain same-source fold using the exact source identity
instead of accepting a mere basename collision.
## Edge direction in graph.json
`graph.json` is written `"directed": false`, but every link is directed: **arc order is the direction** (`source` → `target`, #563). Older canonicalized files carry it in `_src`/`_tgt` markers instead, and those win where present (#2309).
@@ -78,6 +122,22 @@ A plain `json_graph.node_link_graph()` load loses this: an undirected graph re-o
| `INFERRED` | Relationship is a reasonable deduction (e.g., call-graph second pass, co-occurrence in context) |
| `AMBIGUOUS` | Relationship is uncertain; flagged for human review in GRAPH_REPORT.md |
Go member calls, including same-file calls, resolve through declared receiver types and
carry `INFERRED` confidence. Bare calls to package-level functions remain `EXTRACTED`;
unknown or ambiguous receivers do not bind by method name alone. AST cache schema 37
retires Go entries created before these receiver-binding rules.
C++ member chains such as `client.actions->Execute()` use lexical local/parameter
bindings and class-scoped field declarations, including fields in unchanged headers.
Raw pointers and single-type-argument `std::unique_ptr<T>` / `std::shared_ptr<T>`
receivers are supported; `.` does not unwrap a smart pointer. Resolved instance
calls are `INFERRED` static-type relationships, not proof of runtime dispatch.
Unknown/shadowed types, ambiguous class identities, unresolved aliases, custom
pointer wrappers, containers, and computed receivers are not guessed. AST cache
schema 41 retires entries without receiver chains and persistent class fields.
Rebuild existing graphs with `graphify extract . --code-only --force` to populate
unchanged headers before relying on changed-file-only updates.
## Adding a new language extractor
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.
@@ -86,6 +146,14 @@ A plain `json_graph.node_link_graph()` load loses this: an undirected graph re-o
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`.
## Search hook scope
The search hook omits project hints when a structured Grep path or every literal
target of a simple grep/rg command resolves outside the project. Mixed targets,
implicit paths, shell composition/expansion, wrappers, unknown options and
unmapped Windows shell drive paths retain the advisory hint. It does not execute
shell input or change search permissions.
## Security
All external input passes through `graphify/security.py` before use:
@@ -118,6 +186,25 @@ classes under different parents retain separate definitions, methods, and
containment edges; top-level class ids are unchanged. AST cache schema 7 prevents
older cached definitions from retaining the collapsed identities.
Python injected fields retain an unchanged parameter/local's declared class
through `self.field = value`. A local assigned a member-call result can use the
resolved method's single scalar return-type reference. The link uses the exact
producer call's byte span, not a same-line argument or a bare method name.
Unknown types, conflicting assignments, shadowed names, container returns, and
ambiguous return references emit no inferred call. Resulting call edges remain
`INFERRED`. Changed-caller rebuilds carry unchanged methods' return-type references
as resolver context. Changes to a producer's return annotation require a full
rebuild to recompute unchanged callers' inferred relationships.
Python direct module-level constructor assignments (`g = Service()`) retain the
class for member-call resolution inside functions, including an imported alias
or a lowercase class rebound to its instance. The constructor must be declared
or imported before the assignment and resolve to a unique visible class by exact
spelling. Local shadowing, other module bindings, conditional assignments and
dynamic namespace mutation leave these calls unresolved. Qualified constructors
and decorated classes are not inferred by this pass. Edges remain `INFERRED`;
AST cache schema 37 retires Python entries without the instance marker.
C# partial types merge across files by their path inside the namespace,
enclosing types first and each with its arity (`` Outer`1.Inner ``), within one
assembly. Nested halves merge only under the same enclosing chain, and `Foo` and
@@ -126,8 +213,47 @@ lack this path. The merge runs after colliding ids are salted apart by path, so
a half whose file stem collides with another file's (`Spec.cs` and `_Spec.cs`,
`Cfg/Helpers.cs` and `Cfg_Helpers.cs`) still merges and keeps its members.
C# constructors (instance, static and a type's primary constructor) are nodes
owned by their type through a `method` edge, labeled `.TypeName()` with
metadata `kind: "constructor"`. The id is the one a method named after the type
would get, `_make_id(type_id, TypeName)`; each further signature is salted like
a method overload, a static constructor is its own `static` signature, and when
a member spelled like the type in another case (`foo()` in `Foo`) already owns
that id, the constructor takes a salted one, so no existing id moves. Calls in
a constructor's body and `: base(...)`/`: this(...)` arguments are its calls.
`new X(...)` keeps its edge to the type and also links the constructor whose
parameter count fits, as do `: base(...)`/`: this(...)`; two fitting overloads,
an unresolved base or an unbound type give no constructor edge. Constructors
stay out of every name-keyed call index. AST cache schema 40 retires C# entries
without them.
C# property and indexer accessor bodies (and expression bodies) are walked
with the member as the caller, and the member counts as owned by its type for
unqualified, `this.`/`base.` and partial-type lookups, like a method. It is never
a call target by name. An indexer is a `this[]` node (`defines`, context
`field`) with id `_make_id(type_id, "this")`, salted per signature and away
from a member spelled `This`. A user-defined operator or conversion is a
`.operator +()` / `.operator int()` node owned through `method`, with id
`_make_id(type_id, "operator", sha1(signature)[:6])`, since several conversions
share one parameter list. Existing ids do not move. AST cache schema 40.
R extraction preserves symbol-only bindings such as `%||%` as separate nodes.
When normal ID normalization removes an entire binding name, its UTF-8 bytes
provide a deterministic operator suffix within the same lexical owner. Its double
underscore separators cannot collide with an ordinary normalized binding ID. Local
call resolution stops if malformed scope metadata cycles.
### Same-ID AST / semantic provenance during extractor upgrades (#4896)
A newly supported AST extractor can mint an ID that is already owned by an
independently evidenced semantic node in a saved graph, even when the two nodes
refer to the same file. Watch reconciliation retains the saved semantic ID and
its rationale/attribution, assigns the fresh AST record a deterministic
ID-derived AST suffix, and rewrites only fresh AST edge/hyperedge
references. This applies to full and incremental re-extractions; incrementally
rebuilt sources are not positive evidence of semantic deletion. The shrink
guard refuses same-ID losses of semantic provenance even when the total node
count grows, preventing the ordinary missing-ID guard from being bypassed.
If multiple new AST records already share that ID, all use one deterministic
AST successor ID: this retains their preexisting AST coalescing behavior while
ensuring they cannot overwrite independent semantic provenance.
+293
View File
@@ -2,6 +2,299 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/Graphify-Labs/graphify/releases)
## 0.9.105 (2026-11-09)
- Fix: **watch** ignored directories (`node_modules`, `.git`, build output) are pruned from the Linux watch tree, so a large project no longer registers tens of thousands of wasted inotify watches and risks `ENOSPC`; the non-Linux recursive watcher is unchanged and still fires on every real change (#5074, #5091, thanks @Deepjyoti-Sarmah).
- Fix: **cpp** a member-call chain routed through class fields declared in other headers (`client.actions->Execute()`, with value `.`, raw-pointer `->` and single-arg `unique_ptr`/`shared_ptr` receivers) resolves to the field type's member across the include set, gated to a unique type and member and fail-closed otherwise; a typed local whose class is in another repo is parked for the cross-repo merge (#5098, thanks @xRedLeader).
- Fix: **markdown** a code span naming an uppercase `\`-namespace class (`\Foo\Bar`, `App\API`) or a type-qualified method call (`Type::member()`) is kept as a symbol mention instead of being dropped, while a non-call `Type::CONST`/`Type::class` stays dropped (#5093, thanks @Adityakk9031).
- Fix: **ts/js** a call through a destructured CommonJS barrel require (`const { Thing } = require('./barrel')` where the barrel re-exports `Thing`) resolves to the real declaration by following the barrel's exports, instead of dropping the edge (#5034, #5104, thanks @qq2514568380).
- Fix: **wiki** the orphan sweep folds slugs with `casefold` (not `lower`), so two article names that collide only under full Unicode case-folding (`Straße`/`STRASSE`, `Σ`/`ς`) each keep their own file instead of one being deleted as an orphan; a file written this run is never swept (#5087, #5102, thanks @nothariharan).
- Fix: **build** hyperedges are kept whole across an incremental `graphify update`: they are read from the nested graph slot a JSON-only writer uses, and after a deleted-source prune a hyperedge drops only its removed members (and itself only when none remain), instead of silently losing or leaving dangling hyperedges (#5081, #5103, thanks @nothariharan).
- Fix: **cache** a degraded (under-producing) semantic cache entry no longer pins the corpus: after the shrink guard sees a re-extraction come back smaller than the stored graph, the entry is stamped `partial` so the next run re-dispatches it instead of replaying the degraded result forever (#5083, #5101, thanks @nothariharan).
- Fix: **affected** `graphify affected <file>` seeds the file's nested member nodes (a method inside a class) transitively, not just one hop, so impact analysis no longer under-reports callers that bind to a nested member (#5094, thanks @Adityakk9031).
- Fix: **tree** `build_tree` derives the common directory root from file parents, so a single-file or single-directory tree is no longer self-nested under the file itself (#5092, thanks @Adityakk9031).
- Fix: **query** a label whose name is behind a schema or namespace qualifier (`public.sweep_widget_state()`, `fmt.Println`) is matched on its tail by the whole query and ranked above the per-token tiers, so it is no longer out-competed by single-token collision nodes and dropped from the seeds (#5080, #5095, thanks @sunhouy).
- Fix: **detect** an incremental staleness check hashes a file whose stamp lands within the clock-skew window on either side of its mtime, so a same-tick rewrite that does not move mtime is still caught instead of being served stale (#5090, thanks @sunhouy).
- Fix: **path** `graphify path A B` refuses an endpoint whose words appear nowhere in the graph (exit not-found) instead of returning a misleading route built from loosely-overlapping tokens (#5085, thanks @sunhouy).
- Fix: **csharp** a classic extension-method call (`x.Foo()` where `Foo` is declared `static ... Foo(this X x, ...)`) binds to the extension method's declaration through an additive pass that runs after nominal dispatch, gated to a visible namespace, a matching `this` type and a unique applicable method; an instance method of the same name wins, a non-extension static or an unimported extension gets no edge, and ambiguity fails closed (#4828, #4849, thanks @Deepjyoti-Sarmah).
- Fix: **markdown** a bare, unqualified free-function mention in prose (`token`, no `()` and no namespace) binds to a same-named function only when its defining file (or another symbol from it) is cited within the heading's section chain, instead of matching any same-named callable in the corpus; reference-style links (`[text][label]`) resolve at the use site (#4804, #4806, thanks @madanlalit).
- Fix: **export** the `to_json` shrink guard no longer counts semantic sources that were replaced on re-extract or pruned as deletions as "lost", so a legitimate `graphify update` is not refused; a genuine unexplained shrink is still refused (#5107, thanks @khkar).
- Fix: **build** a node whose `file_type` or `confidence` arrives as a structured value (list/dict) from a drifting LLM pass no longer crashes the validate/build membership checks: validation surfaces it as a schema error, and the build folds it to `concept`/`INFERRED` without fabricating a score (#5088, thanks @sdivyanshu90).
- Fix: **llm** a splittable document below the character cap whose model output truncates is promoted to a full-range slice and bisected (and retried) instead of being kept as a truncated partial result; a non-splittable or code/binary unit still fails closed (#5072, #5078, thanks @aadilrizwan).
- Feat: **llm** a custom OpenAI-compatible provider's `extra_headers` are forwarded to the client as `default_headers`, scoped to that provider and with any `Authorization` header dropped so it cannot override the configured credential (#3680, #4783, thanks @jaimemartinez).
- Perf: **extract** whole-graph intermediates (the parse memo on the one-shot CLI, build/cluster/export working lists) are freed as soon as they are consumed, cutting peak memory on a large corpus; graph output is byte-identical (#5063, thanks @TPAteeq).
- Fix: **skillgen** the claw/kiro/pi subagent prompt now tells the worker to write its chunk to `CHUNK_PATH`, so a disk-dispatch chunk is no longer returned inline and lost at the merge step (#5040, thanks @connhodendatabase).
- Fix: **deps** the pypdf floor is raised to 6.21.4 in the `pdf` and `all` extras to pick up its security fixes (#5015, thanks @yotamleo).
The AST cache schema is bumped to 42; warm caches re-run the affected C++, Markdown and C# extractions.
## 0.9.104 (2026-11-07)
- Security: **skill** the `/graphify` runbook no longer substitutes the scan path into Python code. Every generated code block (detect, AST and semantic extraction, build, diagnose, label, manifest, and `--update`) now reads the resolved scan root from the trusted `graphify-out/.graphify_root` sidecar that Step 1 writes through a quoted heredoc, instead of pasting the agent-supplied path into a string literal. A directory whose name carried a quote or `$(...)` could previously break out of `Path('INPUT_PATH')` and run as code; it is now read as inert data. Covers the assembled hosts and the Aider/Devin monoliths (#4762, thanks @danikdanik).
- Fix: **solidity** a call on a receiver of a contract or interface type (`IERC20 token; token.transfer()`, `IERC20(a).transfer()`, `token().balanceOf()`) binds by name and arity through that type's linearization to the type's own declaration, instead of producing no edge; gated to a single visible contract/interface and fail-closed on an unknown or ambiguous type (#5060, thanks @rohit-jsfreaky).
- Fix: **solidity** a call attached by a `using A for T` directive (`using SafeCast for uint256; x.toUint48()`) binds to the library or free function it attaches, matched by the receiver's type and an arity one greater than the call; fail-closed when the receiver type is unknown, the library is ambiguous, or two functions fit (#5062, thanks @rohit-jsfreaky).
- Fix: **solidity** members, free functions and types in one scope whose names differ only by a leading `_` or by case (`_grantRole` / `grantRole`) get separate node ids, so the `_` symbol no longer vanishes into its twin and its calls land on the right node (#5027, thanks @rohit-jsfreaky).
- Fix: **csharp** a constructor (instance, static or primary) is its own node owned by its type, with its body and `: base(...)`/`: this(...)` calls credited to it; `new X(...)`, `: base(...)` and `: this(...)` additively link the arity-correct overload, and two fitting overloads or an unresolved base give no constructor edge (#5054, thanks @rohit-jsfreaky).
- Fix: **csharp** calls inside a property or indexer accessor, an expression body, or an operator/conversion body are credited to that member instead of being lost; an indexer becomes a `this[]` node and an operator a `.operator +()` node (#5056, thanks @rohit-jsfreaky).
- Fix: **query** a same-label node that is the only match for a query term is kept as a seed instead of being dropped by the per-label cap, so every distinct term keeps at least one seed while generic-label flooding stays capped (#5027, thanks @Vaibhav2824).
- Fix: **watch** read-only events are kept out of the inotify mask via a change-only `event_filter`, so a large tree no longer drives watchdog into a self-sustaining queue-overflow loop; falls back with a warning on watchdog versions without `event_filter` support (#5033, thanks @Deepjyoti-Sarmah).
- Fix: **cache** the `\\?\` long-path spelling is kept out of cache identity, so the same file reached through `\\?\C:\...` and `C:\...` shares one entry; also fixes empty stat-index writes under UNC shares, a spurious "stat index switched" warning on Windows, and a junction/symlink alias wrongly sharing its target's digest (#5035, thanks @Bortlesboat).
- Fix: **cache** stat-index keys stay root-relative under a Windows long-path root, so a moved or cloned corpus keeps the portable-key fastpath (#5035, thanks @Vaibhav2824).
- Fix: **tests** the TypeScript unicode fixture is written as UTF-8 on every platform, so byte offsets match the extractor on Windows (cp1252) hosts (#5064, thanks @ayushcodes10).
- Fix: **tests** the hook-freshness source mock is normalized through `os_long_path`, so the read-error/stale branch is actually exercised on Windows (#5065, thanks @ayushcodes10).
- Fix: **tests** the watch pending-queue test compares `Path` objects so `/` and `\` separators compare equal on Windows (#5039, thanks @Yi-111-a).
- Fix: **extract** an ambiguous Python import's placeholder node id is hashed from checkout-independent data (module name, scan-root-relative source file, location) instead of the absolute path, so the same project at a different path or a moved cache gets the same ids (#5045, thanks @Fardin7798).
- Fix: **yaml** a template using CloudFormation intrinsic tags (`!Ref`, `!GetAtt`, `!Sub`) no longer fails to parse: a scoped permissive loader rebuilds each `!`-tagged node's shape without evaluating it, while `!!python/...` tags still raise and never execute (#5077, thanks @ayushcodes10).
- Fix: **watch** a `--watch` incremental update rebuilds the full corpus when `graph.json` is missing, instead of writing a partial graph from the manifest alone (#5016, #5021, thanks @azizur100389).
- Fix: **watch** a change to a JS/TS resolution input (`tsconfig.json`, `jsconfig.json`, a lockfile) triggers a full rebuild so importers pick up the new resolution, instead of leaving stale `imports_from` edges (#5017, #5022, thanks @azizur100389).
- Fix: **ingest** two concurrent `graphify add` captures for the same URL no longer clobber each other: the capture file is created exclusively (`O_EXCL`) and a collision retries a fresh name, with the payload fetched once (#5018, #5023, thanks @azizur100389).
- Fix: **reflect** a malformed entry in the learning overlay is skipped instead of crashing the whole load, and a legacy null-source entry is preserved as a source-less annotation (#5019, #5024, thanks @azizur100389).
- Fix: **global** a malformed repo entry in the global manifest is dropped on its own, keeping the other tracked repos, and only a non-object root or repos map is backed up and reset (#5020, #5025, thanks @azizur100389).
- Fix: **query** a graph freshly built on a subfolder is no longer flagged as a pre-#1504 build (which nagged a no-op `extract --force`): the legacy-id probe strips the `.graphify_root` offset before deriving file stems, and a genuine legacy graph is still caught (#2603, #5028, thanks @neumannpeter1231-lang).
- Fix: **tree** `graphify export tree` recognises the `src` node alias (and `file`/`path`/`filepath`) so a graph carrying those keys renders a populated tree instead of an empty one; a concept-only graph still reports empty (#5030, thanks @Adityakk9031).
- Fix: **cli** `graphify provider add` accepts `--pricing-input=VALUE`/`--pricing-output=VALUE` equals-syntax and rejects a non-numeric, non-finite or negative price with a clean error instead of a traceback or a poisoned cost estimate (#5031, thanks @Adityakk9031).
The AST cache schema is bumped to 40; warm caches re-run the affected Solidity and C# extractions. The Python and YAML fixes above need no bump (placeholder ids are resolved after the per-file cache, and previously-failing YAML was never cached).
## 0.9.103 (2026-11-05)
- Fix: **markdown** a code span written as a backslash namespace (`\Foo\Bar`) or a type-qualified member (`Type::member`) is recognised as a symbol mention and resolves to the real node when one exists, instead of being silently dropped; an absent chain mints nothing (#4610, #4695, thanks @viwe-monai).
- Fix: **detect** `extract` warns loudly when a large share of the corpus has no supported extractor (a 20-file floor and a 20% threshold), instead of only printing a bare unclassified count; a normal mixed project stays silent (#2942, #4646, thanks @ayushcodes10).
- Fix: **thread-safety** the ambient scan root is held in a `ContextVar` instead of a module global, so concurrent library/async callers extracting different roots no longer clobber each other's root; the single-threaded CLI is unchanged (#4602, #4694, thanks @WyattAu).
- Feat: **tree** `graphify export tree` caps how many children a directory lists (`--max-children`, default 200) while `total_count` still reports the full count, so a directory with thousands of entries no longer renders them all (#4766, #4768, thanks @oleksii-tumanov).
- Fix: **install** the Pi project skill is written to `.pi/skills`, where Pi reads it, instead of a `.pi/agent/skills` path it never looks at; uninstall is symmetric (#5011, #5012, thanks @Vivek1898).
- Internal: stage fake install bundles in a temp package root and fail loudly (not skip) on a wheel-build error, and serialise both wheel builders under a shared lock so concurrent runs on one checkout do not collide (#4603, #4664, thanks @wanjinhao1); characterize `_is_stale` across changed/unchanged/vanished sources (#4996, thanks @PratikDhanave); isolate the ambient venv/PATH in the `_detect_run` hook test (#4991, thanks @HhH666-ux).
- Fix: **solidity** a library call (`Lib.f()`, including an aliased import) and an `emit`/`revert`/`require` naming a declared event or error now link to the member they name instead of producing no edge; resolution is gated to a single visible type whose unique name/arity member matches, so a builtin `require` or an ambiguous qualifier is left unresolved (#5001, #5005, thanks @rohit-jsfreaky).
- Fix: **csharp** preprocessor directives and `#if` branches that derail tree-sitter are blanked before parsing (byte-length preserving, so line and column numbers do not move), so a directive no longer closes the enclosing class early and orphans later members or drops their calls; the first `#if` branch and distinct framework-fallback branches are kept (#5003, thanks @rohit-jsfreaky).
- Fix: **python** a bare builtin-named call (`raise NotImplementedError(...)`, `list(...)`) no longer binds to a same-named class in another module unless that caller imported the symbol; an imported homonym still resolves (#4989, #4999, thanks @Deepjyoti-Sarmah).
- Fix: **typescript** a type-position `import('mod')` expression (a parameter/alias/`typeof`/generic-constraint annotation) no longer emits a spurious `dynamic_import` runtime edge; a real runtime `import('mod')` in the same file still does (#4992, #4998, thanks @mathewgeejo).
- Fix: **resolution** a call inside a top-level `def _main()` is attributed to `_main`, not the public `main` it collides with after id normalization; the fix matches only the underscore-collision salt, so a class member's type reference is not misattributed to a sibling method (#4994, #4997, thanks @sunhouy).
- Fix: **yaml** a `<<` merge sequence gives the earlier anchor precedence for a duplicated key, matching the YAML merge spec and PyYAML, so the winning key carries its correct source line (#4995, thanks @PratikDhanave).
- Fix: **markdown** a dotted mention whose method name is a language builtin (`Repository.open`) is no longer dropped; only a bare builtin name is skipped, and no spurious mention is minted (#4990, thanks @PratikDhanave).
- Fix: **hooks** a Bash file read (`cat`, `head`, `tail`, `sed -n`, `nl`) of an in-project code file gets the same graph read-nudge a Read tool does (nudge-only, never a strict deny); writes, stdin, heredocs, docs and globs stay silent (#5010, thanks @rohit-jsfreaky).
- Fix: **hooks** the once-per-session nudge budget is restored after a Claude Code compaction (a `SessionStart` with `source=compact`), so orientation can re-fire once the earlier nudges have left the model's context (#5008, thanks @rohit-jsfreaky).
- Fix: **hooks** the toplevel-anchor logic keeps working when `CDPATH` is exported; an exported `CDPATH` was corrupting the relative `.git` capture and silently skipping the post-commit/checkout rebuild (#4977, #4988, thanks @HhH666-ux).
- Perf: **update** the watch reconcile pass resolves AST ownership once per file instead of re-reading each header once per node, with identical graph output (#4978, #4986, thanks @Deepjyoti-Sarmah).
- **AST cache schema bumped to 39** for the C# (#5003), Solidity (#5001, #5005), YAML (#4995) and Markdown (#4695) extractor fixes; warm caches re-run the affected extractions.
## 0.9.102 (2026-11-03)
- Perf: **update** `graphify update` re-extracts only the files whose content changed since the last build (derived from the manifest inside the lock), instead of re-running the whole pipeline over the corpus for a single edit; the resulting graph is identical to a full rebuild, including cross-file edges from unchanged files into a changed one, and deletions (#4740, #4800, #4801, thanks @Deepjyoti-Sarmah).
- Fix: **watch** a contended incremental rebuild request is recorded on its own queue marker instead of being dropped, so a derived-change request that loses the rebuild lock still runs on the next pass (#4800, #4802, thanks @Deepjyoti-Sarmah).
- Fix: **query** source nodes are ranked above tests, docs and config in query results (a soft weight, not exclusion, so a term matched only by a test still seeds it and a question mentioning "tests" restores full weight), and the answer is rendered file-first (#4982, thanks @rohit-jsfreaky).
- Feat: **query** `graphify query` reads project `query_budget` and `query_depth` defaults from `.graphifyrc` (explicit CLI flags still win), and gains a `--depth N` flag; a malformed setting warns and falls back to the built-in defaults (#1654, #4760, thanks @oleksii-tumanov).
- Fix: **install** `graphify uninstall` removes the global `# graphify` skill registration it wrote into `~/.claude/CLAUDE.md`, instead of leaving a dangling pointer to the deleted skill; a hand-written `# graphify` section or another tool's registration is preserved (#4975, thanks @madhusudanpatnaik).
- Fix: **js** a class `extends` through a CommonJS require binding (`const Base = require('./base'); class D extends Base {}`) resolves the `inherits` edge to the required file's class, matching the ESM import path; an external/unresolved require is left alone (#4688, #4700, thanks @Mpasha17).
- Fix: **skill** the `--update` runbook passes `partial_source_files` to the manifest write and clears a stale `.graphify_partial.txt` at the start of the run, so a doc whose chunk was only partly read is re-queued on the next update instead of being stamped done forever (#4807, #4814, #4816, thanks @gitmotion).
- Fix: **skill** Step 4 threads `force=IS_FORCE` into `to_json`, so a `--force` rebuild actually overwrites past the #479 shrink guard the runbook told the user to use `--force` for (#4777, #4805, thanks @pei711).
- Feat: **skill** for a hub/bridge question, the query workflow now tells the agent to grep the corpus for the hub's distinctive literals in edge-less files and report code that reimplements the hub instead of calling it (#4426, #4704, thanks @ayushcodes10).
- Fix: **hooks** a file whose mtime is newer than `graph.json` but whose content is unchanged no longer weakens the strict read gate; the hook checks the file's extraction hash against the build manifest before declaring it stale, so a checkout that writes `graph.json` first does not force a re-read (#4974, thanks @andrebrait).
- Fix: **hooks** a dedicated Grep call is held to the same once-per-session orientation gate as Read in strict mode; a directory Grep needs no index match, a single-file Grep is denied only when the graph indexes it, and external or graph-output targets stay silent without consuming the deny (#4973, thanks @andrebrait).
- Fix: **hooks** a search whose every literal target is outside the project (a Bash `grep`/`rg` on a `/tmp` or sibling path) emits no project hint, so the graph nudge only fires for in-project searches (#4961, #4979, thanks @Shubham-Padkonde).
- Perf: **load** `graph.json` rows are released as the graph is built (and repeated strings interned) so a load no longer holds both the parsed rows and the finished graph at peak, with identical output (#4960, thanks @ajbmachon).
- Perf: **resolve** symbol resolution holds one parsed file at a time instead of retaining every parsed file across the JS and Python passes, collapsing them into a single per-file loop with unchanged edges (#4958, thanks @ajbmachon).
- Perf: **extract** edge-dedup keys and per-file rows are released once consumed, cutting peak retention during extraction with identical output (#4959, thanks @ajbmachon).
- Fix: **typescript** a typed tagged template (`` sql<{...}[]>`...` ``) and an import-qualified generic annotation (`import("mod").T<X>`) no longer leave the file half-parsed; the recovery runs only on files that already fail to parse, so a type-only `import("mod").T` stops minting a bogus module node and a false `dynamic_import` edge (#4976, thanks @briascoi).
- Fix: **go** a same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method; a bare package-function call no longer binds to a same-named method, and a package-level `var` fallback only applies to a genuinely unbound receiver (#4962, #4966, thanks @xiongjianxu).
- Fix: **go** a member call on a receiver typed from another package (`pkg.T`, the usual shape of a dependency injected across packages) binds only to the `T` declared at the path the file imports `pkg` from, so two packages that both declare `T` are disambiguated by import evidence; an out-of-corpus qualifier stays unresolved (#3368, #4853, thanks @nothariharan).
- Feat: **go** an interface method call additively dispatches to the interface's implicit implementers (method-set superset match, unexported methods scoped to the same directory, capped at 10 implementers and skipped past that), surfacing the concrete methods a call can reach while keeping the edge to the interface (#4934, thanks @nothariharan).
- Fix: **kotlin** a call to an overloaded method resolves (Java gives every overload one node id, which the resolver mis-counted as ambiguous), calls inside an `init {}` block are attributed to the class, and a bare call no longer binds to a class the caller cannot reach through its type chain (#4935, #4956, thanks @Deepjyoti-Sarmah).
- Fix: **python** a module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard so rebinding, local shadowing or an ambiguous constructor leaves it unresolved (#4970, #4972, thanks @Shubham-Padkonde).
- Fix: **js** a call through a default-exported object's method (`import m from './x'; m.foo()`) resolves to the static method, bound only on a single unambiguous target and suppressed by local shadowing, getters, spread or computed keys (#4963, #4967, thanks @xiongjianxu).
- Fix: **solidity** an `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling id that kept the importer's own folder (#4984, #4985, thanks @rohit-jsfreaky).
- Fix: **build** the write guard no longer counts an intentional ghost fold (a #1145 same-file twin, #3344 doc-names-a-file, or #3705 method ghost folded into its surviving twin) as a dropped node on the `build_merge` path; a genuine drop whose survivor is also gone is still refused (#4955, #4957, thanks @Deepjyoti-Sarmah).
- Fix: **extract** paths skipped by ignore rules are reported in the extract summary (bounded, sorted, root-relative, with a VCS-aware hint), surfacing the already-collected ignore list without changing the graph (#4965, #4969, thanks @xiongjianxu).
- Perf: **resolution** the #3252 cross-file repoint indexes edges by source file instead of scanning every corpus edge per importing file, cutting resolution time on large graphs with no change to the resulting edges (#4980, #4981, thanks @jinsoo).
- Fix: **python** a bare builtin name (`NotImplementedError`, `TimeoutError`, `ConnectionError`, …) no longer links to a package class of the same name when the calling module never imports it; the edge is kept (and stays EXTRACTED) only when the caller imports that exact symbol, so a module-level import of some other name from the same file can no longer certify it (#4989).
- **AST cache schema bumped to 37** for the Go (#4966, #4853, #4934), Kotlin (#4956), Python (#4972) and Solidity (#4985) extractor fixes; warm caches re-run the affected extractions.
## 0.9.101 (2026-11-02)
- Fix: **watch** AST-only updates preserve cross-file semantic evidence whose node id collides with a code definition. Semantic nodes and their document-owned links use the existing citing-file namespace, keeping both the code definition and semantic provenance in `graph.json`, including with `--no-cluster`. Fresh AST facts remain authoritative for same-source ids; full-build deduplication is unchanged.
- Fix: **python** a bare call inside a method (`do_thing()`) no longer wrongly self-binds to a same-named method on the class; it resolves to the imported or module-level function it actually names, and a bare call with no such target emits no edge (#4933, thanks @nothariharan).
- Fix: **python** imports resolve across PEP 420 namespace packages split over multiple `src/` roots (no `__init__.py`), while a module ambiguously provided by two roots stays unresolved and loose/stdlib-named modules are left alone (#4929, thanks @nothariharan).
- Fix: **go** a method value reached through a receiver field (`m.UseMiddleware(hs.handler.Middleware)`) is linked as an `indirect_call`, extending the method-value-as-argument handling to field chains rooted at the method's own receiver (#1566, #4931, thanks @nothariharan).
- Fix: **go** a package-level `var` initialiser references the types it names (`var s = wire.NewSet(new(T), ...)`, composite literals, `new(T)`), the type-reference complement to crediting its calls to the file, so a wire-set file no longer extracts as no symbols (#2360, #4932, thanks @nothariharan).
- Fix: **rust** a module-qualified call (`crate::b::helper()`, `super::m::f()`) resolves to the function it names through qualifier-verified cross-file resolution, the dominant idiomatic call form that previously produced no edge; the resolver keeps the call inside the caller's crate and will not bind to a local name, preserving the historical false-positive guards (#2135, #4944, thanks @nothariharan).
- Fix: **rust** a call written inside an expression macro's arguments (`println!("{}", f())`, `vec![g()]`) is linked instead of being lost, gated to an allowlist of expression macros so `macro_rules!` bodies and custom DSLs are left alone, and a normally parsed call still wins the dedupe (#4945, thanks @nothariharan).
- Fix: **llm** a sliced file is cached only once every slice has succeeded, and a held sliced file is assembled in chunk order rather than completion order, so a partial failure no longer leaves a truncated or out-of-order file in the semantic cache; failed slices are stamped for retry (#4943, #4947, thanks @nothariharan).
- Fix: **rebuild** a graph built with `--code-only` stays code-only across hook, `update` and watch rebuilds; the scope is recorded in `.graphify_build.json`, honoured by the rebuild path and the no-change skip key, and a later flagless extract that actually ingests docs clears the scope (#4923, #4939, thanks @Deepjyoti-Sarmah).
- Fix: **watch** a rebuild no longer waits forever when `msvcrt.locking` is unsupported on the filesystem; an unexpected errno is treated as lock-unsupported and the rebuild proceeds unlocked with a warning, matching the existing no-`fcntl`/no-`msvcrt` fallback, while genuine contention still retries (#4924, #4926, thanks @AndresDiagoM).
- Fix: **watch** a full reconcile evicts source records for a linked git worktree that the current ignore rules exclude, including sources owned only through an edge or hyperedge, so a worktree copy's nodes no longer linger after it is excluded; an intentionally scanned linked root and live unexplained sources are preserved (#4919, thanks @azizur100389).
- Fix: **cache** cache keys keep their written case so `README.md` and `readme.md` no longer collide on a case-sensitive filesystem, and hashed and word-count files are opened through `os_long_path` so a path folded by `normcase` can no longer raise `IsADirectoryError`; the digest salt is no longer lowercased, which also closes a latent same-digest collision on POSIX (#4925, #4937, thanks @Deepjyoti-Sarmah).
- Fix: **build** the write guard no longer refuses a healthy graph when entity dedup folds a saved node into a surviving twin; the dedup merge map is carried on the built graph and threaded into both the missing-node check and the net-count check, which now counts N saved ids folded into one survivor as the expected N-1 shrink, while a genuine loss (survivor also absent) is still refused (#4940, #4952, thanks @Deepjyoti-Sarmah).
- Fix: **build** independently sourced semantic file evidence survives a fold into an AST file-self node; a mention carrying its own provenance (`rationale`, `source_url`, `author`, `contributor`) is kept distinct instead of collapsing by label alone, so two docs describing the same file no longer lose one explanation. Ordinary `INFERRED` mention ghosts with only `metadata`/`captured_at` still fold, so graphs do not accumulate duplicates (#4896, #4927, thanks @Ethan-Ethan-Ethan).
- Fix: **build** the file-stem alias index only rebinds an edge onto a migrated node when the edge's file and the alias target share a language family, so a reference in one language (for example Dart) no longer binds onto an unrelated same-stemmed file in another (for example Java); same-language and provenance-less aliases resolve exactly as before (#4949, thanks @ayushcodes10).
- Fix: **cpp** a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling, so it no longer loses to a same-normalized function of the same name, and a salted alias node keeps its own `contains` edge (#4951, thanks @madhusudanpatnaik).
- Fix: **cpp** a member call `x.m()` binds by the receiver's type, now typed from function parameters and class fields and not only local variables (`void render(Base* b){ b->draw(); }` resolves to `Base::draw`), the dominant idiom of passing state by reference; an untyped or ambiguous receiver keeps its in-file binding rather than guessing (#3215, #4946, thanks @nothariharan).
- Fix: **cpp** an out-of-line or split-header definition attaches to the unique owner whose class file is in its include set, carried by a `_cpp_qualified` identity marker, instead of being file-contained or cross-binding to an unrelated same-named function in another file; an ambiguous or namespace-colliding owner fails closed with no edge (#4916, #4920, thanks @azizur100389).
- Fix: **cpp** a local callable value (a lambda or `std::function` assigned to a variable) is kept out of global call resolution by byte-range binding lifetimes, so it no longer mints a spurious `INFERRED` call to a same-named global; a later legitimate call to a real global of that name in the same function is preserved (#4917, #4921, thanks @azizur100389).
- Internal: cover deletion-only semantic manifest preservation so an undispatched semantic stamp survives a deletion-only or failed incremental change (#4922, thanks @azizur100389).
- **AST cache schema bumped to 36** for the Rust call-resolution fixes (#4944, #4945), the case-preserving cache keys (#4937), and the C++ extractor fixes (#4951, #4946, #4920, #4921); warm caches re-run the affected extractions.
## 0.9.100 (2026-11-01)
- Fix: **ids** a type and a function whose names differ only in case (`Foo` the class, `foo` the function) get distinct node ids instead of colliding (which dropped one node and minted a bogus self-loop) (#4904, #4908, thanks @bercedev).
- Fix: **php** a `Scope::MEMBER` access in a class-level initializer (a const value, a property default, or a parameter/promoted-constructor default) emits a `references_constant` edge; `self::`/`static::`/`parent::` are skipped and unknown scopes mint no stub (#4648, #4895, thanks @Jitendarmahara).
- Fix: **hooks** `git rev-parse` output is decoded as UTF-8, so a linked worktree under a non-ASCII path resolves correctly on Windows instead of mojibake (#4903, thanks @LukeTheoJohnson).
- Fix: **analyze** on a code-only graph the isolated-node question reason says "possible missing edges" rather than referencing documentation gaps that cannot apply (#4887, thanks @oleksii-tumanov).
- Perf: **resolve** reference edges are indexed by source once, so JS/TS import resolution no longer re-walks every edge per import (output unchanged) (#4909, #4913, thanks @Deepjyoti-Sarmah).
- Docs: **skill** the skill now says when a graph is worth building, across all generated hosts, while preserving the "if the user invoked /graphify, do it as asked" invariant (#4829, #4906, thanks @TanmayShah29).
- Fix: **deps** the `video` extra caps PyAV below 19 (`av>=11,<19`), because PyAV 19 removed the `metadata_errors` argument that faster-whisper passes unconditionally when opening audio; without the cap a fresh install on Python 3.12+ failed to transcribe (#4842, thanks @SyedFahad7).
- Fix: **r** `setClass`/`setRefClass` S4/R5 inheritance declared with `contains=` now emits an inherits edge (previously only R6Class's `inherit=` was recognised) (#4902, thanks @ayushcodes10).
- Fix: **elixir** a bare function call resolves to a function in the caller's own module before other modules, instead of binding to the last-walked same-named definition (#4900, thanks @ayushcodes10).
- Fix: **dart** a mixin `on A, B` clause resolves every superclass constraint, not just the first (#4899, thanks @ayushcodes10).
- Fix: **fortran** a derived type's `extends(base)` emits an inherits edge, bringing Fortran in line with the other OOP extractors (#4897, thanks @ayushcodes10).
- Fix: **scala** an `extension (x: T) def m` is scoped to its receiver type `T` (a `method` edge to `T`) instead of leaking to file scope (#2044, #4856, thanks @divakantpandey).
- Fix: **terraform** a node carries its original scope so ids stay stable when a cached project directory is moved, instead of re-deriving the scope from the new path (#4858, #4861, thanks @yUm1k4).
- Fix: **extract (JVM)** Java and Kotlin imports, `extends`/`implements` and member calls resolve across files and across the two languages when a written FQN names exactly one sourced type (#4874, #4879, thanks @Deepjyoti-Sarmah).
- Fix: **export** a path/explain/wiki rendering lists every parallel relation between two nodes (via `edge_datas`), and a raw `--no-cluster` write marks the graph `multigraph` so parallel edges survive reload (#4794, thanks @ensell-yes).
- Fix: **export** a partial or failed backup is reported as no backup and retried on the next run, instead of being recorded as a false success (#3769, #4834, thanks @barlowa124).
- Fix: **affected** `graphify affected` (and `query --seed`) resolve the same `path::Symbol` and dotted reference forms `explain` accepts, reusing explain's resolver, and exit non-zero (3 ambiguous / 4 not-found) on a seed that does not resolve (#4792, #4797, thanks @dupeisen).
- Fix: **install** `graphify uninstall` removes every platform's user-scope skill (13 were left behind) and the kilo global command; and `graphify kilo uninstall` removes the kilo skill's `references/` sidecar (#4782, #4789, thanks @bercedev).
- Feat: **llm** the Claude backend caches its (stable, large) system prompt with `cache_control`, counting the cached tokens back into `input_tokens`, and `GRAPHIFY_CLAUDE_PROMPT_CACHE=0` disables it for gateways that reject `cache_control` (#4835, #4855, #4880, thanks @Jvxoq and @1akashkalita).
- Fix: **prompt** the node-id format description in the extraction prompt matches what `ids.py` actually produces (word characters kept, non-ASCII letters/digits preserved, ASCII lowercased) instead of the stale "`[a-z0-9_]` only" wording (#4432, #4799, thanks @dupeisen).
- Docs: **how-it-works** the supported-language count is updated (about 40: 33 tree-sitter grammars plus 7 built-in parsers) and Pass 3 is described as running the configured LLM backend, not Claude only (#4873, thanks @SyedFahad7).
## 0.9.99 (2026-10-30)
- Feat: **path** when several routes tie on length, `graphify path` and the MCP `shortest_path` tool report the most conservative one: among all shortest paths, the route whose weakest hop is weakest is chosen, and the summary notes it was the weakest of N equal-length routes. Previously an arbitrary equal-length route was returned, so the confidence could overstate how sure the connection is. This is the second half of #4881 (the first half, keeping a collapsed edge's weaker evidence in `also_seen`, shipped in 0.9.98 via #4891, thanks @SyedFahad7).
- Fix: **go** a call in a package-level `var` initialiser (including inside a func-literal closure, the common swappable-hook pattern) is credited to the file node instead of being dropped (#2360, #4867, thanks @nothariharan).
- Fix: **go** a method value passed as a function argument (`Wrap(s.Health)`) is linked as an `indirect_call`, bringing Go to parity with Python/JS for callback-by-method-value; conservatively guarded against field-access false positives (#1566, #4868, thanks @nothariharan).
- Fix: **go** a receiver's field whose struct is declared in a sibling file of the same package is typed, so its member calls resolve across the usual struct-here-methods-there Go layout, and the field types persist across incremental rebuilds (#3368, #4866, thanks @nothariharan).
- Fix: **python** `module.func` values listed in a dispatch table (`{"a": mod.func_a}`, including nested collections) resolve to the referenced functions as `indirect_call`s instead of being dropped; non-callable, class, and local-receiver values are left alone (#1566, #4773, thanks @nothariharan).
- Fix: **install** gemini gets its own global skill dir (`~/.gemini/skills/graphify`) on Windows instead of colliding with the `agents` platform's dir; a pre-existing `agents` skill is noted, not deleted (#2800, #4770, thanks @nothariharan).
- Fix: **install** the global OpenCode plugin is written to `~/.config/opencode` (co-located with the global skill) instead of the current directory, with install/uninstall/refresh kept symmetric and legacy locations still cleaned up (#3398, #4771, thanks @nothariharan).
- Docs: **skill** the "Follow these steps in order. Do not skip steps." instruction is reworded to "unless the fast path above applies," resolving the contradiction with the existing-graph fast path across all generated hosts (#4061, #4721, thanks @nothariharan).
- Feat: **serve** `path`, `explain` and `neighbors`/`get_neighbors` print an edge's stored `confidence_score` alongside its tag (`[INFERRED 0.75]`); EXTRACTED stays bare (1.0 by definition) and a missing or non-finite score keeps the bare tag. Composes with the weakest-hop path summary and the `also_seen` evidence tags (#4882, #4888, thanks @SyedFahad7).
## 0.9.98 (2026-10-30)
- Fix: **build** when duplicate same-relation edges collapse, the losing (weaker-confidence) copy's provenance is kept in an `also_seen` list on the surviving edge instead of being discarded, so the weaker evidence is not silently lost; the field is serialized to graph.json and is idempotent across rebuilds (#4881, #4891, thanks @SyedFahad7).
- Fix: **csharp** a C# method node is labelled with its owning type (`MyClass.Method`) instead of a bare `Method`, so same-named methods across types are distinguishable; node ids and edges are unchanged (display label only) (#4883, #4889, thanks @SyedFahad7).
- Feat: **path** `graphify path` and the MCP shortest-path output report the overall path confidence as the weakest hop (lowest confidence tier, then lowest score), with a summary line naming that hop (#4885, #4892, thanks @SyedFahad7).
- Fix: **path** an endpoint written `Type.Member` resolves to the member node, not the containing type, so `graphify path "Exporter.Run" "PdfReport.Build"` finds the real call route; exact names and file names still win first, and a `Type.Member` whose member does not exist fails closed (#4884, #4893, thanks @SyedFahad7).
- Fix: **extract** file ids and per-declaration ids are kept distinct, so a top-level declaration whose name matches its file (for example `class Js` in `a.js`) is no longer silently dropped on an id collision; cross-file references bind to the declared id (#4854, #4857, thanks @Deepjyoti-Sarmah).
- Fix: **dedup** when a cross-file document mention and an AST node collide on a defining id, the AST node keeps the id instead of being dropped, while same-file enrichment, extension twins and single-definer cases are left as-is (#4859, #4872, thanks @TanmayShah29; duplicate approach in #4871 by @ayushcodes10).
- Fix: **build** a two-file import cycle (a imports b, b imports a) is reported in the default undirected build, and the stamp is cleared correctly on incremental/watch rebuilds so a dropped import no longer leaves a stale cycle (#4839, #4841, thanks @Mpasha17; duplicate approach in #4852 by @legendteddy).
- Fix: **extract** a relative JS/TS import carrying a `?query` or `#fragment` suffix (`./mod.js?v=1`) resolves to the real module instead of a phantom node; Node `#subpath` imports are left untouched (#4860, #4876, thanks @Jitendarmahara; duplicate approach in #4869 by @mirzasnowy).
- Fix: **go** a receiver bound with `var x = T{}` or `var x = &T{}` (a composite literal) is typed as `T`, matching the `x := T{}` form, so its member calls resolve (#4843, thanks @ayushcodes10).
- Fix: **verilog** a SystemVerilog class constructor (`function new(...)`, which has no return type) gets its own node, `method` edge and parameter-type references (#4848, thanks @ayushcodes10).
- Fix: **powershell** `using module`/`using assembly` drops a real file extension (`Helpers.psm1` to `helpers`) but keeps a dotted module name with no extension intact (`Az.Accounts`) (#4847, thanks @ayushcodes10).
- Fix: **solidity** a free-function `using {a, b} for T` set emits `uses` edges for each named function, not just the single-library `using Lib for T` form (#4846, thanks @ayushcodes10).
- Fix: **commonlisp** a `defclass` whose superclass is defined later in the same file binds to that local node instead of minting a sourceless stub (#4845, thanks @ayushcodes10).
- Fix: **pascal** `inherited` and `inline` form component blocks (.lfm/.dfm) are recognised, so a later `object` block keeps its correct parent instead of being re-parented by a corrupted nesting stack (#4844, thanks @ayushcodes10).
- Fix: **serve** when two nodes tie in a lookup and differ only by case, the one spelled exactly as queried wins (the others stay reachable one tier down) instead of every spelling being refused as ambiguous (#4870, thanks @nothariharan).
- Fix: **export** the Cypher text export keys `MERGE` on the stable node id and sets the label separately, so re-importing after a label change updates the node instead of creating a duplicate (#4878, thanks @oleksii-tumanov).
- Fix: **pdf** the converted-text cache is keyed on the resolved source path, so two PDFs with the same relative name in different roots do not poison each other within one process (#4851, thanks @xunguangzlj-cloud).
## 0.9.97 (2026-10-27)
- Security: **rationale redaction** credential redaction for rationale labels moves to a single pre-cache choke point (`_redact_rationale_labels` inside `_safe_extract`), so no extractor can skip it, and it now covers more leak shapes: URL userinfo with an empty user or with `/`/`@` in the password, PEM private-key bodies, tokens glued to surrounding text by `_` (for example `ghp_...`), Slack `xoxe-` refresh tokens, short JWTs, and Common Lisp docstrings that previously built labels without redacting. Benign strings (hashes, `sk-` prose, URLs without userinfo) are left alone (#4647, thanks @0xkaushik-ai).
- Security: **deps** anyio is floored to `>=4.14.2` in the `mcp` extra, above CVE-2026-63374 (an IDNA 2003 vs 2008 hostname-validation bypass that let a MITM on a non-ASCII domain present a cert for a different ASCII host, CVSS 9.3). anyio is only a transitive dependency and the lockfile already resolves 4.15.1, so this is a floor to stop a future re-resolution from regressing.
- Fix: **markdown** ATX headings parse per CommonMark: a trailing run of `#` is not part of the heading text (`## Setup ##` is "Setup"), up to three spaces of indent are allowed (four is an indented code block), and a hash-only line like `## ##` mints no node (#4790, #4791, thanks @jaimemartinez).
- Fix: **markdown** fenced code blocks are tracked by CommonMark rules (backtick and tilde fences, info strings, matching close length), so a line that looks like a heading inside a fence no longer leaks as structure, and a heading after a `~~~` block that contains a ` ``` ` line is no longer lost (#4787, #4788, thanks @jaimemartinez).
- Fix: **yaml** structural extraction reads the composed node tree, so keys carry their written spelling and their own source line instead of all landing on line 1, and YAML 1.1 bare keys like `on`/`off`/`yes`/`no` are no longer folded to booleans (a workflow `on:` block is extracted, not turned into a `True` node) (#4784, #4785, thanks @jaimemartinez).
- Fix: **razor** a component's `@implements` interfaces are extracted as `implements` edges instead of being silently dropped (#4820, thanks @ayushcodes10).
- Fix: **terraform** an aliased provider block gets its own alias-qualified node (so two `provider "aws"` blocks no longer collapse into one and lose attributes), and a `provider = aws.west` reference resolves to it instead of dangling; a `local` literally named `provider` is no longer misread (#4819, thanks @ayushcodes10).
- Fix: **cobol** paragraphs that follow a nested `END PROGRAM` reattach to the enclosing program instead of sticking to the nested one, via a program stack (#4824, thanks @ayushcodes10).
- Fix: **blade** a `wire:click` directive binds the bare method name: dotted modifiers (`wire:click.prevent="submit"`) are matched, call arguments are trimmed from the name (`deleteItem(5)` binds `deleteItem`), and a `$`-prefixed magic action mints no fabricated edge (#4823, thanks @ayushcodes10).
- Fix: **pascal** a `record` is recognised as a type with its own methods in the regex fallback (the default path without the optional `pascal` extra), matching the tree-sitter path; `operator` members are extracted too (#4825, thanks @ayushcodes10).
- Fix: **vbnet** an `Operator` declaration is extracted as an `operator`-kind member of its class and its body is walked for calls, so a helper call inside an operator no longer vanishes (#4821, thanks @ayushcodes10).
- Fix: **fortran** a `call` resolves to the subroutine it actually names instead of a target salted with the calling file's name (which never resolved), using the extractor's own cross-file stub idiom (#4795, thanks @ayushcodes10).
- Fix: **cli** `graphify query --help`/`-h` (and now `graphify explain --help`/`-h`) with nothing else prints usage instead of running a literal query for the text "--help"; a longer question that merely contains "--help" as a substring still runs as a query (#4830, thanks @curl-man).
- Fix: **js** a nested (inner) function no longer leaks into the file-wide name map, so a call elsewhere in the file binds to the top-level function of that name rather than an inner one it cannot see; recursion, shadowing and sibling scopes resolve correctly (ports the Python scope scheme to JS/TS) (#4767, thanks @smngvlkz).
- Fix: **ocaml** every binding in an `and`-chained `module ... and ...` or `class ... and ...` is extracted, not just the first, so later bindings are no longer silently dropped; each carries its own source line (#4822, thanks @ayushcodes10).
- Fix: **verilog** a SystemVerilog class `task` method is modeled like a `function` one (its own node, `method` edge and parameter-type references), and a task-local variable no longer leaks as a false field reference on the class (#4774, thanks @ayushcodes10).
- Fix: **build** an edge with no `relation` is dropped instead of persisted, on both the build and the raw `--no-cluster` write paths, and alias folding (`relationship` to `relation`) runs before the check (#4810, thanks @legendteddy; reproducer also filed as #4826 by @sunhouy).
- Fix: **build** the shrink guard counts a saved document-mention node that folds into its AST file twin on reload as present, not lost, so a cluster-only write is no longer refused when nothing was actually lost (#4778, #4779, thanks @AndresDiagoM).
- Fix: **detect** a linked git worktree whose main checkout resolves inside the scan root is pruned, so a sibling worktree no longer gets indexed as a second full copy of the repo (#4683, #4833, thanks @barlowa124; duplicate work in #4685 by @AndresDiagoM).
- Fix: **resolution** an inline comment in a pnpm-workspace glob is stripped per YAML rules, and a glob that `Path.glob` rejects (a `**` component or an absolute pattern) is skipped with a warning instead of crashing the whole `extract` run (#4681, #4687, thanks @Deepjyoti-Sarmah).
- Fix: **report** a community hub `[[wikilink]]` is slugged through the same `export._obsidian_safe_stem` the export uses, so the link matches the file the export actually writes instead of dangling (#4696, thanks @ayushcodes10).
- Fix: **wiki** a community relabelled only by letter case keeps its article instead of having the sweep delete the file the run just wrote; on a case-sensitive filesystem the stale lower-case twin is unlinked rather than renamed over the fresh file (which would silently restore the old body) (#4508, #4798, thanks @dupeisen).
- Fix: **query** filler verbs `get`/`gets`/`got`/`getting` are dropped from query terms (like the existing `work`/`works`), so a framework hub labelled "Get" is not pulled in as a BFS seed by an exact-match bonus; node lookups for a literal `Get` still resolve (#4686, thanks @AndresDiagoM).
## 0.9.96 (2026-10-25)
- Security: **deps** the Pillow floor is raised to `>=13.0.0` on Python 3.11+ (staying at `>=12.3.0` on 3.10, which Pillow 13 no longer supports) and pypdf to `>=6.19.0`, and the lockfile is refreshed to patched versions of transitive dependencies (pyjwt, cryptography, certifi, urllib3, anyio, fsspec, soupsieve, virtualenv). This clears the bulk of the open Dependabot advisories; the Pillow image-parsing CVEs are only patched upstream for Python 3.11+, so a 3.10 install keeps the newest 3.10-compatible Pillow.
- Fix: **llm** a chunk that failed before returning a response no longer has its files reported as model omissions; the warning distinguishes a failed chunk from a genuine omission, and both are still re-dispatched (#3616, #4752, thanks @jaimemartinez; reported by @GREYGROUPJP).
- Fix: **watch** a Markdown file that `detect()` classifies as a paper (arXiv markers, an Abstract) is included in the watch quick-scan rebuild instead of contributing zero nodes; a paper that already has a semantic layer is still excluded from the AST quick-scan (#4750, #4751, thanks @jaimemartinez; reported by @yeochul-jeon).
- Fix: **prs** every unfinished CheckRun status (`WAITING`, `REQUESTED`, `PENDING`, ...) counts as pending CI, so a PR gated on a deployment-protection job is no longer read as ready (#4730, thanks @rudycelekli).
- Fix: **export** an Obsidian note lists every parallel relation between two nodes (for example both `imports` and `calls`) instead of only the first edge (#4731, thanks @rudycelekli).
- Fix: **build** a hyperedge whose members are given under the `members`/`node_ids` aliases has its numeric member ids coerced to strings like the canonical `nodes` list, so the hyperedge is no longer dropped (#4732, thanks @rudycelekli).
- Fix: **llm** a code node whose confidence is written in a different case (`extracted`/`Extracted`) is still evidence-checked before it folds to the `EXTRACTED` enum, so an un-verified node is not presented as solid (#4733, thanks @rudycelekli).
- Fix: **python** a member call binds to the method it actually spells rather than a case/underscore-folded twin (`run()` no longer resolves to `_run()`); a lone folded method still resolves, and a genuine collision fails closed (#4734, thanks @rudycelekli).
- Fix: **zig** a call no longer crosses between a method and a same-named free function; a bare call binds the free function and a receiver call binds the method (#4755, thanks @ayushcodes10).
- Fix: **dart** an unnamed `extension on T { }` declaration is detected and extracted (the name is optional), so its members attach to the extended type (#4741, thanks @ayushcodes10).
- Fix: **llm** the DeepSeek backend sends its output cap as `max_tokens` (which DeepSeek honours) rather than `max_completion_tokens` (which it ignores), so responses are no longer silently uncapped (#4739, #4753, thanks @Ethereal49; reported by @snapp-kenya).
- Fix: **extract** XAML codebehind (`*.xaml` to `*.xaml.cs`) resolves deterministically regardless of directory iteration order, so a graph built on a case-sensitive filesystem is stable (#4747, thanks @anishraja04).
- Fix: **extract** the AST cache hit rate is reported over the file total, not the uncached set, so a warm run no longer prints a misleading "100% uncached" line (#4740, #4746, thanks @Deepjyoti-Sarmah; reported by @lavaxun).
- Fix: **dedup** a node id legitimately shared by two files as a `module`/`namespace` no longer prints a spurious "minted by two different files" warning (#4756, thanks @idachev).
- Fix: **python** the member-call resolver binds only Python callers to Python targets, so a same-named class in another language is no longer mis-bound as a call (#4757, thanks @idachev).
- Fix: **cli** the PreToolUse hook reminders are worded as facts rather than imperatives, so the agent's tool-result stream no longer reads them as prompt injection and ignores them (#2202, #4764, thanks @smngvlkz).
- Fix: **llm** the Ollama context window is sized from an estimate that counts non-Latin characters as whole tokens and from the real system-prompt length, so a non-English or long prompt is no longer silently truncated (#4414, #4761, thanks @smngvlkz).
- Fix: **cli** `graphify extract` records each run's token usage to `graphify-out/cost.json` (the same ledger the skill writes), so a standalone extract refresh updates the cost history (#1769, #4765, thanks @smngvlkz).
- Fix: **ts** chained TypeScript decorators (`@(Link().toMany())`) are recovered as a decorator reference, and a lossy-parse warning names the real error region (#4711, #4715, thanks @Deepjyoti-Sarmah).
- Fix: **js** a `const X = require('pkg')` binding for an external package keeps its node (with the package as source) so `new X()` still resolves, while a require of a corpus-local file still folds to the required module (#4688, #4702, thanks @ayushcodes10).
- Fix: **detect** generated MSBuild `obj/` and `bin/` output is pruned only when build evidence is present (restore/runtime markers nearby), so a C# project scanned after a build no longer ingests generated sources while a real `src/bin` stays (#4742, thanks @Great-Peace).
- Fix: **watch** each watch rebuild is bounded by `GRAPHIFY_REBUILD_TIMEOUT` (default 600s, `0` disables), with a thread-Timer fallback where `SIGALRM` is unavailable or `watch()` runs off the main thread (a `SIGALRM` arm there raises `ValueError` and would tear the watcher down before the rebuild ran), so a hung rebuild no longer stalls the watcher (#2173, #4724, thanks @danieldutu).
- Fix: **robot** each duplicate test-case name gets its own node (salted by line), so two tests with the same name are kept distinct (#4697, thanks @ayushcodes10).
- Fix: **vbnet** external namespaces and types emit a sourceless stub carrying an empty `source_file` sentinel like other languages, instead of a node that fails validation (#4725, #4728, thanks @madanlalit; reported by @alopezradicle).
- Fix: **rust** a `use` is scoped to the crate it names, so `use serde_json::Value` no longer resolves to a same-named type in another crate; a named `pub use` re-export is followed and a manifest-less binding stays `INFERRED` (#4699, #4712, thanks @Deepjyoti-Sarmah).
- Fix: **python** a call through a field injected from a constructor parameter, or through a local typed by a method's return annotation, resolves to the target method (`INFERRED`); it requires a single unambiguous producer and class (#4726, thanks @keny11300).
- Fix: **dedup** an LLM-marked cross-document reference stub that collides with its real definition is namespaced instead of silently dropped, so neither node is lost (#4738, #4743, thanks @SinghAman21; reported by @snapp-kenya).
- Perf: **update** a `graphify update` with no relevant input change skips the detect/extract/build pipeline and leaves the outputs untouched, keyed on the scan file-set, config, `.graphifyrc`, extractor epoch, and an output-completeness stamp; a scanned file with no manifest row (including one whose extraction previously failed) still forces a full rebuild so a later fix is never skipped (#4740, #4748, thanks @Deepjyoti-Sarmah; reported by @lavaxun).
## 0.9.95 (2026-10-23)
Twenty-one community pull requests. A security pass on install: the skill-install writes go through randomly-named temp files instead of predictable ones, so a pre-planted symlink can no longer redirect a write. Extraction: Python, Go, C++ and Rust explicit type aliases (and Rust `union` items) are extracted as type nodes so references resolve instead of minting sourceless stubs, each C# method overload gets its own node bound by argument count, and a package.json dependency's manifest entry links to the node that references it. Plus a one-root-per-repo tree on merged graphs, extended-length cache paths on Windows, and binary media no longer counted as text. The AST cache schema is bumped, so the first build after upgrading re-extracts.
- Fix: **security** the skill install stages every write (version stamp, `SKILL.md`, references) through a randomly-named `mkstemp`/`mkdtemp` file created with `O_EXCL` and restrictive mode instead of a predictable `*.tmp` name, so a local attacker who pre-creates a symlink at that path can no longer redirect the write to clobber an arbitrary file; the final move stays atomic (#4513, thanks @Mahdifotohi).
- Fix: **python** an explicit module-level type alias (`X: TypeAlias = ...`, `type X = ...`, `NewType`) is extracted as a type node, so a field or parameter typed by the alias resolves to it instead of minting a sourceless stub; an implicit assignment, a local alias, or a re-export is left alone (#4578, thanks @madhusudanpatnaik).
- Fix: **go** a `type A = B` alias is extracted as a type node (tree-sitter parses it as a `type_alias`, not a `type_spec`), so references resolve to it; a re-export (`type Field = pkg.Field`) mints no node (#4579, thanks @madhusudanpatnaik).
- Fix: **cpp** a namespace-scope `using A = B;` or `typedef B A;` alias is extracted as a type node so references resolve; a member alias inside a class and a same-name re-export are excluded (#4580, thanks @madhusudanpatnaik).
- Fix: **rust** a `type` alias and a `union` item are extracted as type nodes (a union's fields reference their types like a struct), so references resolve instead of minting stubs; an impl-associated `type` is excluded (#4581, Refs #4285, thanks @madhusudanpatnaik; reported by @jonatasbcardio-boop).
- Fix: **csharp** each method overload gets its own node and source location instead of collapsing to one, and a call binds to the overload matching its argument count, across in-file, receiver-typed, bare-name cross-file, partial-class, and interface-dispatch resolution; a non-overloaded method keeps its id (#4584, #4591, thanks @Mpasha17; reported by @TerraVenil).
- Fix: **tree** `graphify export tree` on a merged multi-repo graph gives each repo its own root (keyed by the repo tag) instead of conflating same-path files from different repos; untagged nodes are not counted as a repo (#4524, #4525, thanks @AromalBiju1).
- Fix: **cache** AST cache entries are read and written through Windows extended-length (`\\?\`) paths, so a deep cache path over the 260-character limit no longer fails extraction with a `FileNotFoundError`; a no-op off Windows (#4542, thanks @omsenjalia).
- Fix: **detect** a binary media file (an image or audio/video) is no longer read and counted as text toward the corpus word total; an SVG stays counted as the XML text it is (#4548, thanks @kalkaran).
- Fix: **json_config** a `package.json` dependency's manifest entry links (`declares`) to the ref node that importing code resolves to, so the manifest entry and its importers share one node instead of being orphaned; the entry is relabelled `name@range` (#4569, #4572, thanks @Deepjyoti-Sarmah; reported by @BiSide).
- Feature: **yaml** `.yaml`/`.yml` files are now extracted structurally (a file node plus `contains` edges to keys) and classified as code rather than documents, so Helm charts, Kubernetes manifests, and CI pipelines contribute nodes to a code-only or `--update` run instead of nothing, matching how `.json` is handled. Multi-document streams (`---` separators) are walked per document; a data array, an OpenAPI/Swagger spec, a JSON-schema-in-YAML, and a flat data bundle are skipped so data-heavy YAML does not mint orphan nodes; parsing uses `safe_load` so a `!!python/...` tag never executes; output is bounded (1 MiB, 500 pairs, depth 6). The AST cache schema is bumped, so the first build after upgrading re-extracts (#2214, #4706, thanks @nothariharan; reported by @dchavezf).
- Fix: **extract** a bare call that resolves to a same-named symbol only because the caller imported that symbol's module (`from b import other`, then a call to a `_make_id` defined in both `a.py` and `b.py`) is no longer promoted to `EXTRACTED`; the edge is still emitted for connectivity but stays `INFERRED`, so a symbol that was never imported is not falsely certified. A real symbol import (`from a import _make_id`) still resolves `EXTRACTED` (#2945, #4707, thanks @nothariharan; reported by @TotalUnitManagement).
- Fix: **security** the SSRF guard blocks a host that resolves to a multicast address (`224.0.0.0/4`, `ff00::/8`), closing a gap alongside the existing private/reserved/loopback/link-local checks (#4708, thanks @Dextheking1).
- Fix: **security** the Obsidian export sanitizes a node's file-type and confidence before emitting them as frontmatter `tags`, so a crafted value cannot break out of the YAML list into a sibling key, matching how community tags are already sanitized (#4709, thanks @Dextheking1).
- Fix: **security** the Google Workspace shortcut sidecar escapes a file id or url through full YAML double-quoted-scalar escaping (tab, C0/DEL controls, and the Unicode line breaks U+2028/U+2029/U+0085), so a hostile shortcut file cannot inject frontmatter keys (#4710, thanks @Dextheking1).
- Fix: **affected** `graphify affected <path>` resolves a path whose file-node label was disambiguated by the shared-basename suffix pass (for example two `hooks.py` from different directories), reusing the canonical file-label predicate instead of a bare basename match (#4698, #4713, thanks @Deepjyoti-Sarmah; reported by @karsan8119).
- Fix: **build** a raw (`--no-cluster`) build resolves an import endpoint through the same old-stem alias index the clustered build uses, and mints an external stub only after resolution, so the raw graph no longer freezes an import onto a stub when the clustered graph resolves it (#4670, #4676, thanks @nothariharan; reported by @xiongjianxu).
- Fix: **cross-repo** an Objective-C class declared in one repo's header and implemented in another repo's `.m` binds a member call to the implementation, the cross-repo analog of the same-repo split-dir fix; two same-named classes that both define the selector stay ambiguous (#4690, #4691, thanks @xiongjianxu).
- Fix: **hooks** the rebuild hook runs from the checkout's top level (derived from the git common dir, falling back to `--show-toplevel`), so a stray `graphify-out/` in a subdirectory can no longer root the rebuild at the wrong place and walk an enormous tree (#3258, #4689, thanks @jaimemartinez; reported by @dsfaccini).
- Fix: **objc** `NS_CLOSED_ENUM` declarations are extracted as enums with their cases, the same as `NS_ENUM`/`NS_OPTIONS`; the AST cache schema is bumped so the first build after upgrading re-extracts (#4705, thanks @Jvxoq).
- Fix: **sql** a `CREATE TABLE` whose column default the SQL grammar cannot parse (for example MySQL/MariaDB `DEFAULT current_timestamp()`) is recovered from the ERROR node instead of being dropped, so the table and its foreign-key references still resolve; the AST cache schema is bumped (#4613, #4677, thanks @08raviyadav; reported by @AirRunner).
## 0.9.94 (2026-10-22)
Nineteen community pull requests. A security pass on ingestion: a fetched URL with no hostname, with a malformed or zero port, or with embedded `user:pass@` credentials is now rejected before the request leaves, on the first fetch and on every redirect, and a text capture no longer follows a dangling symlink out of the corpus. Extraction and resolution: a Maven POM contributes only its own dependencies, a JS/TS member call on an untyped receiver stops guessing a same-named method in the same file, a CommonJS `require` binding no longer shadows the class the required file exports, and Objective-C category node ids stay repo-relative instead of embedding the absolute checkout path. SQL gets its own pass: T-SQL bracketed names are unbracketed, a `GO` batch separator ends the statement, cross-file table stubs fold onto their real definition, and a procedure emits `reads_from`/`writes_to` edges. Plus a markdown bare method only links when its class is cited, the MCP node lookup refuses a substring near-miss instead of answering with an unrelated node, a cross-repo edge points at the call site, Objective-C calls resolve across a split header/impl, an incremental build stops re-queuing files an extractor declined by design, a quoted Codex hook command for install paths with spaces, an IPv6 bracketed-`Host` serve fix, and a complete, drift-guarded `--platform` list in `--help`. The AST cache schema is bumped, so the first build after upgrading re-extracts.
- Fix: **security** `validate_url` rejects a fetched URL that has no hostname (`http:///path`), a non-numeric, out-of-range, or zero port, or embedded `user:pass@` credentials, before the request is made and again on every redirect, so a malformed or credential-bearing URL is no longer fetched or persisted into the graph; a normal `@` in a path or query and a valid high port still pass (#4643, #4644, #4645, thanks @cellrishi-code).
- Fix: **manifest** a Maven `pom.xml` contributes only its own `<dependencies>` (including those under `<profiles>`), not the version pins under `<dependencyManagement>` or a build plugin's own `<dependencies>`, so a parent or BOM POM no longer emits dependency edges it only manages (#4596, thanks @jayhemnani9910).
- Fix: **js** a member call on an untyped receiver (`x.foo()` where `x` has no known type) is deferred to receiver-typed resolution instead of binding to a same-named method elsewhere in the file, so a spurious self-loop or cross-call edge is no longer emitted; `this.foo()`, a typed receiver, and a locally instantiated receiver still resolve (#4598, #4605, thanks @ayushcodes10; reported by @SaschaAndresGrimm).
- Fix: **js** a CommonJS `const X = require('./m')` binding no longer mints a module-scope node that shadows the class the required file exports, so `new X()` resolves to the required declaration; a real `const x = factory()` binding still keeps its node (#4621, #4634, thanks @lab1207; reported by @sub4biz).
- Fix: **extract** an Objective-C category's class and method node ids stay repo-relative instead of embedding the absolute checkout path, so a category file like `Foo+Cat.h` yields portable ids that match across machines and merge cleanly; two same-named categories in different directories stay distinct (#4666, #4642, thanks @madhusudanpatnaik; reported by @xiongjianxu).
- Fix: **codex** the generated Codex PreToolUse hook command quotes the graphify executable path, so an install under a path containing a space no longer builds a broken hook command, matching the existing Claude and Gemini hooks (#4662, thanks @supercell02).
- Fix: **serve** an IPv6 HTTP bind accepts its own bracketed `Host` header (`[::1]:port`), so a server bound to an IPv6 loopback no longer refuses every request with a 421 (#4656, thanks @zydo).
- Fix: **ingest** a text capture never writes through an existing entry: the free-path search uses `lstat`, so a name that is a dangling symlink is treated as occupied and the capture is diverted instead of following the link and writing outside the corpus (#4657, thanks @zydo).
- Fix: **cli** `graphify --help` lists every accepted `--platform` value (it had omitted amp, copilot, kilo, kimi, and antigravity-windows); the list is derived from the same source as the install usage so the two cannot drift, with a guard test (#4655, thanks @zydo).
- Fix: **sql** T-SQL bracketed identifiers (`[dbo].[Orders]`) are unbracketed so a name matches across styles, and a stored procedure's body emits `reads_from`/`writes_to` edges for the tables it reads and writes; aliases, variables, temp tables, strings, and comments never become targets (#4635, #4649, thanks @Deepjyoti-Sarmah; reported by @RuVl).
- Fix: **sql** a `GO` batch separator (a client command, not a terminator) ends the statement, so a statement after a `GO` with no trailing `;` parses on its own instead of merging into one malformed node; a `GO` inside a string, comment, or column name is left alone (#4651, #4652, thanks @Deepjyoti-Sarmah).
- Fix: **sql** a table referenced before its `CREATE TABLE` is seen folds onto the real definition instead of staying a separate stub, and a schema-qualified name binds correctly, while two genuinely different tables in different schemas (`dbo.Orders` vs `sales.Orders`) stay distinct and a SQL stub no longer binds to a same-named class in another language (#4653, #4654, thanks @Deepjyoti-Sarmah).
- Fix: **markdown** a bare method name in prose (for example `redis` where only `Cache.redis` exists) only links to the method when the owning class is cited in the same document, so a plain word is no longer turned into a false `references` edge; a qualified `Class.method` or `Class::method` mention still resolves (#4609, #4617, thanks @nothariharan; reported by @saad-siddique).
- Fix: **mcp** the `get_node` and `get_neighbors` tools, and the `explain` command, refuse a substring-only near-miss with candidate suggestions instead of returning an unrelated node as the answer; an exact or prefix match still resolves (#3917, #4618, thanks @nothariharan; reported by @Alexandre-Aktisea).
- Fix: **cross-repo** a cross-repo call edge points at the real call site rather than the caller's header declaration, so the edge's `source_file` and `source_location` name the line that makes the call (#4668, #4669, thanks @xiongjianxu).
- Fix: **extract** an incremental build no longer re-queues, on every run, a code file an extractor declined by design (for example a virtual-workspace manifest); the file is marked `ast_empty` and left alone, while a genuinely failed or transiently empty extraction is still retried (#2543, #4672, thanks @xiongjianxu).
- Fix: **objc** a member call resolves when a class is split across a header and an implementation in different directories, binding the selector to its single definition; two unrelated same-named classes that both define the selector stay ambiguous and get no edge (#4673, #4674, thanks @xiongjianxu).
## 0.9.93 (2026-10-20)
Twenty-two community pull requests. Extraction: a reference to a Kotlin type alias, C# delegate, Swift macro, Dart typedef, Python module function or Rust sibling-module `use` now resolves to its real declaration instead of minting a sourceless stub; Metal/CUDA GPU qualifiers no longer mint god nodes; `extern "C"` headers route to the C++ extractor; an extensionless script with a versioned-interpreter shebang is classified; and Obsidian vault-relative wikilinks resolve. Plus a credential-redaction pass on rationale labels, a node-confidence fold, a truncated-reply label decode, a `.graphifyrc` BOM fix, a GraphML multigraph export fix, two-repo file disambiguation in explain and path, a PDF-read warning, no skill writes on `--version`/`--help`, two PR-tooling fixes (slashed default branch, legacy CI statuses), and a skill partly-read-file recovery so a long file a subagent only skimmed is retried on the next `--update` instead of silently kept half-read. The AST cache schema is bumped, so the first build after upgrading re-extracts.
+1 -1
View File
@@ -36,7 +36,7 @@ This Code of Conduct applies within all community spaces, including the GitHub r
## 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).
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/graphify).
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.
+1 -1
View File
@@ -149,7 +149,7 @@ Focus on the problem first, proposed behavior, alternatives, and compatibility c
- **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.
- **Discord**: Join the [Graphify Discord](https://discord.gg/graphify) 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.
+43 -6
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -104,7 +104,7 @@ 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.
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, ending with the path's overall confidence: that of its weakest hop.
---
@@ -247,12 +247,15 @@ for example `graphify claude install --project` or `graphify codex install --pro
| Cursor | `graphify cursor install` |
| Devin CLI | `graphify devin install` |
| Google Antigravity | `graphify antigravity install` |
| Google Antigravity (Windows) | `graphify antigravity install` (auto-detected on Windows) |
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`.
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session indexed-read denial come from that same policy, so Pi matches Claude Code's hook behavior; guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
Claude Code's `graphify install --project --strict` makes Read and dedicated Grep share one denial per session unless a recent graph query has oriented the agent (default 30 minutes). A Grep over a directory needs no indexed-file match; a Grep pinned to a single file is denied only when the graph indexes that file, as with Read. External and graph-output Grep targets produce neither a deny nor a nudge, in soft mode as well as strict mode, matching Read's scope. A graph marked `needs_update` never triggers a Grep denial. Bash searches and Glob stay advisory. `GRAPHIFY_HOOK_STRICT=1` enables the policy without reinstalling; `GRAPHIFY_HOOK_STRICT=0` disables it even when installed with `--strict`. Existing strict installs need a reinstall to add the search hook's `--strict` flag, or the environment override. Soft nudges are capped per session (`GRAPHIFY_HOOK_NUDGE_CAP`, default 5). After a context compaction, a `SessionStart` hook (matcher `compact`) resets that budget, the subagents' budgets and the strict denial, since the compacted context no longer holds the earlier nudges.
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session denial shared by indexed Read and dedicated Grep come from that same policy, so Pi matches Claude Code's hook behavior; Bash and file listing remain advisory. Guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
> Codex uses `$graphify` instead of `/graphify`.
@@ -268,6 +271,7 @@ Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native P
| `google` | Google Sheets rendering | `uv tool install "graphifyy[google]"` |
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` |
| `mcp` | MCP stdio server | `uv tool install "graphifyy[mcp]"` |
| `watch` | Auto-rebuild on file changes (`graphify watch`) | `uv tool install "graphifyy[watch]"` |
| `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]"` |
@@ -301,7 +305,7 @@ Run `graphify <platform> install` once in your project, for example `graphify cl
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.
- **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, or via `cat`, `head`, `tail`, `sed -n` and similar readers in Bash) 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.
@@ -369,10 +373,26 @@ See the [full command reference](#full-command-reference) below.
---
## Labeling and rendering limits
- **`--batch-size`**: 100 communities per labeling call by default, sized for a ~16k-token context (~150 tokens/community). Use `--batch-size 40` for an 8k window. Context overflow is not split-retried; failed batches keep hub-derived names.
- **`--missing-only`**: `label --missing-only` keeps existing labels and names only unnamed / `Community N` entries. Use `label` (full relabel) to refresh names after the community set changes.
- **`.graphify_labels.json.sig`**: records the community membership signature; labels survive a re-cluster only while it matches.
- **`export html`**: 5,000-node default; above it graphify renders an aggregated community view. Use `--node-limit N`. `GRAPHIFY_VIZ_NODE_LIMIT` / `.graphifyrc` `viz_node_limit=N` apply to `cluster-only`, `update`, `watch`, and hooks, not `export html`.
- **Leiden fallback**: without the `leiden` extra, clustering silently uses networkx Louvain. Switching later reshuffles every community, so plan a full relabel.
---
## Ignoring files
graphify honors `.gitignore` and supports `--exclude` patterns and a project `.graphifyignore`. Details: **[Configuration](https://docs.graphify.com/reference/configuration)**.
`graphify extract` reports paths skipped by ignore rules, with up to three sorted examples relative to
the scan root. Each pruned directory counts once; its contents are not enumerated. Default noise
directories such as `node_modules` are excluded from this summary. If source is missing, review the
ignore rules. `--no-gitignore` bypasses VCS ignore rules only; `.graphifyignore` and `--exclude`
remain effective.
## Project configuration
@@ -392,6 +412,20 @@ viz_node_limit=0
The declaration flows through classification, extractor selection, grammar and resolution, imports, `graphify watch`, and the AST cache (a file re-parsed under a different language never reuses the old entry), and the same `.graphifyrc` is read by `extract`, `update`, the hooks, the MCP server, and the `/graphify` skill. A typo is reported once on stderr and the scan continues with the defaults. How declarations interact with caching, incremental rebuilds, and import resolution: **[Configuration](https://docs.graphify.com/reference/configuration)**.
**Query defaults.** Set `query_budget` to a positive integer and `query_depth` to an integer from 1 to 6:
```ini
query_budget=4000
query_depth=3
```
For `graphify query`, explicit `--budget N` / `--budget=N` and `--depth N` / `--depth=N` override these settings independently. Without a project setting or explicit option, the defaults remain budget 2000 and depth 2. These keys do not change the MCP server's defaults.
Settings come from the project owning the selected `--graph`, even when the command runs from another directory. An existing absolute directory in the graph's sibling `.graphify_root` marker identifies that project. Otherwise a matching relative `GRAPHIFY_OUT` suffix identifies it; absolute, empty, traversal-containing or nonmatching output paths fall back to the graph file's directory. Relative markers are ignored.
The query command always reads that project's `.graphifyrc`. An invalid recognized setting or an unreadable file produces one stderr warning and discards all project settings for that query; explicit options still apply. The settings parser stays strict for its other callers. Existing explicit budget values retain their behavior; persisted `query_budget` values must be positive.
---
## Team setup
@@ -410,6 +444,9 @@ Beyond your AI assistant, query `graph.json` straight from the CLI with `graphif
Backends, API keys, hook behavior, and tuning are controlled by environment variables. Full table: **[Configuration](https://docs.graphify.com/reference/configuration)**.
- **Claude API prompt caching**: `GRAPHIFY_CLAUDE_PROMPT_CACHE` controls system-prompt caching for `--backend claude`. Unset or blank keeps caching enabled; `1`, `true`, `yes`, or `on` explicitly enables it, and `0`, `false`, `no`, or `off` disables it (case-insensitive, surrounding whitespace ignored). Invalid values raise an error before sending a request. For example, run `GRAPHIFY_CLAUDE_PROMPT_CACHE=0 graphify extract . --backend claude` when an Anthropic-compatible endpoint rejects `cache_control`. Disabling sends the original plain-text system prompt. The setting applies equally to official Anthropic and custom `ANTHROPIC_BASE_URL` / `ANTHROPIC_MODEL` endpoints, including deep mode; it does not affect Bedrock, Claude CLI, or Graphify's local extraction cache. Enabling requests caching but cannot guarantee cache hits: the endpoint/model must support it and the prompt must meet its minimum length. Unsupported caching errors are not silently retried without caching.
- **Claude CLI model**: `GRAPHIFY_CLAUDE_CLI_MODEL` overrides the model for the `claude-cli` backend (default: Opus). `haiku` or `sonnet` are usually enough for community naming; the semantic extraction pass benefits from a larger model.
---
## Privacy
@@ -464,7 +501,7 @@ Every command and flag, with examples: **[CLI reference](https://docs.graphify.c
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).
New here? Say hi on [Discord](https://discord.gg/XDnKVpzdXB) or in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
New here? Say hi on [Discord](https://discord.gg/graphify) or in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +531,7 @@ Building something in the graphify ecosystem? That is encouraged. If your projec
<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://discord.gg/graphify"><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>
+4 -1
View File
@@ -28,7 +28,7 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| Vector | Mitigation |
|--------|-----------|
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. It also rejects embedded credentials, port 0, and missing hostnames. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
| 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. |
@@ -38,6 +38,9 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| 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 parameterized to avoid unchecked traversal where appropriate. |
| Symlink escape during ingest | `ingest` checks names with `lstat` and creates capture files exclusively. If another entry takes the selected name, the capture retries with a numbered name. |
| Credentials in persisted text | `security.redact_secrets()` replaces credential-shaped substrings in labels and rationale text before they are written to `graph.json`. |
| Destructive uninstall | `uninstall --purge` refuses to delete the project folder, the home directory, or a filesystem root, including when `GRAPHIFY_OUT` points outside the project. |
| 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
+1 -1
View File
@@ -6,7 +6,7 @@ Thanks for using graphify. Here is where to go, depending on what you need.
- **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.
- **Discord:** [discord.gg/graphify](https://discord.gg/graphify) 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.
+7 -6
View File
@@ -5,15 +5,15 @@
graphify processes your files in three passes:
**Pass 1 — Code structure (free, no API calls)**
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. 25 languages supported. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. About 40 languages are supported: 33 are parsed with tree-sitter grammars and 7 (Dart, Apex, COBOL, Razor, Blade, Pascal and Robot Framework) use built-in parsers. A few languages need an optional extra, e.g. `pip install "graphifyy[sql]"`; graphify tells you which extra to install if one is missing. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
Code files are not sent to the LLM semantic extractor in the normal pipeline. If a corpus contains only code files, Pass 3 is skipped entirely; semantic extraction is reserved for docs, papers, images, and transcripts.
**Pass 2 — Video and audio (local, no API calls)**
Video and audio files are transcribed with faster-whisper. To focus the transcript on your domain, the transcription prompt is seeded with your top god nodes (the most-connected concepts in your code graph so far). Transcripts are cached — re-runs skip already-processed files.
**Pass 3 — Docs, papers, images (Claude subagents, costs tokens)**
Claude runs in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
**Pass 3 — Docs, papers, images (LLM subagents, costs tokens)**
Your assistant's subagents (or, with `graphify extract --backend`, a model such as Gemini, Kimi, OpenAI, DeepSeek or a local Ollama model) run in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
Before Pass 3, optional converters turn supported pointer/binary formats into
Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
@@ -27,7 +27,7 @@ Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
Communities are found using the [Leiden algorithm](https://www.nature.com/articles/s41598-019-41695-z) — a graph-clustering method that groups nodes by edge density. Nodes with many connections between them end up in the same community.
**No embeddings needed.** The semantic similarity edges that Claude extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
**No embeddings needed.** The semantic similarity edges that the model extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
---
@@ -38,7 +38,7 @@ Every relationship is tagged with one of three labels:
| Tag | Meaning |
|-----|---------|
| `EXTRACTED` | Found directly in the source (e.g. a function call, an import) |
| `INFERRED` | A reasonable inference Claude made, with a `confidence_score` (0.0–1.0) |
| `INFERRED` | A reasonable inference the model made, with a `confidence_score` (0.0–1.0) |
| `AMBIGUOUS` | Uncertain — flagged in the report for manual review |
EXTRACTED edges always have confidence 1.0. INFERRED edges use a discrete rubric:
@@ -70,7 +70,7 @@ Each `worked/` folder in the repo has the raw input files and actual output (`GR
## Parallel extraction
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel Claude subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel LLM subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
---
@@ -97,5 +97,6 @@ Each edge has:
- `confidence` — `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`
- `confidence_score` — float (INFERRED only)
- `source_file` — where the relationship was found
- `also_seen` — optional; when the same relation between the same two nodes was found more than once, the edge keeps the highest-confidence copy and lists each other copy's `confidence`, `confidence_score`, `source_file` and `source_location` here, weakest first. `graphify path` shows their tags next to the edge's own (`[AMBIGUOUS/INFERRED]`)
Hyperedges (group relationships connecting 3+ nodes) live in `G.graph["hyperedges"]`.
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ viz_node_limit=0
المساهمات مرحّب بها. راجع **[CONTRIBUTING.md](../../CONTRIBUTING.md)** لإعداد التطوير، وأوامر الاختبار وتكافؤ CI، وسير عمل git، وما يصنع مساهمة قوية (الأمثلة العملية وتقارير أخطاء الاستخراج هي الأكثر فائدة). المعمارية وكيفية إضافة لغة: [ARCHITECTURE.md](../../ARCHITECTURE.md).
جديد هنا؟ ألقِ التحية على [Discord](https://discord.gg/XDnKVpzdXB) أو في [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
جديد هنا؟ ألقِ التحية على [Discord](https://discord.gg/graphify) أو في [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Made with [contrib.rocks](https://contrib.rocks).
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Každý příkaz a přepínač, s příklady: **[CLI reference](https://docs.gra
Příspěvky jsou vítány. Viz **[CONTRIBUTING.md](../../CONTRIBUTING.md)** pro vývojové nastavení, příkazy pro testy a paritu s CI, git workflow a to, co dělá silný příspěvek (vypracované příklady a hlášení chyb extrakce jsou nejužitečnější). Architektura a jak přidat jazyk: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Jste tu noví? Pozdravte nás na [Discordu](https://discord.gg/XDnKVpzdXB) nebo v [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Jste tu noví? Pozdravte nás na [Discordu](https://discord.gg/graphify) nebo v [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Stavíte něco v ekosystému graphify? To je podporováno. Pokud váš projekt p
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Hver kommando og hvert flag, med eksempler: **[CLI-reference](https://docs.graph
Bidrag er velkomne. Se **[CONTRIBUTING.md](../../CONTRIBUTING.md)** for udviklingsopsætningen, test- og CI-paritetskommandoerne, git-workflowet og hvad der gør et stærkt bidrag (gennemarbejdede eksempler og fejlrapporter om ekstraktion er de mest nyttige). Arkitektur og hvordan man tilføjer et sprog: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Ny her? Sig hej på [Discord](https://discord.gg/XDnKVpzdXB) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Ny her? Sig hej på [Discord](https://discord.gg/graphify) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Bygger du noget i graphify-økosystemet? Det opmuntres. Hvis dit projekt bruger
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Jeder Befehl und jedes Flag, mit Beispielen: **[CLI-Referenz](https://docs.graph
Beiträge sind willkommen. Siehe **[CONTRIBUTING.md](../../CONTRIBUTING.md)** für die Entwicklungseinrichtung, die Test- und CI-Paritätsbefehle, den Git-Workflow und was einen starken Beitrag ausmacht (durchgearbeitete Beispiele und Extraktions-Fehlerberichte sind am nützlichsten). Architektur und wie man eine Sprache hinzufügt: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Neu hier? Sagen Sie Hallo auf [Discord](https://discord.gg/XDnKVpzdXB) oder in den [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Neu hier? Sagen Sie Hallo auf [Discord](https://discord.gg/graphify) oder in den [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Bauen Sie etwas im graphify-Ökosystem? Das ist erwünscht. Wenn Ihr Projekt "gr
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ viz_node_limit=0
Οι συνεισφορές είναι ευπρόσδεκτες. Δείτε το **[CONTRIBUTING.md](../../CONTRIBUTING.md)** για τη ρύθμιση ανάπτυξης, τις εντολές test και CI-parity, τη ροή εργασίας git, και τι κάνει μια ισχυρή συνεισφορά (τα δουλεμένα παραδείγματα και οι αναφορές σφαλμάτων εξαγωγής είναι τα πιο χρήσιμα). Αρχιτεκτονική και πώς να προσθέσετε μια γλώσσα: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Νέοι εδώ; Πείτε ένα γεια στο [Discord](https://discord.gg/XDnKVpzdXB) ή στα [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Νέοι εδώ; Πείτε ένα γεια στο [Discord](https://discord.gg/graphify) ή στα [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -486,7 +486,7 @@ viz_node_limit=0
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Cada comando y flag, con ejemplos: **[Referencia de CLI](https://docs.graphify.c
Las contribuciones son bienvenidas. Consulta **[CONTRIBUTING.md](../../CONTRIBUTING.md)** para la configuración de desarrollo, los comandos de pruebas y de paridad con CI, el flujo de trabajo de git y qué hace una contribución sólida (los ejemplos trabajados y los informes de errores de extracción son los más útiles). Arquitectura y cómo añadir un lenguaje: [ARCHITECTURE.md](../../ARCHITECTURE.md).
¿Nuevo por aquí? Saluda en [Discord](https://discord.gg/XDnKVpzdXB) o en [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
¿Nuevo por aquí? Saluda en [Discord](https://discord.gg/graphify) o en [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ El README está disponible en 32 idiomas. Usa el selector de idioma en la parte
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ viz_node_limit=0
مشارکت‌ها خوش‌آمد هستند. برای راه‌اندازی توسعه، فرمان‌های آزمون و برابری با CI، گردش‌کار git، و اینکه چه چیزی یک مشارکت قوی را می‌سازد (مثال‌های عملی و گزارش‌های باگ استخراج مفیدترین‌ها هستند) **[CONTRIBUTING.md](../../CONTRIBUTING.md)** را ببینید. معماری و چگونگی افزودن یک زبان: [ARCHITECTURE.md](../../ARCHITECTURE.md).
تازه‌وارد هستید؟ در [Discord](https://discord.gg/XDnKVpzdXB) یا در [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) سلام کنید.
تازه‌وارد هستید؟ در [Discord](https://discord.gg/graphify) یا در [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) سلام کنید.
---
@@ -494,7 +494,7 @@ viz_node_limit=0
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Jokainen komento ja lippu, esimerkkien kera: **[CLI-viite](https://docs.graphify
Osallistumiset ovat tervetulleita. Katso **[CONTRIBUTING.md](../../CONTRIBUTING.md)** kehitysympäristön, testi- ja CI-pariteettikomentojen, git-työnkulun ja sen osalta, mikä tekee vahvan osallistumisen (työstetyt esimerkit ja ekstraktiovikailmoitukset ovat hyödyllisimpiä). Arkkitehtuuri ja miten lisätä kieli: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Uusi täällä? Sano hei [Discordissa](https://discord.gg/XDnKVpzdXB) tai [GitHub Discussionsissa](https://github.com/Graphify-Labs/graphify/discussions).
Uusi täällä? Sano hei [Discordissa](https://discord.gg/graphify) tai [GitHub Discussionsissa](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Rakennatko jotain graphify-ekosysteemissä? Sitä kannustetaan. Jos projektisi k
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Ang [**Graphify Cloud**](https://app.graphify.com/login) ay ang laging-nakabukas
Malugod na tinatanggap ang mga kontribusyon. Tingnan ang **[CONTRIBUTING.md](../../CONTRIBUTING.md)** para sa development setup, ang mga utos para sa test at CI-parity, ang git workflow, at kung ano ang bumubuo ng isang matibay na kontribusyon (ang mga worked example at extraction bug report ang pinaka-kapaki-pakinabang). Arkitektura at kung paano magdagdag ng wika: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Bago rito? Kumusta sa [Discord](https://discord.gg/XDnKVpzdXB) o sa [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Bago rito? Kumusta sa [Discord](https://discord.gg/graphify) o sa [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ May ginagawa ka ba sa ekosistema ng graphify? Iyon ay hinihikayat. Kung ang proy
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Chaque commande et chaque option, avec des exemples : **[CLI reference](https://
Les contributions sont les bienvenues. Voir **[CONTRIBUTING.md](../../CONTRIBUTING.md)** pour la configuration de développement, les commandes de test et de parité CI, le workflow git, et ce qui fait une contribution solide (les exemples travaillés et les rapports de bugs d'extraction sont les plus utiles). Architecture et comment ajouter un langage : [ARCHITECTURE.md](../../ARCHITECTURE.md).
Nouveau ici ? Dites bonjour sur [Discord](https://discord.gg/XDnKVpzdXB) ou dans les [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Nouveau ici ? Dites bonjour sur [Discord](https://discord.gg/graphify) ou dans les [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Vous construisez quelque chose dans l'écosystème graphify ? C'est encouragé.
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ viz_node_limit=0
תרומות מתקבלות בברכה. ראו **[CONTRIBUTING.md](../../CONTRIBUTING.md)** עבור הגדרת הפיתוח, פקודות הבדיקה ושקילות ה-CI, תהליך העבודה של git, ומה הופך תרומה לחזקה (דוגמאות מעשיות ודיווחי באגים של חילוץ הם השימושיים ביותר). ארכיטקטורה ואיך להוסיף שפה: [ARCHITECTURE.md](../../ARCHITECTURE.md).
חדשים כאן? אמרו שלום ב-[Discord](https://discord.gg/XDnKVpzdXB) או ב-[GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
חדשים כאן? אמרו שלום ב-[Discord](https://discord.gg/graphify) או ב-[GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -486,7 +486,7 @@ viz_node_limit=0
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ viz_node_limit=0
योगदान का स्वागत है। डेवलपमेंट सेटअप, टेस्ट और CI-समतुल्य कमांड, git वर्कफ़्लो, और क्या एक मजबूत योगदान बनाता है (worked examples और एक्सट्रैक्शन बग रिपोर्ट सबसे उपयोगी हैं) के लिए **[CONTRIBUTING.md](../../CONTRIBUTING.md)** देखें। आर्किटेक्चर और कोई भाषा कैसे जोड़ें: [ARCHITECTURE.md](../../ARCHITECTURE.md)।
यहां नए हैं? [Discord](https://discord.gg/XDnKVpzdXB) पर या [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) में नमस्ते कहें।
यहां नए हैं? [Discord](https://discord.gg/graphify) पर या [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) में नमस्ते कहें।
---
@@ -494,7 +494,7 @@ graphify पारिस्थितिकी तंत्र में कु
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ A [**Graphify Cloud**](https://app.graphify.com/login) a graphify tetejére ép
A hozzájárulásokat szívesen fogadjuk. A fejlesztési beállításért, a teszt- és CI-paritási parancsokért, a git-munkafolyamatért és azért, hogy mi tesz egy hozzájárulást erőssé (a kidolgozott példák és a kinyerési hibajelentések a leghasznosabbak), lásd: **[CONTRIBUTING.md](../../CONTRIBUTING.md)**. Architektúra és hogyan adjunk hozzá egy nyelvet: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Új itt? Köszönjön be a [Discordon](https://discord.gg/XDnKVpzdXB) vagy a [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) felületen.
Új itt? Köszönjön be a [Discordon](https://discord.gg/graphify) vagy a [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) felületen.
---
@@ -494,7 +494,7 @@ A README 32 nyelven érhető el. Használja a fájl tetején lévő nyelvváltó
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Setiap perintah dan flag, dengan contoh: **[CLI reference](https://docs.graphify
Kontribusi disambut baik. Lihat **[CONTRIBUTING.md](../../CONTRIBUTING.md)** untuk penyiapan pengembangan, perintah test dan CI-parity, alur kerja git, dan apa yang membuat kontribusi kuat (worked examples dan laporan bug ekstraksi adalah yang paling berguna). Arsitektur dan cara menambahkan bahasa: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Baru di sini? Sapa di [Discord](https://discord.gg/XDnKVpzdXB) atau di [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Baru di sini? Sapa di [Discord](https://discord.gg/graphify) atau di [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Sedang membangun sesuatu di ekosistem graphify? Itu dianjurkan. Jika proyek Anda
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Ogni comando e flag, con esempi: **[CLI reference](https://docs.graphify.com/ref
I contributi sono benvenuti. Vedi **[CONTRIBUTING.md](../../CONTRIBUTING.md)** per la configurazione di sviluppo, i comandi di test e di parità con la CI, il flusso di lavoro git e cosa rende un contributo solido (gli esempi elaborati e le segnalazioni di bug di estrazione sono i più utili). Architettura e come aggiungere un linguaggio: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Nuovo qui? Saluta su [Discord](https://discord.gg/XDnKVpzdXB) o nelle [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Nuovo qui? Saluta su [Discord](https://discord.gg/graphify) o nelle [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Stai costruendo qualcosa nell'ecosistema di graphify? È incoraggiato. Se il tuo
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ AI アシスタントに加えて、`graphify query`、`graphify path`、`graphi
コントリビューションを歓迎します。開発環境のセットアップ、テストと CI-parity のコマンド、git ワークフロー、そして何が優れたコントリビューションになるか(実例と抽出バグレポートが最も役立ちます)については、**[CONTRIBUTING.md](../../CONTRIBUTING.md)** を参照してください。アーキテクチャと言語の追加方法: [ARCHITECTURE.md](../../ARCHITECTURE.md)。
初めてですか?[Discord](https://discord.gg/XDnKVpzdXB) または [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) で挨拶してください。
初めてですか?[Discord](https://discord.gg/graphify) または [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) で挨拶してください。
---
@@ -486,7 +486,7 @@ graphify のエコシステムで何かを作っていますか?それは歓
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ AI 어시스턴트 외에도, `graphify query`, `graphify path`, `graphify expla
기여를 환영합니다. 개발 환경 설정, 테스트 및 CI-parity 명령, git 워크플로, 그리고 무엇이 강력한 기여가 되는지(실제 예시와 추출 버그 리포트가 가장 유용합니다)는 **[CONTRIBUTING.md](../../CONTRIBUTING.md)** 를 참고하세요. 아키텍처와 언어 추가 방법: [ARCHITECTURE.md](../../ARCHITECTURE.md).
처음이신가요? [Discord](https://discord.gg/XDnKVpzdXB) 또는 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 에서 인사해 주세요.
처음이신가요? [Discord](https://discord.gg/graphify) 또는 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 에서 인사해 주세요.
---
@@ -486,7 +486,7 @@ graphify 생태계에서 무언가를 만들고 계신가요? 그것은 권장
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Elk commando en elke flag, met voorbeelden: **[CLI reference](https://docs.graph
Bijdragen zijn welkom. Zie **[CONTRIBUTING.md](../../CONTRIBUTING.md)** voor de ontwikkelopzet, de test- en CI-pariteitscommando's, de git-workflow en wat een sterke bijdrage maakt (uitgewerkte voorbeelden en extractiebugrapporten zijn het nuttigst). Architectuur en hoe je een taal toevoegt: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Nieuw hier? Zeg hallo op [Discord](https://discord.gg/XDnKVpzdXB) of in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Nieuw hier? Zeg hallo op [Discord](https://discord.gg/graphify) of in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Bouw je iets in het graphify-ecosysteem? Dat wordt aangemoedigd. Als je project
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Hver kommando og hvert flagg, med eksempler: **[CLI-referanse](https://docs.grap
Bidrag er velkomne. Se **[CONTRIBUTING.md](../../CONTRIBUTING.md)** for utviklingsoppsettet, test- og CI-paritetskommandoene, git-arbeidsflyten og hva som gjør et sterkt bidrag (gjennomarbeidede eksempler og feilrapporter om ekstraksjon er mest nyttige). Arkitektur og hvordan man legger til et språk: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Ny her? Si hei på [Discord](https://discord.gg/XDnKVpzdXB) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Ny her? Si hei på [Discord](https://discord.gg/graphify) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Bygger du noe i graphify-økosystemet? Det oppmuntres. Hvis prosjektet ditt bruk
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Każde polecenie i flaga, z przykładami: **[CLI reference](https://docs.graphif
Wkład jest mile widziany. Zobacz **[CONTRIBUTING.md](../../CONTRIBUTING.md)**, aby poznać konfigurację środowiska deweloperskiego, polecenia testów i zgodności z CI, przepływ pracy w git oraz to, co składa się na mocny wkład (opracowane przykłady i zgłoszenia błędów ekstrakcji są najbardziej przydatne). Architektura i jak dodać język: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Jesteś tu nowy? Przywitaj się na [Discordzie](https://discord.gg/XDnKVpzdXB) lub w [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Jesteś tu nowy? Przywitaj się na [Discordzie](https://discord.gg/graphify) lub w [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Budujesz coś w ekosystemie graphify? To jest zachęcane. Jeśli Twój projekt u
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ O [**Graphify Cloud**](https://app.graphify.com/login) é a camada sempre ativa
Contribuições são bem-vindas. Veja **[CONTRIBUTING.md](../../CONTRIBUTING.md)** para a configuração de desenvolvimento, os comandos de teste e de paridade com a CI, o fluxo de trabalho do git, e o que faz uma contribuição forte (exemplos resolvidos e relatórios de bugs de extração são os mais úteis). Arquitetura e como adicionar uma linguagem: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Novo por aqui? Diga oi no [Discord](https://discord.gg/XDnKVpzdXB) ou nas [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Novo por aqui? Diga oi no [Discord](https://discord.gg/graphify) ou nas [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Está construindo algo no ecossistema do graphify? Isso é incentivado. Se o seu
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Fiecare comandă și opțiune, cu exemple: **[Referința CLI](https://docs.graph
Contribuțiile sunt binevenite. Vedeți **[CONTRIBUTING.md](../../CONTRIBUTING.md)** pentru configurarea de dezvoltare, comenzile de test și de paritate cu CI, fluxul de lucru git și ce înseamnă o contribuție puternică (exemplele lucrate și rapoartele de erori de extracție sunt cele mai utile). Arhitectura și cum să adăugați un limbaj: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Nou aici? Salutați pe [Discord](https://discord.gg/XDnKVpzdXB) sau în [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Nou aici? Salutați pe [Discord](https://discord.gg/graphify) sau în [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Construiți ceva în ecosistemul graphify? Asta este încurajat. Dacă proiectul
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ viz_node_limit=0
Вклад приветствуется. Смотрите **[CONTRIBUTING.md](../../CONTRIBUTING.md)** для настройки среды разработки, команд тестирования и паритета с CI, рабочего процесса git и того, что делает вклад сильным (проработанные примеры и отчёты об ошибках извлечения наиболее полезны). Архитектура и как добавить язык: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Впервые здесь? Поздоровайтесь в [Discord](https://discord.gg/XDnKVpzdXB) или в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Впервые здесь? Поздоровайтесь в [Discord](https://discord.gg/graphify) или в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ README доступен на 32 языках. Используйте перек
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Alla kommandon och flaggor, med exempel: **[CLI-referens](https://docs.graphify.
Bidrag är välkomna. Se **[CONTRIBUTING.md](../../CONTRIBUTING.md)** för utvecklingsmiljön, kommandona för test och CI-paritet, git-arbetsflödet och vad som gör ett starkt bidrag (utarbetade exempel och felrapporter om extraktion är mest användbara). Arkitektur och hur man lägger till ett språk: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Ny här? Säg hej på [Discord](https://discord.gg/XDnKVpzdXB) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Ny här? Säg hej på [Discord](https://discord.gg/graphify) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ Bygger du något i graphify-ekosystemet? Det uppmuntras. Om ditt projekt använd
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ viz_node_limit=0
ยินดีรับการมีส่วนร่วม ดู **[CONTRIBUTING.md](../../CONTRIBUTING.md)** สำหรับการตั้งค่าสภาพแวดล้อมการพัฒนา, คำสั่งทดสอบและ CI-parity, เวิร์กโฟลว์ git และอะไรที่ทำให้การมีส่วนร่วมแข็งแกร่ง (ตัวอย่างจริงและรายงานบั๊กการสกัดมีประโยชน์ที่สุด) สถาปัตยกรรมและวิธีเพิ่มภาษา: [ARCHITECTURE.md](../../ARCHITECTURE.md)
เพิ่งมาที่นี่? ทักทายบน [Discord](https://discord.gg/XDnKVpzdXB) หรือใน [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions)
เพิ่งมาที่นี่? ทักทายบน [Discord](https://discord.gg/graphify) หรือใน [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions)
---
@@ -486,7 +486,7 @@ README นี้มีให้ใน 32 ภาษา ใช้ตัวสล
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Yaygın kurulum ve çıkarım sorunları ve bunların çözümleri: **[Sorun gid
Katkılar memnuniyetle karşılanır. Geliştirme kurulumu, test ve CI eşitlik komutları, git iş akışı ve güçlü bir katkıyı neyin oluşturduğu (işlenmiş örnekler ve çıkarım hata raporları en yararlı olanlardır) için **[CONTRIBUTING.md](../../CONTRIBUTING.md)** dosyasına bakın. Mimari ve bir dilin nasıl ekleneceği: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Buraya yeni mi geldiniz? [Discord](https://discord.gg/XDnKVpzdXB) üzerinde veya [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) içinde selam verin.
Buraya yeni mi geldiniz? [Discord](https://discord.gg/graphify) üzerinde veya [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) içinde selam verin.
---
@@ -494,7 +494,7 @@ graphify ekosisteminde bir şeyler mi inşa ediyorsunuz? Buna teşvik ediliyor.
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ viz_node_limit=0
Внески вітаються. Дивіться **[CONTRIBUTING.md](../../CONTRIBUTING.md)** для налаштування розробки, команд тестування та відповідності CI, git-процесу та того, що робить внесок сильним (опрацьовані приклади та звіти про баги вилучення найкорисніші). Архітектура та як додати мову: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Новачок тут? Привітайтеся в [Discord](https://discord.gg/XDnKVpzdXB) або в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Новачок тут? Привітайтеся в [Discord](https://discord.gg/graphify) або в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -494,7 +494,7 @@ README доступний 32 мовами. Використовуйте пере
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -464,7 +464,7 @@ Har bir buyruq va bayroq, misollar bilan: **[CLI ma'lumotnomasi](https://docs.gr
Hissalar olqishlanadi. Ishlab chiqish sozlash, test va CI-parity buyruqlari, git ish oqimi va kuchli hissani nima tashkil qilishi (ishlab chiqilgan misollar va ekstraktsiya xato hisobotlari eng foydali) uchun **[CONTRIBUTING.md](../../CONTRIBUTING.md)** ga qarang. Arxitektura va til qanday qo'shiladi: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Bu yerda yangimisiz? [Discord](https://discord.gg/XDnKVpzdXB) da yoki [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) da salom ayting.
Bu yerda yangimisiz? [Discord](https://discord.gg/graphify) da yoki [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) da salom ayting.
---
@@ -494,7 +494,7 @@ graphify ekotizimida biror narsa quryapsizmi? Bu rag'batlantiriladi. Agar loyiha
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ Mọi lệnh và cờ, kèm ví dụ: **[CLI reference](https://docs.graphify.co
Hoan nghênh đóng góp. Xem **[CONTRIBUTING.md](../../CONTRIBUTING.md)** để biết thiết lập môi trường phát triển, các lệnh kiểm thử và CI-parity, quy trình git, và điều gì làm nên một đóng góp mạnh (các ví dụ thực tế và báo cáo lỗi trích xuất là hữu ích nhất). Kiến trúc và cách thêm một ngôn ngữ: [ARCHITECTURE.md](../../ARCHITECTURE.md).
Mới đến? Chào một tiếng trên [Discord](https://discord.gg/XDnKVpzdXB) hoặc trong [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
Mới đến? Chào một tiếng trên [Discord](https://discord.gg/graphify) hoặc trong [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
---
@@ -486,7 +486,7 @@ README có sẵn trong 32 ngôn ngữ. Dùng trình chuyển ngôn ngữ ở đ
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ viz_node_limit=0
欢迎贡献。请见 **[CONTRIBUTING.md](../../CONTRIBUTING.md)** 以了解开发环境设置、测试与 CI-parity 命令、git 工作流,以及什么构成一次出色的贡献(可运行的示例与提取错误报告是最有用的)。架构与如何新增一种语言:[ARCHITECTURE.md](../../ARCHITECTURE.md)。
刚来吗?在 [Discord](https://discord.gg/XDnKVpzdXB) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打声招呼。
刚来吗?在 [Discord](https://discord.gg/graphify) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打声招呼。
---
@@ -486,7 +486,7 @@ Made with [contrib.rocks](https://contrib.rocks).
<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://discord.gg/graphify"><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>
+3 -3
View File
@@ -21,7 +21,7 @@
<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://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://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></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://discord.gg/graphify"><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>
@@ -456,7 +456,7 @@ viz_node_limit=0
歡迎貢獻。見 **[CONTRIBUTING.md](../../CONTRIBUTING.md)** 了解開發環境建置、測試與 CI 對齊的命令、git 工作流程,以及什麼樣的貢獻才算扎實(可執行的範例和提取 bug 報告最有用)。架構和如何新增一門語言:[ARCHITECTURE.md](../../ARCHITECTURE.md)。
新來的?在 [Discord](https://discord.gg/XDnKVpzdXB) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打個招呼。
新來的?在 [Discord](https://discord.gg/graphify) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打個招呼。
---
@@ -486,7 +486,7 @@ Made with [contrib.rocks](https://contrib.rocks).
<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://discord.gg/graphify"><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>
+30 -9
View File
@@ -122,6 +122,7 @@ from graphify.install import ( # noqa: E402,F401
_OPENCODE_PLUGIN_HEADER,
_drop_opencode_config_entry,
_opencode_config_names_plugin,
_opencode_dir,
_opencode_plugin_is_v1_only,
_PLATFORM_CONFIG,
_skill_lock,
@@ -429,12 +430,21 @@ def _refresh_v1_opencode_plugins() -> None:
if os.environ.get("GRAPHIFY_NO_AUTO_REFRESH", "").strip().lower() in ("1", "true", "yes"):
return
try:
directories = dict.fromkeys(d.resolve() for d in (Path.cwd(), Path.home()))
# The cwd and home .opencode dirs are where installs before #3398 wrote,
# ~/.config/opencode is the global install's dir since.
directories = dict.fromkeys(
d.resolve()
for d in (
_opencode_dir(project=True, project_dir=Path.cwd()),
_opencode_dir(project=True, project_dir=Path.home()),
_opencode_dir(project=False),
)
)
except (OSError, RuntimeError):
return
loadable: "bool | None" = None # asked once, and only when an old plugin is found
for directory in directories:
plugin_file = directory / _OPENCODE_PLUGIN_PATH
plugin_file = directory / _OPENCODE_PLUGIN_PATH.relative_to(".opencode")
def pending() -> "bool | None":
"""True for an old plugin, False for a stale entry only, None for neither."""
@@ -486,7 +496,7 @@ def _refresh_v1_opencode_plugins() -> None:
elif dropped:
print(
f"graphify: removed the stale graphify entry from "
f"{directory / _OPENCODE_CONFIG_PATH}; set GRAPHIFY_NO_AUTO_REFRESH=1 to disable",
f"{directory / _OPENCODE_CONFIG_PATH.name}; set GRAPHIFY_NO_AUTO_REFRESH=1 to disable",
file=sys.stderr,
)
@@ -861,7 +871,11 @@ def _run_cli() -> None:
print("Usage: graphify <command>")
print()
print("Commands:")
print(" install [--platform P] copy skill to platform config dir (claude|windows|codebuddy|codex|opencode|aider|amp|agents|claw|droid|trae|trae-cn|gemini|cursor|antigravity|hermes|kiro|pi|devin)")
# Derive the list from the same source as `graphify install` usage
# (_print_install_usage) so the two can never drift apart, rather than
# hand-maintaining it (amp, copilot, antigravity-windows had been missed, #4655).
_platform_values = "|".join([*_PLATFORM_CONFIG, "gemini", "cursor"])
print(f" install [--platform P] copy skill to platform config dir ({_platform_values})")
print(" uninstall remove graphify from all detected platforms in one shot")
print(" --purge also delete graphify-out/ directory")
print(" path \"A\" \"B\" shortest path between two nodes in graph.json")
@@ -905,13 +919,13 @@ def _run_cli() -> None:
print(" --graph <path> path to graph.json (default <path>/graphify-out/graph.json)")
print(" --no-label keep 'Community N' placeholders (skip LLM community naming)")
print(" --backend=<name> backend to use for community naming (default: auto-detect)")
print(" --model=<name> model to use for community naming")
print(" --model=<name> model to use for community naming (claude-cli also reads GRAPHIFY_CLAUDE_CLI_MODEL)")
print(" --max-concurrency=N parallel community-labeling LLM calls (default 4; forced to 1 for ollama/claude-cli)")
print(" --batch-size=N communities per labeling LLM call (default 100)")
print(" --batch-size=N communities per labeling LLM call (default 100, sized for ~16k context; use 40 for 8k)")
print(" label <path> (re)name communities with the configured LLM backend, regenerate report")
print(" --missing-only keep existing labels and only name missing/placeholder communities")
print(" --backend=<name> backend to use (default: auto-detect from API keys)")
print(" --model=<name> model to use for community naming")
print(" --model=<name> model to use for community naming (claude-cli also reads GRAPHIFY_CLAUDE_CLI_MODEL)")
print(" --max-concurrency=N parallel labeling LLM calls (default 4; forced to 1 for ollama/claude-cli)")
print(" --batch-size=N communities per labeling LLM call (default 100)")
print(" query \"<question>\" BFS traversal of graph.json for a question")
@@ -919,7 +933,10 @@ def _run_cli() -> None:
print(" --context C explicit edge-context filter (repeatable)")
print(" --seed X start at node X (id, label or file path; repeatable)")
print(" instead of the question's keyword matches")
print(" --budget N cap output at N tokens (default 2000)")
print(" --budget N, --budget=N cap output at N tokens (default 2000)")
print(" --depth N, --depth=N traversal depth 1-6 (default 2)")
print(" absent options use the selected graph project's .graphifyrc")
print(" query_budget / query_depth. Explicit options override project values.")
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
print(" query, path and explain exit 0 with an answer, 3 when a name is ambiguous")
print(" (the candidates are listed), 4 when no node matches")
@@ -965,6 +982,8 @@ def _run_cli() -> None:
print(" and OPENAI_MODEL to the model name your server serves")
print(" claude also reaches custom Anthropic-compatible endpoints (LiteLLM")
print(" proxy, gateways): set ANTHROPIC_BASE_URL and ANTHROPIC_MODEL")
print(" GRAPHIFY_CLAUDE_PROMPT_CACHE=0 disables Claude system-prompt caching")
print(" (default: enabled; set 1 to explicitly enable)")
print(" --model M override backend default model")
print(" --mode deep aggressive INFERRED-edge semantic extraction")
print(" --force full re-scan and re-dispatch: skip the incremental")
@@ -991,7 +1010,7 @@ def _run_cli() -> None:
print(" global list list repos in the global graph")
print(" global path print path to the global graph file")
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
print(" export html emit interactive graph.html [--graph PATH] [--labels PATH] [--node-limit N] [--no-viz]")
print(" export html emit interactive graph.html [--graph PATH] [--labels PATH] [--node-limit N, default 5000] [--no-viz]")
print(" export callflow-html emit Mermaid-based architecture/call-flow HTML")
print(" [GRAPH|DIR] [--graph PATH] [--labels PATH] [--report PATH] [--sections PATH] [--output HTML]")
print(" [--lang auto|zh-CN|en] [--max-sections N] [--diagram-scale N]")
@@ -1032,6 +1051,8 @@ def _run_cli() -> None:
)
print(" aider install write graphify section to AGENTS.md (Aider)")
print(" aider uninstall remove graphify section from AGENTS.md")
print(" amp install copy graphify skill + write AGENTS.md section (Amp)")
print(" amp uninstall remove graphify skill + AGENTS.md section (Amp)")
print(
" copilot install copy graphify skill to ~/.copilot/skills (GitHub Copilot CLI)"
)
+103 -19
View File
@@ -129,6 +129,29 @@ def _prefer_file_node(
if len(exact_file_nodes) == 1:
return exact_file_nodes[0]
# #2032 relabels colliding basenames to their shortest unique path suffix
# ("alpha/hooks.py"), so neither pass above nor the one below matches a file
# node whose basename is shared. The label is still a path form of the
# node's OWN source_file, which is what _is_file_node_label encodes (the
# predicate build/analyze already treat as "this node names its file").
# Checked before the L1 fallback because a module docstring (a `rationale`
# node located on the docstring's line) or a one-line top-level definition
# can also sit on L1, leaving that fallback with more than one candidate
# (#4698).
from graphify.build import _is_file_node_label
path_file_nodes = [
node_id
for node_id in node_ids
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
and _is_file_node_label(
str(graph.nodes[node_id].get("label", "")),
str(graph.nodes[node_id].get("source_file", "")),
)
]
if len(path_file_nodes) == 1:
return path_file_nodes[0]
l1_nodes = [
node_id
for node_id in node_ids
@@ -148,6 +171,36 @@ def _prefer_file_node(
return None
def resolve_reference_forms(graph: nx.Graph, query: str) -> str | None:
"""Resolve the reference forms `explain` accepts but `resolve_seed` did not.
`explain` resolves a `path::Symbol` reference (#3485) and a dotted Python
name (`pkg.mod.func` / `pkg.mod:func`, #4366) to a single node; `affected` and
`query --seed` rejected both with "No unique node match" even when `explain`
resolved the very same string. Following the README's own advice ("use the
precise ID returned by the graph") therefore forced a caller through
`explain` first just to obtain an id (#4792).
Only the two path-qualified forms are handled here — they carry their own
disambiguating context, so a match is never a guess. A bare name keeps going
through `resolve_seed`'s existing tiers, where an exact-name tie must stay
unresolved rather than be broken by graph-iteration order.
Returns the unique node id, or None to fall through to the ordinary tiers.
"""
from graphify.serve import _find_node_tiers
source_exact, exact, _prefix, _substring = _find_node_tiers(graph, query)
for tier in (source_exact, exact):
if len(tier) == 1:
return str(tier[0])
if tier:
# Several nodes in the winning tier is ambiguity, not precedence;
# do not fall back to a looser tier and pick one arbitrarily.
break
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
@@ -155,6 +208,11 @@ def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str |
query = query.rstrip("/\\") or query
if query in graph:
return query
# `path::Symbol` and dotted Python names resolve exactly as `explain` does
# (#4792); checked before the label tiers, which cannot express them.
qualified = resolve_reference_forms(graph, query)
if qualified is not None:
return qualified
query_lower = _normalize_label(query)
exact_label_matches = [
str(node_id)
@@ -260,19 +318,23 @@ def affected_nodes(
# 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))
member_queue = deque([seed])
while member_queue:
parent = member_queue.popleft()
if hasattr(graph, "out_edges"):
member_edges = graph.out_edges(parent, data=True)
else:
member_edges = (
(s, t, d) for s, t, d in graph.edges(data=True) if s == parent
)
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))
member_queue.append(member)
supertype_cache: dict[str, list[str]] = {}
# Overridden members walked without being reported; one that a real edge
@@ -330,6 +392,27 @@ def affected_nodes(
return hits
def resolve_seed_outcome(
graph: nx.Graph, query: str, root: Path | None = None
) -> tuple[str | None, list[str]]:
"""Resolve a seed and report why it failed, so the CLI can set an exit code.
`affected` printed "No unique node match" and still exited 0, so a script
could not branch on the outcome the README documents (3 = ambiguous,
4 = no match) while `explain` already follows it (#4792). Returns
``(node_id, [])`` on success, ``(None, rivals)`` when the query is the
ambiguous name of several nodes, and ``(None, [])`` when nothing matched.
"""
seed = resolve_seed(graph, query, root)
if seed is not None:
return seed, []
from graphify.serve import find_node_ambiguity
normalized = query.rstrip("/\\") or query
rivals = find_node_ambiguity(graph, normalized)
return None, [str(node_id) for node_id in rivals]
def format_affected(
graph: nx.Graph,
query: str,
@@ -337,9 +420,11 @@ def format_affected(
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
depth: int = 2,
root: Path | None = None,
seed: str | None = None,
) -> str:
relation_list = tuple(relations)
seed = resolve_seed(graph, query, root)
if seed is None:
seed = resolve_seed(graph, query, root)
if seed is None:
return f"No unique node match for {query}"
@@ -372,7 +457,8 @@ def load_graph(path: Path) -> nx.Graph:
from networkx.readwrite import json_graph
try:
raw = json.loads(path.read_text(encoding="utf-8"))
from graphify.paths import consumed, read_graph_json
raw = read_graph_json(path)
except (json.JSONDecodeError, OSError) as exc:
raise RuntimeError(
f"Cannot read graph file {path}: {exc}. "
@@ -387,7 +473,5 @@ def load_graph(path: Path) -> nx.Graph:
# (__main__.py) already normalizes this (#738; same class as #1198).
if "links" not in raw and "edges" in raw:
raw = dict(raw, links=raw["edges"])
try:
return json_graph.node_link_graph(raw, edges="links")
except TypeError:
return json_graph.node_link_graph(raw)
raw = dict(raw, nodes=consumed(raw["nodes"]), links=consumed(raw["links"]))
return json_graph.node_link_graph(raw, edges="links")
+40 -19
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
from pathlib import Path
import networkx as nx
from graphify.build import edge_data
from graphify.build import edge_datas
# Builtin/mock names that can appear as annotation-derived nodes in pre-existing
# graphs. Excluded from god-node ranking so they don't displace real abstractions
@@ -82,9 +82,13 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
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()'
# Method stub: AST extractor labels methods as '.method_name()'; C# methods
# carry their owner for display ('Owner.method_name()', #4883).
if label.startswith(".") and label.endswith("()"):
return True
from graphify.extractors.csharp import bare_csharp_method_label
if bare_csharp_method_label(label, source_file) is not None:
return True
# Module-level function stub: labeled 'function_name()' - only has a contains edge
# These are real functions but structurally isolated by definition; not a gap worth flagging
if label.endswith("()") and G.degree(node_id) <= 1:
@@ -406,18 +410,22 @@ def _cross_community_surprises(
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
result = []
for (u, v), score in top_edges:
data = edge_data(G, u, v)
result.append({
"source": G.nodes[u].get("label", u),
"target": G.nodes[v].get("label", v),
"source_files": [
G.nodes[u].get("source_file", ""),
G.nodes[v].get("source_file", ""),
],
"confidence": data.get("confidence", "EXTRACTED"),
"relation": data.get("relation", ""),
"note": f"Bridges graph structure (betweenness={score:.3f})",
})
for data in edge_datas(G, u, v):
result.append({
"source": G.nodes[u].get("label", u),
"target": G.nodes[v].get("label", v),
"source_files": [
G.nodes[u].get("source_file", ""),
G.nodes[v].get("source_file", ""),
],
"confidence": data.get("confidence", "EXTRACTED"),
"relation": data.get("relation", ""),
"note": f"Bridges graph structure (betweenness={score:.3f})",
})
if len(result) >= top_n:
break
if len(result) >= top_n:
break
return result
# Build node → community map
@@ -575,11 +583,19 @@ def suggest_questions(
and G.nodes[n].get("file_type") != "rationale"
]
if isolated:
has_semantic_layer = any(
G.nodes[n].get("file_type") in ("document", "paper", "image")
for n in G.nodes()
)
reason = (
"possible documentation gaps or missing edges" if has_semantic_layer
else "possible missing edges"
)
labels = [G.nodes[n].get("label", n) for n in isolated[:3]]
questions.append({
"type": "isolated_nodes",
"question": f"What connects {', '.join(f'`{l}`' for l in labels)} to the rest of the system?",
"why": f"{len(isolated)} weakly-connected nodes found - possible documentation gaps or missing edges.",
"why": f"{len(isolated)} weakly-connected nodes found - {reason}.",
})
# 5. Low-cohesion communities → structural questions
@@ -757,12 +773,14 @@ def find_import_cycles(
# 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"):
forward = not data.get("deferred") and not data.get("type_only")
# An undirected build keeps one edge per file pair, so the other file's
# runtime import back is only a stamp on this edge (#4839).
reverse = bool(data.get("reverse_import"))
if not forward and not reverse:
continue
src_file_attr = data.get("source_file", "")
@@ -787,7 +805,10 @@ def find_import_cycles(
if not tgt_file:
continue
file_graph.add_edge(src_file_attr, tgt_file)
if forward:
file_graph.add_edge(src_file_attr, tgt_file)
if reverse:
file_graph.add_edge(tgt_file, src_file_attr)
if not file_graph.edges():
return []
+603 -64
View File
@@ -70,6 +70,8 @@ def _lost_saved_semantic_nodes(
saved_nodes: list,
new_nodes: list,
deleted_sources: set[str] | None = None,
folded: dict[str, str] | None = None,
dedup_remap: dict[str, str] | None = None,
) -> list[dict]:
"""Saved semantic nodes whose ids are absent from the new graph.
@@ -80,6 +82,15 @@ def _lost_saved_semantic_nodes(
An auto-minted import stub (``external`` true, or ``type`` ``external``) is
rebuilt from the import edges of this run. Dropping one is not a lost
rationale or document node.
``folded`` (when given) maps each saved node id that build_from_json merged
into an AST twin to that twin's id, so a caller comparing node counts can
discount it.
``dedup_remap`` is the ``{merged-away id: survivor id}`` map entity dedup
produced this run (#4940). A saved id it folded into a survivor that is in
the new graph is one node, not a lost one. A survivor that is itself gone
excuses nothing: the content went with it.
"""
deleted = {
norm
@@ -89,8 +100,10 @@ def _lost_saved_semantic_nodes(
new_ids = {node.get("id") for node in new_nodes if isinstance(node, dict)}
# A semantic ghost deduplicated into its AST twin (#1145) loses its id but
# the symbol survives at the same (source_file, label).
new_ast_loc_nodes: set[tuple[str, str]] = set()
new_ast_loc_nodes: dict[tuple[str, str], str] = {}
ast_loc_collisions: set[tuple[str, str]] = set()
# AST file nodes, for the label-only fold of build_from_json Pass 2b (#3344).
new_ast_file_nodes: list[tuple[str, str]] = []
for node in new_nodes:
# Match build_from_json's strict canonical-AST check (#2334).
if not isinstance(node, dict) or node.get("_origin") != "ast":
@@ -101,13 +114,15 @@ def _lost_saved_semantic_nodes(
lbl = str(node.get("label", "")).strip()
if not lbl:
continue
if _is_file_node_label(lbl, sf):
new_ast_file_nodes.append((str(node.get("id")), sf))
norm_sf = _norm_source_file(sf)
if not norm_sf:
continue
key = (norm_sf, lbl)
if key in new_ast_loc_nodes:
ast_loc_collisions.add(key)
new_ast_loc_nodes.add(key)
new_ast_loc_nodes[key] = str(node.get("id"))
# cluster-only and build_from_json rewrite a legacy semantic id to its
# canonical stem, then fold a bare doc id into its `_doc` twin. That id
# is the same node. A missing rationale id has no such successor.
@@ -136,19 +151,84 @@ def _lost_saved_semantic_nodes(
continue
if isinstance(node_id, str) and _renamed_present(node_id):
continue
if dedup_remap:
survivor = dedup_remap.get(node_id)
if isinstance(survivor, str) and _renamed_present(survivor):
continue
sf_val = node.get("source_file")
source = _norm_source_file(sf_val) if isinstance(sf_val, str) else None
lbl = str(node.get("label", "")).strip()
if source and lbl:
loc_key = (source, lbl)
if loc_key in new_ast_loc_nodes and loc_key not in ast_loc_collisions:
if (
not _has_independent_semantic_evidence(node)
and loc_key in new_ast_loc_nodes
and loc_key not in ast_loc_collisions
):
if folded is not None:
folded[str(node_id)] = new_ast_loc_nodes[loc_key]
continue
# Full-code rebuilds can relabel an AST file node with a path-qualified
# suffix when several files share a basename. The exact (source_file,
# label) key then disappears even though Pass 2 legitimately folded
# an evidence-free same-source file mention. Match by exact source
# identity, not bare filename, to avoid either silent data loss or a
# spurious fail-closed refusal on an unrelated identically named file.
if source and lbl and not _has_independent_semantic_evidence(node):
same_source_twins = {
nid for nid, sf in new_ast_file_nodes
if _norm_source_file(sf) == source
and _is_file_node_label(lbl, sf)
}
if len(same_source_twins) == 1:
if folded is not None:
folded[str(node_id)] = next(iter(same_source_twins))
continue
# Only a mention of SOME OTHER file is eligible for label-only
# folding. If the semantic node's label names its OWN source file,
# it is a file-self record; it must not fold into a different source's
# AST file just because the basename happens to match.
# Only an evidence-free mention is eligible for Pass 2b's label-only
# fold. Rich semantic records from unrelated source files are distinct
# provenance, even if their label happens to be a real file name.
# Mirror build_from_json exactly; otherwise the shrink guard would
# silently exempt a lost record that the builder no longer folds.
file_twins = (
[nid for nid, sf in new_ast_file_nodes if _is_file_node_label(lbl, sf)]
if (
lbl
and not _has_independent_semantic_evidence(node)
and not _is_file_node_label(lbl, source)
) else []
)
if len(file_twins) == 1:
if folded is not None:
folded[str(node_id)] = file_twins[0]
continue
if source and source in deleted:
continue
lost.append(node)
return lost
def _dedup_shrink_allowance(saved_ids: set, new_ids: set, dedup_remap: dict[str, str]) -> int:
"""How many fewer nodes the graph may have because dedup merged saved ids (#4940).
Merging N saved ids into one survivor removes N - 1 nodes when the survivor
is new this run, and N when it is itself a saved id (that one stays in the
count of the old graph). Only merges whose survivor is in the new graph
count: a missing survivor is a loss, not a merge.
"""
losers_by_survivor: dict[str, int] = {}
for loser, survivor in dedup_remap.items():
if loser in saved_ids and survivor in new_ids:
losers_by_survivor[survivor] = losers_by_survivor.get(survivor, 0) + 1
return sum(
count if survivor in saved_ids else count - 1
for survivor, count in losers_by_survivor.items()
)
# Relations that say only "these two symbols appear together", with no claim about
# HOW. An extractor that finds a specific fact for a pair — a call, an import, an
# inheritance — routinely emits one of these for the same pair as well, so when the
@@ -170,6 +250,66 @@ _GENERIC_RELATIONS: frozenset[str] = frozenset({"references", "uses", "mentions"
# `calls` is not ranked here.
_STRUCTURAL_MEMBER_RELATIONS: frozenset[str] = frozenset({"method", "contains"})
_CONFIDENCE_RANK: dict[str, int] = {"EXTRACTED": 3, "INFERRED": 2, "AMBIGUOUS": 1}
# The fields that say how sure the graph is of an edge and where that came from.
# A same-relation collision keeps one edge; the loser's copy of these fields is
# folded into the winner's `also_seen` list instead of being discarded (#4881).
_EVIDENCE_KEYS: tuple[str, ...] = ("confidence", "confidence_score", "source_file", "source_location")
def _evidence(attrs: dict) -> dict:
"""The provenance fields of one edge (or ``also_seen`` entry), scalars only."""
out: dict = {}
for key in _EVIDENCE_KEYS:
val = attrs.get(key)
if isinstance(val, bool) or val is None or val == "":
continue
if key == "confidence_score":
try:
val = float(val)
except (TypeError, ValueError):
continue
if not math.isfinite(val):
continue
elif not isinstance(val, (str, int, float)):
continue
out[key] = val
return out
def _evidence_sort_key(ev: dict) -> tuple:
# Weakest first: lowest confidence tier, then lowest score.
score = ev.get("confidence_score")
return (
_CONFIDENCE_RANK.get(str(ev.get("confidence", "")), 0),
score is None,
score if score is not None else 0.0,
str(ev.get("source_file", "")),
str(ev.get("source_location", "")),
)
def edge_evidence(d: dict) -> list[dict]:
"""Every provenance record an edge carries: its own, then each ``also_seen``."""
also = d.get("also_seen")
return [d, *(a for a in also if isinstance(a, dict))] if isinstance(also, list) else [d]
def _fold_also_seen(winner: dict, loser: dict) -> None:
"""Record ``loser``'s provenance on ``winner`` when the two collapse (#4881).
Entries that repeat the winner's own provenance, or each other, are dropped,
so re-feeding a written graph.json through the build is idempotent.
"""
own = _evidence(winner)
kept: list[dict] = []
for raw in (*edge_evidence(winner)[1:], loser, *edge_evidence(loser)[1:]):
ev = _evidence(raw)
if ev and not ev.items() <= own.items() and ev not in kept:
kept.append(ev)
if kept:
winner["also_seen"] = sorted(kept, key=_evidence_sort_key)
else:
winner.pop("also_seen", None)
# Import-family relations whose target may legitimately be a module OUTSIDE the
# graph (stdlib, a third-party dependency, another repo). Historically the edge
@@ -278,21 +418,90 @@ def finalize_raw_graph_endpoints(data: dict) -> None:
A stub is derived from the import edges that point at it, so a stub carried
over from an earlier graph that no edge references any more is dropped too;
a fresh build of the same tree would not have it.
Re-pointing an endpoint also needs the alias index, not just
normalization: a framework-style ``#import <Kit/ToolEvent.h>`` resolves to
a real header whose file node is ``kit_event_toolevent``, but the edge the
extractor emitted names the header by its bare basename (``toolevent``).
Normalization alone cannot bridge those two ids, so the raw path used to
mint an external stub for the import and leave the edge on it while the
clustered path re-pointed it at the real file (#4670). Resolving against the
shared alias index makes both write paths agree, and only a genuinely
external import (e.g. ``<Foundation/Foundation.h>``) is left to mint a stub.
"""
mint_external_stubs_in_data(data)
nodes = data.get("nodes")
key = "links" if isinstance(data.get("links"), list) else "edges"
links = data.get(key)
if not isinstance(nodes, list) or not isinstance(links, list):
return
# Match build_from_json's pre-validation alias folding before applying the
# raw-path persistence rules. An edge that still has no relation afterwards
# has no trustworthy semantic default and must not reach graph.json (#4809).
for edge in links:
if isinstance(edge, dict):
_fold_edge_aliases(edge)
declared = {n.get("id") for n in nodes if isinstance(n, dict)}
norm_to_id = {_normalize_id(nid): nid for nid in declared if isinstance(nid, str)}
node_by_id = {
n.get("id"): n for n in nodes
if isinstance(n, dict) and isinstance(n.get("id"), str)
}
# Alias index (#4670): the same old-stem spellings build_from_json resolves
# against, so an endpoint written in a pre-migration spelling still lands on
# the node it names. Only fills gaps — never overrides a real node id.
#
# Kept apart from norm_to_id, gated below, for the same reason
# build_from_json keeps it apart: the alias uniqueness check only
# protects against two same-stem files in one language, never a
# same-named node whose real identity is in another language (#4941).
alias_to_id = _alias_index(
(n.get("id"), n) for n in nodes
if isinstance(n, dict) and isinstance(n.get("id"), str)
)
# Re-point every endpoint that has a canonical form BEFORE stubbing, so an
# import that names a real file is not frozen onto a stub minted for its
# unresolved spelling. build_from_json resolves first and mints only for
# what is still missing; minting first is what left the raw path's import
# edges on a stub for a file that was in the corpus all along (#4670).
for e in links:
if not isinstance(e, dict):
continue
for primary, alias in (("source", "from"), ("target", "to")):
field = primary if primary in e else alias
endpoint = e.get(field)
if isinstance(endpoint, str) and endpoint in declared:
continue
if not isinstance(endpoint, str):
continue
norm = _normalize_id(endpoint)
canonical = norm_to_id.get(norm)
if canonical is None:
alias_target = alias_to_id.get(norm)
if alias_target is not None and _alias_lang_compatible(
e.get("source_file"),
(node_by_id.get(alias_target) or {}).get("source_file"),
):
canonical = alias_target
if canonical is not None:
e[field] = canonical
# Whatever still names an undeclared node is genuinely external: mint the
# typed stub for it so the on-disk graph.json has no undeclared endpoint
# (#2873), then drop the edges that still cannot attach to two declared
# nodes.
mint_external_stubs_in_data(data)
declared = {n.get("id") for n in nodes if isinstance(n, dict)}
kept: list = []
referenced: set = set()
dropped_schema_edges = 0
for e in links:
if not isinstance(e, dict):
kept.append(e)
continue
if "relation" not in e:
dropped_schema_edges += 1
continue
attached = True
for primary, alias in (("source", "from"), ("target", "to")):
field = primary if primary in e else alias
@@ -309,6 +518,12 @@ def finalize_raw_graph_endpoints(data: dict) -> None:
referenced.add(e.get("source", e.get("from")))
referenced.add(e.get("target", e.get("to")))
links[:] = kept
if dropped_schema_edges:
print(
f"[graphify] WARNING: dropped {dropped_schema_edges} schema-invalid edge(s) "
"missing required field 'relation'.",
file=sys.stderr,
)
for hyperedge in data.get("hyperedges", []) or []:
if isinstance(hyperedge, dict):
members = hyperedge.get("nodes", hyperedge.get("members", hyperedge.get("node_ids", [])))
@@ -468,7 +683,7 @@ def _fold_node_aliases(node: dict) -> None:
if not node.get("label") and isinstance(node.get("name"), str) and node["name"]:
node["label"] = node.pop("name")
if not node.get("source_file"):
for alias in ("file", "path", "filepath"):
for alias in ("file", "path", "filepath", "src"):
val = node.get(alias)
if isinstance(val, str) and val.strip():
node["source_file"] = node.pop(alias)
@@ -508,6 +723,10 @@ def _fold_confidence(obj: dict) -> None:
model-drifted string confidences re-warns on every command forever,
identically to the numeric gap above.
Structured JSON values (lists/objects) carry no usable confidence. They
fall back to ``INFERRED`` without inventing a numeric score, just like
an unrecognized nonnumeric string, before validation can hash them.
``confidence_score`` itself is NOT popped in either case: it is a
legitimate companion field the edge loop sanitizes and to_json
round-trips.
@@ -528,6 +747,8 @@ def _fold_confidence(obj: dict) -> None:
except ValueError:
pass
obj["confidence"] = "INFERRED"
elif isinstance(_conf, (list, dict)):
obj["confidence"] = "INFERRED"
if not obj.get("confidence") and obj.get("confidence_score") is not None:
obj["confidence"] = "INFERRED"
@@ -607,9 +828,13 @@ def _coerce_non_string_ids(extraction: dict) -> None:
for he in extraction.get("hyperedges") or ():
if not isinstance(he, dict):
continue
members = he.get("nodes")
if isinstance(members, list):
he["nodes"] = [_coerce_id(ref) for ref in members]
# The `members`/`node_ids` aliases (#1561) are coerced too, for the
# same reason as `from`/`to` above: they are folded onto `nodes` only
# later, by which time the node ids they name have already become str.
for key in ("nodes", *_HE_MEMBER_ALIASES):
members = he.get(key)
if isinstance(members, list):
he[key] = [_coerce_id(ref) for ref in members]
def _norm_source_file(p: str | None, root: str | None = None) -> str | None:
@@ -676,6 +901,25 @@ def _is_file_node_label(label: "str | None", source_file: "str | None") -> bool:
return "/" in lbl and (sf == lbl or sf.endswith("/" + lbl))
def _has_independent_semantic_evidence(node: dict) -> bool:
"""Do not label-fold a semantic record with evidence of its own.
A file mention can legitimately be folded into an AST file-self node,
but such a fold discards the semantic record's independent explanation
and attribution. Keep these records distinct unless the same-source
(source_file, label) twin rule already matched them.
Only genuine provenance counts. `metadata` and `captured_at` are attached
to ordinary INFERRED mention ghosts by extract.py, so treating them as
evidence would stop those ghosts folding and let duplicates proliferate
on real graphs (#4896).
"""
return any(
node.get(field) not in (None, "", [], {})
for field in ("rationale", "source_url", "author", "contributor")
)
def _shortest_unique_suffix(sf: str, all_sfs: "set[str]") -> str:
"""Shortest trailing path suffix (basename + k parent dirs) of *sf* that is
unique among *all_sfs*. `a/b/index.ts` vs `c/b/index.ts` -> `a/b/index.ts`;
@@ -735,6 +979,39 @@ def disambiguate_file_labels_in_nodes(nodes: "list") -> None:
nodes[i]["label"] = new_label
def _qualify_csharp_method_labels(G: "nx.Graph") -> None:
"""Give C# method nodes an ``Owner.Name()`` display label (#4883). Ids and
edges are never changed, and an undirected graph's owner side is read from
the edge's recorded ``_src``/``_tgt``. Idempotent."""
from graphify.extractors.csharp import csharp_method_label_reassignments
method_edges = [
(data.get("_src", u), data.get("_tgt", v))
for u, v, data in G.edges(data=True)
if data.get("relation") == "method"
]
for nid, new_label in csharp_method_label_reassignments(
G.nodes(data=True), method_edges
).items():
G.nodes[nid]["label"] = new_label
def qualify_csharp_method_labels_in_nodes(nodes: "list", edges: "list") -> None:
"""Raw node/edge-list form of :func:`_qualify_csharp_method_labels`, in
place, for the --no-cluster writers that bypass build_from_json (#4883)."""
from graphify.extractors.csharp import csharp_method_label_reassignments
method_edges = [
(e.get("source"), e.get("target"))
for e in edges
if isinstance(e, dict) and e.get("relation") == "method"
]
reassigned = csharp_method_label_reassignments(
((n.get("id"), n) for n in nodes if isinstance(n, dict)), method_edges
)
for n in nodes:
if isinstance(n, dict) and n.get("id") in reassigned:
n["label"] = reassigned[n["id"]]
def _infer_merge_root(graph_path: Path) -> str | None:
"""Best-effort scan root for relativizing paths in build_merge when the caller
passes no ``root`` (#1571).
@@ -966,6 +1243,106 @@ def _old_file_stems(rel: Path) -> list[str]:
return [f for f in forms if f and not (f in seen or seen.add(f))]
def _alias_index(nodes: "Iterable[tuple[str, dict]]") -> dict[str, str]:
"""Map every OLD-stem spelling of a node to that node's canonical id.
The pre-migration id recipe keyed a file's node on its stem, so a file at
``Kit/Event/ToolEvent.h`` used to be ``toolevent`` and is now
``kit_event_toolevent`` (#1504/#1509). An edge endpoint still written in the
old spelling must resolve to the migrated node instead of dangling, so each
node registers its old-stem forms as aliases.
An alias is committed only when EXACTLY ONE node claims it. The old-stem
form drops the extension and every directory but the immediate parent, so
"ping.h" and "ping.php" in different directories both alias to bare "ping";
committing an ambiguous alias would bind an edge to whichever same-stem file
happened to be seen first, merging unrelated files.
A Python module whose bare stem is a stdlib name (e.g. ``scripts/logging.py``)
must not claim the collapsed bare-stem alias ("logging"): that alias would
capture a genuine external ``import logging`` edge and bind it to this
same-named local file (#4261). The directory-scoped alias form
("scripts_logging") is still registered, so a real stale-id reference to this
file keeps healing.
Both the normalized and the raw spelling of every alias are registered, so
a caller can look an endpoint up with or without normalization.
Shared by :func:`build_from_json` and :func:`finalize_raw_graph_endpoints`
so the clustered and the raw (``--no-cluster``) write paths resolve an
endpoint the same way (#4670).
"""
from graphify.extractors.base import _file_stem as _fs
from graphify.extractors.csharp import bare_csharp_method_label
from graphify.extractors.resolution import _PYTHON_STDLIB_MODULE_NAMES
alias_candidates: dict[str, set[str]] = {}
for nid, attrs in nodes:
if not isinstance(nid, str) or not isinstance(attrs, dict):
continue
sf = attrs.get("source_file")
if not sf:
continue
rel = Path(str(sf))
if _is_abs(str(sf)):
continue
new_stem = make_id(_fs(rel))
if not new_stem:
continue
is_py_stdlib_stem = (
rel.suffix.lower() in (".py", ".pyi")
and make_id(rel.stem) in _PYTHON_STDLIB_MODULE_NAMES
)
if str(attrs.get("label", "")) == rel.name:
suffix = "" # this node IS the file, whatever its (possibly salted) id
else:
suffix = ""
if _normalize_id(nid).startswith(new_stem):
suffix = _normalize_id(nid)[len(new_stem):] # leading "_entity" or ""
for old_stem in _old_file_stems(rel):
if old_stem == new_stem:
continue
if is_py_stdlib_stem and old_stem in _PYTHON_STDLIB_MODULE_NAMES:
continue
alias = old_stem + suffix
alias_candidates.setdefault(_normalize_id(alias), set()).add(nid)
alias_candidates.setdefault(alias, set()).add(nid)
m_label = str(attrs.get("label", ""))
m_label = bare_csharp_method_label(m_label.strip(), sf) or m_label
if attrs.get("_origin") == "ast" and m_label.startswith("."):
m_name = make_id(m_label.strip().removeprefix(".").removesuffix("()"))
m_alias = f"{new_stem}_{m_name}"
if _normalize_id(nid) != _normalize_id(m_alias):
alias_candidates.setdefault(_normalize_id(m_alias), set()).add(nid)
alias_candidates.setdefault(m_alias, set()).add(nid)
return {
alias_key: next(iter(candidates))
for alias_key, candidates in alias_candidates.items()
if len(candidates) == 1
}
def _alias_lang_compatible(edge_source_file: object, alias_source_file: object) -> bool:
"""True unless the edge's own file and the alias target's file are both in
a KNOWN, DIFFERENT language family (#4941).
The uniqueness check in :func:`_alias_index` only protects against
ambiguity between same-stem files, never against a same-named node whose
real identity is in another language entirely: a Dart `PunchType` enum
reference and an unrelated `PunchType.java` file both collapse to the
bare old-stem alias "punchtype", and since only the Java file ever
registers it, the alias commits unconditionally and binds the Dart
reference onto the Java file. Permissive when either side's family is
unknown (no source_file, or an extension outside the known map), so a
legitimate same-language or provenance-less alias still resolves exactly
as before.
"""
from graphify.extract import _lang_family
edge_family = _lang_family(edge_source_file)
alias_family = _lang_family(alias_source_file)
return edge_family is None or alias_family is None or edge_family == alias_family
def _semantic_id_remap(nodes: list, root: str | None) -> dict:
"""Re-derive non-AST node ids from ``source_file`` using the canonical
full-path stem, so a cached/LLM fragment carrying a pre-migration short id
@@ -1063,7 +1440,37 @@ def _has_global_id(node: dict) -> bool:
return meta.get("mcp_kind") in _MCP_GLOBAL_ID_KINDS
def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: int = 300) -> bool:
def legacy_id_source_prefix(graph_path: str | Path) -> str | None:
"""The scan-root prefix that a graph's stored ``source_file`` values carry.
A build scoped to a subfolder from its parent (``graphify update sub``)
stores ``source_file`` relative to the build's cwd (``sub/pkg/mod.py``,
#2603) while every id is minted relative to the scan root (``pkg_mod``).
The relative ``.graphify_root`` marker next to the graph records exactly
that offset (``sub``). Returns it in normalized POSIX form, or None when
there is no offset: no marker, an absolute marker (the build anchored
source_file at the scan root itself), ``.``, or a path leaving the cwd.
"""
try:
text = (Path(graph_path).parent / ".graphify_root").read_text(
encoding="utf-8-sig"
).strip()
except (OSError, UnicodeError, ValueError):
return None
if not text:
return None
text = text.replace("\\", "/")
if _is_abs(text):
return None
import posixpath
prefix = posixpath.normpath(text)
if prefix in (".", "") or prefix == ".." or prefix.startswith("../"):
return None
return prefix
def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: int = 300,
source_prefix: str | None = None) -> bool:
"""Whether a loaded graph still uses pre-#1504 node IDs (parent-dir / filename
stem) rather than the full repo-relative path. Read-only consumers (query,
serve) use this to nudge the user to rebuild, since they don't re-extract.
@@ -1075,9 +1482,16 @@ def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: in
file-stem form and would otherwise false-positive. Nodes whose ID is global by
construction (see ``_MCP_GLOBAL_ID_KINDS``) are skipped for the same reason.
Returns True as soon as one file node's ID matches an OLD stem form but not the
canonical full-path form."""
canonical full-path form.
``source_prefix`` (see :func:`legacy_id_source_prefix`) is the cwd->scan-root
offset stored source_file values carry; it is stripped before the stem is
derived, since ids never include it. Without it a fresh subfolder build reads
as legacy: ``sub/pkg/mod.py`` wants ``sub_pkg_mod``, and the real ``pkg_mod``
looks exactly like the old one-parent form."""
from graphify.extractors.base import _file_stem
_r = str(root) if root is not None else None
_pfx = (source_prefix.replace("\\", "/").rstrip("/") + "/") if source_prefix else None
checked = 0
for node in nodes:
if not isinstance(node, dict):
@@ -1097,9 +1511,11 @@ def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: in
if not nid or not isinstance(nid, str) or not sf:
continue
sf_norm = _norm_source_file(str(sf), _r) or str(sf)
rel = Path(sf_norm)
if _is_abs(sf_norm):
continue
if _pfx and sf_norm.startswith(_pfx):
sf_norm = sf_norm[len(_pfx):]
rel = Path(sf_norm)
if not rel.name:
continue # source_file == scan root -> Path('.'), no file stem (#1618)
new_stem = make_id(_file_stem(rel))
@@ -1212,7 +1628,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
if node.get("file_type") in (None, ""):
node["file_type"] = "concept"
ft = node.get("file_type", "")
if ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
if not isinstance(ft, str):
node["file_type"] = "concept"
elif ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
node["file_type"] = _FILE_TYPE_SYNONYMS.get(ft, "concept")
# Canonicalize hyperedge member lists (#1561): producers sometimes key the
@@ -1359,6 +1777,7 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
_noloc_nodes: dict[tuple[str, str], str] = {} # (source_file, label) -> ghost node id
_ast_file_nodes: list[tuple[str, str]] = [] # (node_id, source_file) for AST file-self nodes (#3344)
_ast_method_nodes: dict[tuple[str, str], list[str]] = {} # (source_file, norm_method) -> [ast_nid, ...]
from graphify.extractors.csharp import bare_csharp_method_label
# Pass 1: collect canonical nodes — AST-origin nodes take precedence over LLM nodes.
# When 2+ AST nodes share a key (same-named symbols in same-named files across
@@ -1420,8 +1839,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
# a dotfile label like `.env` is never mistaken for a method
# (#3705 follow-up). Key on the normalized name for parity with
# the alias index below and the rest of the dedup passes.
if label.startswith(".") and label.endswith("()"):
m_name = make_id(label.removeprefix(".").removesuffix("()"))
m_label = bare_csharp_method_label(label, sf) or label
if m_label.startswith(".") and m_label.endswith("()"):
m_name = make_id(m_label.removeprefix(".").removesuffix("()"))
_ast_method_nodes.setdefault((sf, m_name), []).append(nid)
else:
# First non-AST node for this (file, label) wins as canonical; a
@@ -1445,6 +1865,11 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
if key in _loc_nodes and _loc_nodes[key] != nid:
if not dedup and G.nodes[_loc_nodes[key]].get("_origin") != "ast":
continue
# #4896: an independent semantic explanation is not a disposable
# AST twin even when it names the SAME physical source file.
# Preserve the original semantic id, rationale and source attribution.
if _has_independent_semantic_evidence(attrs):
continue
_noloc_nodes[key] = nid
elif key not in _loc_nodes:
# Spec-conformant method ghost omitting class segment / leading dot
@@ -1488,13 +1913,22 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
ast_id for ast_id, ast_sf in _ast_file_nodes
if _is_file_node_label(label, ast_sf)
}
if len(matches) == 1:
if (
len(matches) == 1
and not _has_independent_semantic_evidence(attrs)
and not _is_file_node_label(label, attrs.get("source_file"))
):
_ghost_remap[nid] = next(iter(matches))
# Remove ghost nodes from the graph; edges will be re-pointed via norm_to_id.
for ghost_id in _ghost_remap:
G.remove_node(ghost_id)
node_set.discard(ghost_id)
if _ghost_remap:
# These folds are intentional (#1145, #3344, #3705), so the write
# guards must not read them as lost nodes. Report them on the same
# {merged-away id: survivor id} channel entity dedup uses (#4940).
G.graph.setdefault("_dedup_remap", {}).update(_ghost_remap)
# Normalized ID map: lets edges survive when the LLM generates IDs with
# slightly different casing or punctuation than the AST extractor.
@@ -1533,55 +1967,35 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
# unrelated same-named PHP script) is still caught as ambiguous instead of
# the header silently dropping out of the race and leaving the PHP file as
# the lone (wrong) "unambiguous" winner.
from graphify.extractors.base import _file_stem as _fs
from graphify.extractors.resolution import _PYTHON_STDLIB_MODULE_NAMES
_alias_candidates: dict[str, set[str]] = {}
for nid in node_set:
attrs = G.nodes[nid]
sf = attrs.get("source_file")
if not sf:
continue
rel = Path(str(sf))
if _is_abs(str(sf)):
continue
new_stem = make_id(_fs(rel))
# A Python module whose bare stem is a stdlib name (e.g. `scripts/logging.py`)
# must not claim the collapsed bare-stem alias ("logging"): that alias would
# capture a genuine external `import logging` / `logging.getLogger()` edge
# and bind it to this same-named local file (#4261). The directory-scoped
# alias form ("scripts_logging") is still registered, so a real stale-id
# reference to this file keeps healing.
is_py_stdlib_stem = (
rel.suffix.lower() in (".py", ".pyi")
and make_id(rel.stem) in _PYTHON_STDLIB_MODULE_NAMES
)
if str(attrs.get("label", "")) == rel.name:
suffix = "" # this node IS the file, whatever its (possibly salted) id
else:
suffix = ""
if _normalize_id(nid).startswith(new_stem):
suffix = _normalize_id(nid)[len(new_stem):] # leading "_entity" or ""
for old_stem in _old_file_stems(rel):
if old_stem == new_stem:
continue
if is_py_stdlib_stem and old_stem in _PYTHON_STDLIB_MODULE_NAMES:
continue
alias = old_stem + suffix
_alias_candidates.setdefault(_normalize_id(alias), set()).add(nid)
_alias_candidates.setdefault(alias, set()).add(nid)
if attrs.get("_origin") == "ast" and str(attrs.get("label", "")).startswith("."):
m_name = make_id(str(attrs.get("label", "")).strip().removeprefix(".").removesuffix("()"))
m_alias = f"{new_stem}_{m_name}"
if _normalize_id(nid) != _normalize_id(m_alias):
_alias_candidates.setdefault(_normalize_id(m_alias), set()).add(nid)
_alias_candidates.setdefault(m_alias, set()).add(nid)
for alias_key, candidates in _alias_candidates.items():
if len(candidates) == 1:
norm_to_id.setdefault(alias_key, next(iter(candidates)))
#
# The index itself lives in _alias_index so the raw (--no-cluster) write
# path resolves endpoints identically (#4670).
#
# Kept apart from norm_to_id, not merged into it: the uniqueness check in
# _alias_index only protects against two same-stem files in the SAME
# language racing for one alias, never against a same-named node whose
# real identity is in another language (#4941). Gating the alias lookup
# itself, below, catches that case without touching the unconditional
# normalized-id and ghost-remap entries norm_to_id already carries.
alias_to_id = _alias_index((nid, G.nodes[nid]) for nid in node_set)
def _resolve_endpoint(raw_id: str, edge_source_file: object) -> str:
norm = _normalize_id(raw_id)
resolved = norm_to_id.get(norm)
if resolved is not None:
return resolved
alias_target = alias_to_id.get(norm)
if alias_target is not None and _alias_lang_compatible(
edge_source_file, G.nodes[alias_target].get("source_file")
):
return alias_target
return raw_id
# Iterate edges in a deterministic order. The graph is undirected and stores
# direction in _src/_tgt; when two edges collapse onto the same node pair the
# last write wins, so an unstable iteration order flips _src/_tgt run-to-run
# and makes the serialized graph churn. Sorting fixes the last-write outcome.
dropped_schema_edges = 0
for edge in sorted(
extraction.get("edges", []),
key=lambda e: (
@@ -1612,9 +2026,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
continue
# Remap mismatched IDs via normalization before dropping the edge.
if src not in node_set:
src = norm_to_id.get(_normalize_id(src), src)
src = _resolve_endpoint(src, edge.get("source_file"))
if tgt not in node_set:
tgt = norm_to_id.get(_normalize_id(tgt), tgt)
tgt = _resolve_endpoint(tgt, edge.get("source_file"))
if src not in node_set or tgt not in node_set:
# An import/re-export whose target is not a declared node points at
# an external module (stdlib / third-party / another repo). Mint a
@@ -1663,6 +2077,8 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
if not math.isfinite(_num_val) or _num_val < 0:
_num_val = 1.0
attrs[_num_key] = _num_val
if "also_seen" in attrs:
_fold_also_seen(attrs, {})
# Backfill source_file from the endpoint nodes (every node carries one).
# Semantic/LLM edges occasionally omit it, which downstream validation
# flags and leaves query results with no file reference (#1279).
@@ -1674,6 +2090,13 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
)
if "source_file" in attrs:
attrs["source_file"] = _norm_source_file(attrs["source_file"], _root)
# Relation aliases are folded before validation, but a still-missing
# relation has no trustworthy default. Other historically tolerated edge
# gaps have repair/default paths elsewhere in this builder; relation does
# not. Fail closed rather than persist an uninterpretable edge (#4809).
if "relation" not in attrs:
dropped_schema_edges += 1
continue
if attrs.get("definition_file"):
# Same portability rule as source_file (#3223); heals a graph
# written before the fix on its next rebuild.
@@ -1744,6 +2167,15 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
incoming_rel = attrs.get("relation")
reverse = existing.get("_src") == tgt and existing.get("_tgt") == src
if reverse and existing_rel == incoming_rel:
# For an import the dropped leg is the other half of a two-file
# cycle. Stamp the kept edge so find_import_cycles still sees it
# (#4839); a type-only or deferred import closes no cycle.
if (
incoming_rel in ("imports_from", "re_exports")
and not attrs.get("type_only")
and not attrs.get("deferred")
):
existing["reverse_import"] = True
continue
# Different relations in opposite directions are two facts that only
# share a pair because the graph is undirected. A type's
@@ -1784,9 +2216,11 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
existing_rank = _CONFIDENCE_RANK.get(existing_conf, 0)
incoming_rank = _CONFIDENCE_RANK.get(incoming_conf, 0)
if existing_rank > incoming_rank:
_fold_also_seen(existing_attrs, attrs)
continue
if existing_rank == incoming_rank:
if existing_attrs.get("source_location") and not attrs.get("source_location"):
_fold_also_seen(existing_attrs, attrs)
continue
existing_score = existing_attrs.get("confidence_score")
incoming_score = attrs.get("confidence_score")
@@ -1795,8 +2229,21 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
and incoming_score is not None
and existing_score > incoming_score
):
_fold_also_seen(existing_attrs, attrs)
continue
_fold_also_seen(attrs, existing_attrs)
# add_edge merges into the stored dict: a field only the loser
# carried (its score, its line) would otherwise stay on the winner.
for _key in (*_EVIDENCE_KEYS, "also_seen"):
if _key not in attrs:
existing_attrs.pop(_key, None)
G.add_edge(src, tgt, **attrs)
if dropped_schema_edges:
print(
f"[graphify] WARNING: dropped {dropped_schema_edges} schema-invalid edge(s) "
"missing required field 'relation'.",
file=sys.stderr,
)
hyperedges = extraction.get("hyperedges", [])
if hyperedges:
# Relativize hyperedge source_file the same way nodes and edges are
@@ -1857,6 +2304,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
# directory-qualified display label so lookup/discovery can disambiguate
# them (#2032). Labels only — ids and edges are untouched.
_disambiguate_file_node_labels(G)
# Also last, after the method-ghost passes above: C# methods display with
# their owning type (#4883).
_qualify_csharp_method_labels(G)
return G
@@ -1896,6 +2346,7 @@ def build(
combined["output_tokens"] += ext.get("output_tokens", 0)
_root = str(Path(root).resolve()) if root else None
_dedup_collapsed = 0
_dedup_remap: dict[str, str] = {}
if dedup and combined["nodes"]:
# Numeric ids must be str before dedup, which keys on them and would
# raise TypeError in _pick_winner's regex search (#2326). build_from_json
@@ -1925,6 +2376,7 @@ def build(
# survivor rewiring the edges get (#2805).
hyperedges=combined.get("hyperedges"),
protected_ids=protected_ids,
remap_out=_dedup_remap,
)
_dedup_collapsed = _before_dedup - len(combined["nodes"])
G = build_from_json(combined, directed=directed, root=_root, dedup=dedup)
@@ -1932,6 +2384,10 @@ def build(
# Popped before to_json so it is not stored in graph.json.
if _dedup_collapsed:
G.graph["_dedup_collapsed"] = _dedup_collapsed
# Which ids dedup folded into which survivor, for the #479 write guard
# (#4940). Popped by to_json, so it is not stored in graph.json.
if _dedup_remap:
G.graph.setdefault("_dedup_remap", {}).update(_dedup_remap)
return G
@@ -1950,6 +2406,20 @@ def take_shrink_accounting(G) -> tuple[int, int]:
return collapsed, pruned
def take_dedup_remap(G) -> dict[str, str]:
"""Read and remove the ``{merged-away id: survivor id}`` map (#4940).
``build`` stashes it on ``G.graph`` when entity dedup merged nodes.
``to_json`` calls this to excuse a saved id the merge folded into a twin,
and it also drops the key so it is never persisted into graph.json.
"""
attrs = getattr(G, "graph", None)
if not isinstance(attrs, dict):
return {}
remap = attrs.pop("_dedup_remap", None)
return dict(remap) if isinstance(remap, dict) else {}
def _norm_label(label: str | None) -> str:
"""Canonical dedup key — Unicode-aware, preserves CJK/word characters."""
if not isinstance(label, str):
@@ -2014,7 +2484,8 @@ def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dic
def _load_existing_graph(graph_path: Path) -> "tuple[list, list, list, bool] | None":
"""Load (nodes, edges, hyperedges, directed) from an existing graph.json for
an incremental merge, accepting both the ``links`` and ``edges`` spellings.
an incremental merge, accepting both the ``links`` and ``edges`` spellings
and either hyperedge persistence slot (top-level or ``graph.hyperedges``).
Reads the JSON directly instead of going through node_link_graph().
The latter rebuilds an undirected nx.Graph and then enumerating
@@ -2042,6 +2513,26 @@ def _load_existing_graph(graph_path: Path) -> "tuple[list, list, list, bool] | N
links_key = "links" if "links" in data else "edges"
nodes = list(data.get("nodes", []))
edges = list(data.get(links_key, []))
# Hyperedge persistence is dual-slot (#2485): to_json writes BOTH a
# top-level `hyperedges` key and the nested `graph.hyperedges` (node_link
# graph attrs), but node_link_data-only writers emit just the nested slot.
# build_from_json already folds the nested slot onto the top-level key;
# this loader must do the same or an incremental merge silently drops a
# nested-only graph's whole hyperedge set — the data loss #5081 reported,
# still reachable through that writer shape.
#
# A top-level LIST wins: it is the canonical slot, so an explicit [] there
# must not be resurrected from a stale nested copy (the CLI's source pruner
# also edits only the top-level key). A missing, null, or otherwise
# malformed top-level value falls back to the nested list instead of
# dropping a set that is still readable.
top_level = data.get("hyperedges")
if isinstance(top_level, list):
hyperedges = top_level
else:
graph_attrs = data.get("graph")
nested = graph_attrs.get("hyperedges") if isinstance(graph_attrs, dict) else None
hyperedges = nested if isinstance(nested, list) else []
# Backfill tier provenance on legacy items (#2334): _origin is stamped at
# extraction time only (extract.py for AST, and the semantic path never
# stamps), so pre-0.9.16 graphs and externally-merged fragments carry
@@ -2054,7 +2545,7 @@ def _load_existing_graph(graph_path: Path) -> "tuple[list, list, list, bool] | N
return (
nodes,
edges,
list(data.get("hyperedges", [])),
hyperedges,
bool(data.get("directed", False)),
)
@@ -2635,6 +3126,28 @@ def build_merge(
if edges_to_remove:
G.remove_edges_from(edges_to_remove)
# build() revalidated hyperedge members BEFORE this prune removed the
# deleted files' nodes, so a surviving cross-file hyperedge can still
# name one of them (#5081). Now that the node set is final, mirror
# build()'s #1916 policy: drop members that no longer resolve, and drop
# the hyperedge itself only when no member remains (single-member
# hyperedges are legal).
if G.graph.get("hyperedges"):
_pruned_hyperedges = []
for he in G.graph["hyperedges"]:
if not isinstance(he, dict):
_pruned_hyperedges.append(he)
continue
members = he.get("nodes")
if isinstance(members, list):
live = [m for m in members if _hashable(m) and m in G]
if not live:
continue
if live != members:
he["nodes"] = live
_pruned_hyperedges.append(he)
G.graph["hyperedges"] = _pruned_hyperedges
orphaned = _sweep_orphans()
n_nodes += len(orphaned)
# Excuse only saved nodes this prune removed (#3774). A stub minted
@@ -2728,12 +3241,20 @@ def build_merge(
# guard (#1951), and refusing it here would reintroduce the #1116
# false-refuse for legitimate edits that remove symbols from a file.
if had_graph and not dedup:
# Ghost folds build_from_json made on purpose (#1145, #3344, #3705).
# Read, not popped: to_json reads the same map and strips it.
_folds = G.graph.get("_dedup_remap") or {}
def _in_new_graph(n: dict) -> bool:
nid = n.get("id")
if nid is None or not _hashable(nid):
return True # untrackable identity — never count as lost
if nid in G:
return True
# A fold into a survivor still in the graph is one node, not a
# loss; a survivor that is gone excuses nothing (#4955).
if _folds.get(nid) in G:
return True
# Doc-twin heal (#1799): build_from_json merges a markdown
# quick-scan's bare doc node into its semantic `<id>_doc` twin for
# the same file — a legitimate collapse, not a loss.
@@ -2772,6 +3293,24 @@ def build_merge(
if unverified_semantic_shrink:
G.graph["_unverified_semantic_shrink"] = unverified_semantic_shrink
# Saved sources whose semantic nodes this run replaced or pruned on purpose,
# for to_json's lost-node check: LLM ids are not stable across re-extracts.
# A source with an unverified shrink (#3203) stays guarded. Popped by to_json.
def _replaced_on_purpose(sf: str) -> bool:
norm = _norm_source_file(sf, _replace_root) or sf
if norm in unverified_semantic_shrink:
return False
return sf in new_sem_sources or norm in new_sem_sources or _prune_match(sf)
_replaced_sources = {
n["source_file"] for n in _disk_nodes
if isinstance(n, dict) and not _is_ast_tier(n)
and isinstance(n.get("source_file"), str) and n["source_file"]
and _replaced_on_purpose(n["source_file"])
}
if _replaced_sources:
G.graph["_replaced_sources"] = sorted(_replaced_sources)
return G
+149 -30
View File
@@ -17,6 +17,7 @@ from pathlib import Path
# absolute path ("/shared/graphify-out"). Single source of truth in graphify.paths
# (#1423); re-exported here as _GRAPHIFY_OUT for the existing call sites.
from graphify.paths import GRAPHIFY_OUT as _GRAPHIFY_OUT
from graphify.paths import os_long_path as _os_long_path
from graphify.paths import os_replace_with_fallback as _os_replace_with_fallback
# AST cache entries are the output of graphify's own extractor code, so they
@@ -37,7 +38,7 @@ except Exception:
_EXTRACTOR_VERSION = "unknown"
# Bump when AST cache-key semantics change independently of the package version.
_AST_CACHE_SCHEMA = 20 # Obsidian `[[wikilink]]` targets that start with the scan root's own folder names now resolve to the real page (#4559), so cached markdown extractions re-run; prior (19): Dart `typedef` declarations are extracted as aliases (not variables of type `typedef`); C++ Metal/CUDA GPU qualifiers no longer mint sourceless god nodes (#4550); a `.h` header containing `extern "C"` routes to the C++ extractor; prior (18): Kotlin `typealias` (#4553), C# `delegate` (#4552), and Swift `macro` declarations (#4551) are now extracted so references stop minting sourceless stubs; Rust `use` rooted at a `mod` declared in the same scope carries `_rust_use_name` (#4564); prior (17): Python pytest-fixture markers (`_py_fixture`/`_python_fixture_param`, #4332) and module-level class-id collision salting (#2810); TS `this.field` typed from any method incl. static (#4473); Solidity callables carry `metadata.arity` + inherited-call/`super`/modifier raw calls (#4379); Go type-decl and Rust file-item case-distinct node ids (#4444); prior (16): Rust `use` edges carry the imported name as written (`_rust_use_name`, #4439); (15): Go generic receiver types normalized (`Box[T]` -> `Box`) so methods attach to the type node; prior (14): C# receiver resolution for nameless/`new X()`/`foreach` receivers (defer + receiver-chain markers) and `_`/case-distinct node ids (underscore-salted); prior (13): Kotlin/Scala/C++/Swift generic & template type params no longer mint sourceless stubs; Objective-C NS_ENUM/NS_OPTIONS extraction and `_callable`/`_callable_class` markers; Go and PHP receiver-typed member calls park cross-repo (`go_type_table`/`php_type_table`, receiver fields); prior (12): Java inherited-supertype (`receiver_unbound`) and chained/new/cast receiver typing (`java_receiver_chain`, `_java_ret`); C/C++ quoted cross-directory include provenance (`include_kind`); JS external imports anchored to the package, not the path leaf; prior (11): Python property-accessor decorators / `Self`, Swift `Self`, Go generic type params, Python forward type-hint file node, PowerShell dot-source, C# verbatim-interpolated string recovery; (10): C# partial types carry `type_path`; (9): Python property-read raw calls and `_py_property` nodes; (8): Rust `use`-group per-binding edges; (7): Python opaque-base/super(args) markers + nested-class enclosing ids.
_AST_CACHE_SCHEMA = 42 # A bare, unqualified free-function mention in a Markdown document (`token` in prose, no `()` and no namespace) binds to a same-named function only when the defining file, or another symbol from it, is cited within the heading's section chain, instead of matching any same-named callable anywhere in the corpus; reference-style links (`[text][label]`) resolve at the use site (#4804, #4806); and a C# classic extension-method call (`x.Foo()` where `Foo` is a `static ... Foo(this X x, ...)`) binds to the extension's declaration through a post-nominal additive pass, gated to a visible namespace, a matching `this` type and a unique applicable method, with a BCL deny-list and fail-closed on ambiguity or an instance-method shadow (#4828); so cached Markdown and C# extractions re-run; prior (41): A C++ member-call chain routed through class fields declared in other headers (`client.actions->Execute()`, with value `.`, raw-pointer `->` and single-arg `unique_ptr`/`shared_ptr` receivers) resolves to the field type's member across the include set, gated to a unique type and member and fail-closed otherwise, and class fields are persisted on the node (#5098); and a Markdown code span naming an uppercase `\`-namespace class (`\Foo\Bar`, `App\API`) or a type-qualified method call (`Type::member()`) is kept as a symbol mention instead of being dropped, while a non-call `Type::CONST`/`Type::class` stays dropped (#5093); so cached C++ and Markdown extractions re-run; prior (40): Solidity members, free functions and types whose names differ only by a leading `_` (or by case) in one scope (`_grantRole(bytes32,address)` / `grantRole(bytes32,address)`) get separate node ids: the one public name keeps its id and the others are salted, as in Python and C# (#3302, #4415), so the `_` function no longer vanishes and its calls stop landing on its twin (#5027); a Solidity call on a receiver of a contract or interface type (`IERC20 token; token.transfer()`, `IERC20(a).transfer()`, `token().balanceOf()`) binds by name and arity through that type's linearization to the type's own member instead of producing no edge, gated to a single visible contract/interface and fail-closed on an unknown or ambiguous type (#5060); a Solidity call attached by a `using A for T` directive (`using SafeCast for uint256; x.toUint48()`) binds to the library or free function it attaches, matched by the receiver's type and an arity one greater than the call (the receiver), fail-closed when the type is unknown or two functions fit (#5062); a C# constructor (instance, static or primary) is its own node owned by its type through a `method` edge, its body and `: base(...)`/`: this(...)` calls credited to it, and `new X(...)`/`: base`/`: this` additively link the arity-correct overload (#5054); and a C# call inside a property/indexer accessor, expression body, operator or conversion is credited to that member (an indexer is a `this[]` node, an operator a `.operator +()` node) instead of being lost (#5056), so cached Solidity and C# extractions re-run; prior (39): A Markdown code span written as a backslash namespace (`\Foo\Bar`) or a type-qualified member (`Type::member`) is recognised as a symbol mention and emits a `ns_qualified` raw_call (#4610, #4695), so cached Markdown extractions re-run; prior (38): C# preprocessor directives and `#if` branches that would derail tree-sitter-c-sharp are blanked before parsing (byte-length preserving, so lines and columns do not move), so a directive no longer closes the enclosing class early and drops later members or calls (#5003); a Solidity library call (`Lib.f()`, including an aliased import), and an `emit`/`revert`/`require` naming a declared event or error, link to the member they name instead of producing no edge, resolved only when a single visible type and a unique name/arity member match (#5001, #5005); and a YAML `<<` merge sequence gives the earlier anchor precedence for a duplicated key, matching the merge spec and PyYAML, so the winning key carries its correct source line (#4995); so cached C#, Solidity and YAML extractions re-run; prior (37): Solidity `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling stub that kept the importer's own folder (#4985); a Python module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard (#4972); Kotlin resolves a call to an overloaded method and attributes calls inside an `init {}` block to the class, and a bare call no longer binds to a class the caller cannot reach (#4935, #4956); a Go same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method (#4962, #4966); a Go member call on a receiver typed from another package (`pkg.T`) binds only to the `T` declared at the path the file imports `pkg` from (#3368, #4853); and a Go interface method call additively dispatches to Line truncated
# Per-process memo: distributions() scans site-packages metadata, which is
@@ -410,7 +411,10 @@ def _ensure_stat_index(root: Path, cache_root: "Path | None" = None) -> None:
# relative so a moved/cloned corpus still hits (#2199) — same load/save
# re-anchoring the detect manifest uses.
_stat_index_root = new_root
_stat_index_anchor = Path(root).resolve()
# Spell the anchor like the in-memory keys (_normalize_path): callers pass an
# os_long_path() root, and on Windows relpath() cannot relate "\\?\C:\..." to
# "C:\...", so every key stayed absolute and a moved corpus missed (#5035).
_stat_index_anchor = _normalize_path(Path(root).resolve())
p = _stat_index_file(_stat_index_root)
_stat_index_path = p
_stat_index = {}
@@ -498,14 +502,22 @@ def _flush_stat_index() -> None:
def _normalize_path(path: Path) -> Path:
"""Normalize path for consistent cache keys across Windows path spellings."""
"""Normalize a path for cache identity without folding case.
Windows spellings can differ in separators and in the optional
extended-length prefix. Case is not equivalent on every volume a Windows
process can reach, so the key keeps the caller's case. Use
paths.os_long_path() for the path handed to the filesystem.
"""
import sys
if sys.platform != "win32":
return path
s = str(path)
if s.startswith("\\\\?\\"):
if s.startswith("\\\\?\\UNC\\"):
s = "\\\\" + s[8:] # \\?\UNC\server\share -> \\server\share
elif s.startswith("\\\\?\\"):
s = s[4:] # strip extended-length prefix \\?\
return Path(os.path.normcase(s))
return Path(os.path.normpath(s))
def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = None) -> str:
@@ -524,19 +536,30 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
The path handed to the filesystem comes from os_long_path(); the cache key
preserves case because case sensitivity belongs to the volume, not the
platform (#4925).
"""
global _stat_index_dirty
p = _normalize_path(Path(path))
root = _normalize_path(Path(root))
if not p.is_file():
raise IsADirectoryError(f"file_hash requires a file, got: {p}")
raw_path = Path(path)
raw_root = Path(root)
src = Path(_os_long_path(raw_path))
root_src = Path(_os_long_path(raw_root))
if not src.is_file():
raise IsADirectoryError(f"file_hash requires a file, got: {src}")
# The stat index is a cache artifact, so it must follow the cache location
# (cache_root), not the key-anchor root — otherwise it leaves a stray
# graphify-out/cache/stat-index.json inside the analyzed source tree even when
# the AST cache itself is redirected to CWD (#1774 completion).
_ensure_stat_index(root, cache_root=cache_root)
resolved = p.resolve()
#
# The index root, key and salt use the normalized spelling. The \\?\ form
# from os_long_path() is for I/O only: as the root it made load_cached()'s
# plain cache_root look like a second root (#3989), and no key was relative
# to it, so every key was written absolute (#2199).
_ensure_stat_index(_normalize_path(raw_root), cache_root=cache_root)
resolved = _normalize_path(src.resolve())
abs_key = str(resolved)
# The salt is the path component that enters the digest (relative to root, or
# the absolute-path fallback). The stat-index memo MUST be keyed by it too:
@@ -545,17 +568,17 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
# path served whichever was computed first — making file_hash order-dependent
# and poisoning the persisted stat-index across runs (#1989). Store one digest
# per salt so alternating roots don't force re-reads.
resolved_root = root.resolve()
resolved_root = _normalize_path(root_src.resolve())
try:
resolved_rel = resolved.relative_to(resolved_root)
except ValueError:
# Preserve the existing fallback for a target outside the corpus. An
# in-root symlink to such a target is excluded by collect_files(), but
# direct cache callers still rely on the resolved external identity.
salt = resolved.as_posix().lower()
salt = resolved.as_posix()
else:
walked = Path(os.path.abspath(p))
walked_root = Path(os.path.abspath(root))
walked = Path(os.path.abspath(raw_path))
walked_root = Path(os.path.abspath(raw_root))
try:
walked_rel = walked.relative_to(walked_root)
except ValueError:
@@ -566,18 +589,18 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
walked_rel = None
for parent in walked.parents:
try:
if parent.resolve() == resolved_root:
if _normalize_path(parent.resolve()) == resolved_root:
walked_rel = walked.relative_to(parent)
break
except OSError:
continue
if walked_rel is None:
walked_rel = resolved_rel
salt = walked_rel.as_posix().lower()
salt = walked_rel.as_posix()
st: "os.stat_result | None" = None
try:
st = p.stat()
st = src.stat()
if _stat_sig_fresh(_stat_index.get(abs_key), st):
hashes = _stat_index[abs_key].get("hashes")
if isinstance(hashes, dict):
@@ -592,8 +615,8 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
# Captured BEFORE the read so the stamp can never post-date content that
# changed while we were reading it (see _stat_sig_fresh).
observed_at_ns = time.time_ns()
raw = p.read_bytes()
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
raw = src.read_bytes()
content = _body_content(raw) if src.suffix.lower() == ".md" else raw
h = hashlib.sha256()
h.update(content)
h.update(b"\x00")
@@ -627,13 +650,14 @@ def cached_word_count(path: Path, root: Path, compute, cache_root: "Path | None"
correct, just not accelerated.
"""
global _stat_index_dirty
p = _normalize_path(Path(path))
root = _normalize_path(Path(root))
_ensure_stat_index(root, cache_root=cache_root)
abs_key = str(p.resolve())
raw_path = Path(path)
raw_root = Path(root)
src = Path(_os_long_path(raw_path))
_ensure_stat_index(_normalize_path(raw_root), cache_root=cache_root)
abs_key = str(_normalize_path(src.resolve()))
st: "os.stat_result | None" = None
try:
st = p.stat()
st = src.stat()
entry = _stat_index.get(abs_key)
if _stat_sig_fresh(entry, st) and "word_count" in entry:
return entry["word_count"]
@@ -643,7 +667,7 @@ def cached_word_count(path: Path, root: Path, compute, cache_root: "Path | None"
# Captured BEFORE compute() reads the file, for the same reason file_hash
# stamps before its read (see _stat_sig_fresh).
observed_at_ns = time.time_ns()
wc = compute(Path(path))
wc = compute(raw_path)
if st is not None:
_stat_entry_for(abs_key, st, observed_at_ns)["word_count"] = wc
@@ -1099,10 +1123,11 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast",
return None
h = _salted_key(h, salt)
prompt_fp = _resolve_prompt_fp(prompt, prompt_file)
entry = cache_dir(location, kind, prompt_fp) / f"{h}.json"
# Extended-length form so a deep root does not push the entry past MAX_PATH.
entry = Path(_os_long_path(cache_dir(location, kind, prompt_fp) / f"{h}.json"))
legacy_hit = False
if prompt_fp and not entry.exists() and allow_legacy:
legacy = cache_dir(location, kind) / f"{h}.json"
legacy = Path(_os_long_path(cache_dir(location, kind) / f"{h}.json"))
if legacy.exists():
entry, legacy_hit = legacy, True
if entry.exists():
@@ -1263,8 +1288,10 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
_relativize_ids_in(on_disk, p, root)
h = _salted_key(file_hash(p, root, cache_root=cache_root), salt)
location = cache_root if cache_root is not None else root
target_dir = cache_dir(location, kind, _resolve_prompt_fp(prompt, prompt_file))
entry = target_dir / f"{h}.json"
# Extended-length form: under a deep root the entry, and its longer temp
# name, overrun Windows MAX_PATH and the write fails the whole extraction.
target_dir = _os_long_path(cache_dir(location, kind, _resolve_prompt_fp(prompt, prompt_file)))
entry = os.path.join(target_dir, f"{h}.json")
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
try:
os.write(fd, json.dumps(on_disk).encode())
@@ -1822,6 +1849,98 @@ def save_semantic_cache(
return saved
def mark_semantic_cache_partial(
files: Iterable[str | Path],
root: Path = Path("."),
*,
mode: str | None = None,
prompt: "str | Path | None" = None,
prompt_file: "str | Path | None" = None,
cache_root: "Path | None" = None,
) -> list[Path]:
"""Stamp the serving semantic cache entry for each file ``partial: True``.
The semantic cache is deliberately unversioned and content-hash keyed, so a
degraded extraction — e.g. a document chunk that returned only its
file-level node — is otherwise replayed as authoritative on every later
run. The #3203 shrink guard keeps refusing the graph write while the cache
keeps suppressing the LLM call that could heal it, so the corpus is stuck
until an operator deletes the entry by hand (#5083).
The guard compares against graph.json, which :func:`save_semantic_cache`
deliberately does not read (the cache writer does not know the graph), so
the CLI marks the entry after the fact instead. ``load_cached`` already
treats ``partial`` as a miss: the next run re-dispatches the file and a
complete extraction overwrites the same content-hash key with a clean
entry, which is the self-healing path the ``_partial`` truncation flag
already uses.
Marks the entry the read path would actually serve — the
prompt-fingerprint namespace when it exists, else the pre-fingerprint flat
layout ``load_cached`` falls back to — so a legacy entry cannot keep
shadowing the marked one.
``files`` may be absolute, or relative to ``root`` (the shape of the shrink
guard's canonical ``source_file`` keys). Returns the entry paths actually
marked. Best-effort: a missing, unreadable or already-partial entry is
skipped rather than failing the extraction.
"""
kind = "semantic" if mode is None else f"semantic-{mode}"
location = cache_root if cache_root is not None else root
prompt_fp = _resolve_prompt_fp(prompt, prompt_file)
marked: list[Path] = []
for value in files:
p = Path(value)
if not p.is_absolute():
p = Path(root) / p
try:
h = file_hash(p, root, cache_root=cache_root)
except (OSError, ValueError):
continue
candidates: list[Path] = []
if prompt_fp:
candidates.append(cache_dir(location, kind, prompt_fp) / f"{h}.json")
candidates.append(cache_dir(location, kind) / f"{h}.json")
entry = next(
(c for c in candidates if c.exists()), None
)
if entry is None:
continue
# Extended-length form for I/O only: under a deep root the entry path
# overruns Windows MAX_PATH. Report the logical path to callers.
io_entry = Path(_os_long_path(entry))
try:
payload = json.loads(io_entry.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
continue
if not isinstance(payload, dict) or payload.get("partial"):
continue
payload["partial"] = True
# Match save_cached's I/O: the temp file and the replace dest both use
# the extended-length form so a deep root cannot fail the write.
fd, tmp_path = tempfile.mkstemp(
dir=str(Path(_os_long_path(entry.parent))),
prefix=f"{entry.stem}.",
suffix=".tmp",
)
try:
os.write(fd, json.dumps(payload).encode())
os.close(fd)
_os_replace_with_fallback(tmp_path, io_entry)
except Exception:
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(tmp_path)
except OSError:
pass
continue
marked.append(entry)
return marked
def scope_semantic_result(
result: dict,
root: Path = Path("."),
+24
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any
@@ -26,6 +27,29 @@ def _load_toml(path: Path) -> dict[str, Any]:
return tomllib.load(manifest)
def package_name(manifest: Path) -> str | None:
"""A Cargo.toml's `[package] name` as Rust spells it in a path (`-` -> `_`).
Returns None when the manifest has no package name, cannot be read, or
cannot be parsed. Callers that scope a Rust import to a crate treat "no
name" as "no crate", never as an error, so this stays silent.
"""
try:
package = _load_toml(manifest).get("package")
except (OSError, ValueError):
return None
except ImportError: # Python 3.10 without tomli: recover the one key we need
try:
text = manifest.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
match = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', text, re.M | re.S)
name = match.group(1) if match else None
else:
name = package.get("name") if isinstance(package, dict) else None
return name.replace("-", "_") if isinstance(name, str) and name else None
def _discover_root_manifest(root: Path) -> Path | None:
"""Find a Cargo.toml under *root* when none sits directly at the root.
+847 -135
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -138,6 +138,7 @@ def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
)
for src, tgt, attrs in edge_rows:
stable.add_edge(src, tgt, **attrs)
del edge_rows # `stable` holds the edges now
native_result = _native_leiden(stable, resolution)
if native_result is not None:
+77 -25
View File
@@ -14,7 +14,10 @@ The resolvers now park those calls on the caller node as
``_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.
single-repo resolvers use: an ambiguous name still fabricates nothing. An ObjC
class split ``@interface``(.h)/``@implementation``(.m) across repos is the one
exception — several same-named candidates bind to the sole one that DEFINES the
selector (#1556), two definitions still being an ambiguity.
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
@@ -59,6 +62,11 @@ _LANG_SUFFIXES: dict[str, frozenset[str]] = {
# carries `defines` instead. `method` wins when both name the same member.
_MEMBER_RELATIONS = ("defines", "method")
# An ObjC @implementation lives in a `.m`/`.mm`; a `.h` carries only the @interface
# declaration. This is what tells the one DEFINITION apart from the declarations when
# a class is split across repositories.
_OBJC_IMPL_SUFFIXES = frozenset({".m", ".mm"})
def _key(label: object) -> str:
"""Normalize a node label or a parked name to its bare identifier.
@@ -172,6 +180,34 @@ def _member_keys(lang: str, callee: str) -> tuple[str, ...]:
return (callee,)
def _objc_union_definition(
merged: "nx.Graph",
members: dict[tuple[str, str], list[str]],
candidates: list[str],
callee: str,
) -> str | None:
"""The sole DEFINITION of an ObjC selector across same-named candidates.
An ObjC class whose `@interface` (`.h`) and `@implementation` (`.m`) live in
different repositories surfaces as several same-named candidates that
``_merge_decl_def_classes`` folds within a repo but cannot across the boundary
(its id embeds the directory, #1556). The candidate that DEFINES the selector —
an impl in `.m`/`.mm`, or a folded node naming its impl in ``definition_file`` —
is the target; a bare header declaration is not. Two candidates that both define
it are two unrelated classes and stay ambiguous, so the single-definition guard
still holds for the collision it was meant to catch.
"""
defs: list[str] = []
for cand in candidates:
for member_key in _member_keys("objc", callee):
for member in members.get((cand, member_key), []):
data = merged.nodes[member]
if data.get("definition_file") or _suffix(data.get("source_file")) in _OBJC_IMPL_SUFFIXES:
defs.append(member)
defs = list(dict.fromkeys(defs))
return defs[0] if len(defs) == 1 else None
def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
"""Emit `calls` edges for parked member calls another repo answers.
@@ -228,31 +264,42 @@ def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
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.
if not candidates:
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]:
if lang == "objc" and len(candidates) > 1:
# A class split @interface(.h)/@implementation(.m) across repos
# leaves several same-named candidates; bind the selector to its
# sole definition rather than bailing on the collision guard.
target = _objc_union_definition(
merged, members_by_relation["method"], candidates, callee)
if target is None:
continue
targets: list[str] = []
for relation in _member_relations(lang):
members = members_by_relation[relation]
for member_key in _member_keys(lang, callee):
targets.extend(members.get((candidates[0], member_key), []))
if targets:
break
if len(targets) != 1:
continue
target = targets[0]
else:
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):
members = members_by_relation[relation]
for member_key in _member_keys(lang, callee):
targets.extend(members.get((candidates[0], member_key), []))
if targets:
break
if len(targets) != 1:
continue
target = targets[0]
if target == caller or merged.has_edge(caller, target):
continue
merged.add_edge(
@@ -262,7 +309,12 @@ def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
context="cross_repo",
confidence="INFERRED",
confidence_score=0.85,
source_file=str(caller_data.get("source_file") or ""),
# The parked call-site file (the .m), not the caller node's own
# source_file (often the .h where the method is declared): the
# location below is the call-site line, so pairing it with the
# .h would point past the end of an unrelated file. Pre-#3152
# graphs have no `file`, so fall back to the caller's file.
source_file=str(entry.get("file") or caller_data.get("source_file") or ""),
source_location=entry.get("line"),
weight=1.0,
_src=caller,
+191 -7
View File
@@ -446,12 +446,14 @@ def _rank_path(source_file: str, root: Path | None) -> str:
def _collision_rank(node: dict, root: Path | None = None,
mentions: "frozenset | set" = frozenset()) -> tuple:
mentions: "frozenset | set" = frozenset(),
outranked: "frozenset | set" = frozenset()) -> tuple:
"""A total order for choosing the survivor of an ID collision, independent of
the order the colliding nodes arrive in.
The winner is the node with the SMALLEST rank. A node whose ``source_file``
defines the ID always outranks a mere reference; among equally-(non-)defining
defines the ID always outranks a mere reference, and a definer listed in
``outranked`` ranks behind the other definers (#4859); among equally-(non-)defining
nodes an active/in-progress path outranks an archived/done one (#2532); then
it prefers the shorter, more canonical label over a longer qualified variant,
then breaks any remaining tie lexically on label and finally on the REVERSED
@@ -470,6 +472,14 @@ def _collision_rank(node: dict, root: Path | None = None,
level up (#3775/#3786). It changes no collision between two sourced
nodes, since both sides of that key agree there.
``outranked`` (see ``_outranked_by_ast``) holds the ``(id, file)`` of non-AST
definers that another file's AST node also defines. A doc whose own path
prefixes a code entity's id (``pkg.md`` beside ``pkg/test_x.py``) defines it
too, and used to take it on a shorter label, so its next re-extract deleted the
code node (#4859). Such a definer now ranks right behind the other definers;
same-file pairs (#2091), same-stem twins, and collisions with one definer
rank as before.
``mentions`` (see ``_mentions``) holds the ``(id, file)`` of nodes read as a
mention of a document rather than the document itself. Such a node ranks as a
reference even though its id is a path slice, so a real document outranks it
@@ -481,9 +491,10 @@ def _collision_rank(node: dict, root: Path | None = None,
"""
label = node.get("label") or ""
rank_path = _rank_path(node.get("source_file") or "", root)
key = (node.get("id"), rank_path)
return (
# definers (False) sort before references (True)
not _defines_id(node) or (node.get("id"), rank_path) in mentions,
not _defines_id(node) or key in mentions,
key in outranked and node.get("_origin") != "ast", # (#4859)
not node.get("source_file"), # a located node beats a source-less one (#4492)
_lifecycle_penalty(rank_path), # active paths beat archived ones (#2532)
len(label), # shorter, more canonical label first
@@ -492,6 +503,40 @@ def _collision_rank(node: dict, root: Path | None = None,
)
def _outranked_by_ast(nodes: list[dict], root: Path | None,
mentions: "frozenset | set") -> set[tuple[str, str]]:
"""``(id, root-relative file)`` of non-AST definers that an AST node from
another file also defines, while their own file has no AST definer (#4859).
The AST node is extracted fact and the other is an inference about it, so the
AST node keeps the id. The check is strict on ``_origin == "ast"``, as in the
build ghost pass: fresh semantic chunks arrive unstamped. A file that has its
own AST definer (#2091 enrichment) is never listed, and an AST node with the
same full stem (an ``x.py``/``x.html`` twin, or a slug twin such as
``pkg/service.py`` and ``pkg_service.py``) never counts against it.
"""
ast_defs: dict[str, list[tuple[str, str]]] = defaultdict(list)
others: list[tuple[str, str, str]] = []
for node in nodes:
nid = node.get("id") or ""
source_file = node.get("source_file") or ""
rank_path = _rank_path(source_file, root)
if not nid or not _defines_id(node) or (nid, rank_path) in mentions:
continue
entry = (rank_path, _full_stem(source_file))
if node.get("_origin") == "ast":
ast_defs[nid].append(entry)
else:
others.append((nid, *entry))
outranked = set()
for nid, rank_path, stem in others:
defs = ast_defs.get(nid, [])
if (defs and rank_path not in {rp for rp, _ in defs}
and any(ast_stem != stem for _, ast_stem in defs)):
outranked.add((nid, rank_path))
return outranked
def _mentions(nodes: list[dict], edges: list[dict],
root: Path | None) -> set[tuple[str, str]]:
"""``(id, root-relative file)`` of nodes read as a MENTION of a document (#4281).
@@ -609,6 +654,9 @@ def _merge_missing_attributes(survivor: dict, duplicate: dict) -> dict:
return merged
_SHARED_ID_TYPES = ("module", "namespace")
def _report_id_collision(nid: str, survivor: dict, losers: list[dict]) -> None:
"""Report an ID collision in proportion to what dropping the loser actually costs.
@@ -619,6 +667,18 @@ def _report_id_collision(nid: str, survivor: dict, losers: list[dict]) -> None:
and one is genuinely lost — warn, and point at the extraction split that keeps them
apart (#1504).
"""
# A module/namespace node (`import Foundation`) is one shared entity that every
# importing file legitimately mints — the same rule the extractors apply when
# they exempt these types from collision disambiguation. Only a group of one
# such type under one label is that shared entity; a module colliding with a
# namespace, or two differently named modules, is still a real collision.
group = (survivor, *losers)
if (
survivor.get("type") in _SHARED_ID_TYPES
and all(n.get("type") == survivor.get("type") for n in group)
and all(n.get("label") == survivor.get("label") for n in group)
):
return
keep_file = survivor.get("source_file") or ""
keep_label = survivor.get("label") or ""
for loser in losers:
@@ -905,6 +965,120 @@ def _path_qualify_dropped_collisions(
return out_nodes, edges
def _is_reference_stub(node: dict) -> bool:
"""Whether semantic extraction marked a node as a cross-document stub."""
metadata = node.get("metadata")
return isinstance(metadata, dict) and metadata.get("graphify_reference_stub") is True
def _namespace_reference_stub_collisions(
nodes: list[dict], edges: list[dict], hyperedges: list[dict] | None,
root: Path | None, *, preserve_saved_semantics: bool = False,
) -> tuple[list[dict], list[dict]]:
"""Keep semantic references distinct from another file's defining node.
Semantic extraction marks a node it emitted solely for a referenced entity
with ``metadata.graphify_reference_stub``. Preserve every marked node under
``<citing-file>__ref__<original-id>`` instead of silently dropping it when
its target ID collides with another file's node. Edges from the citing file
follow its namespaced endpoint.
The marker distinguishes reference stubs from two independent documents
that happen to share an ID. Path specificity cannot make that distinction:
it regresses genuine nested-path definitions.
With preserve_saved_semantics, AST-only updates retain saved semantic
evidence even when it predates the reference-stub marker. A scan root is
required to distinguish source files; full builds keep their definer rules.
"""
def key(source_file: object) -> str:
return _rank_path(source_file, root) if isinstance(source_file, str) else ""
by_id: dict[str, list[dict]] = defaultdict(list)
for node in nodes:
nid = node.get("id")
if isinstance(nid, str) and nid:
by_id[nid].append(node)
taken = {node.get("id") for node in nodes if node.get("id")}
renames: dict[tuple[str, str], str] = {}
for nid, members in by_id.items():
if len({key(node.get("source_file")) for node in members}) < 2:
continue
ast_sources = {
key(node.get("source_file")) for node in members
if node.get("_origin") == "ast"
}
stubs = [
node for node in members
if _is_reference_stub(node) or (
preserve_saved_semantics
and root is not None
and node.get("_origin") == "semantic"
and key(node.get("source_file"))
and ast_sources
and key(node.get("source_file")) not in ast_sources
)
]
if not stubs:
continue
source_keys = {key(node.get("source_file")) for node in stubs}
if "" in source_keys:
continue
candidates = {
source_key: f"{_full_stem(source_key)}__ref__{nid}"
for source_key in source_keys
if _full_stem(source_key)
}
if len(candidates) != len(source_keys):
continue
if len(set(candidates.values())) != len(candidates):
continue
if any(candidate in taken for candidate in candidates.values()):
if not preserve_saved_semantics:
continue
reserved = taken | set(candidates.values())
for source_key in sorted(candidates):
base = candidates[source_key]
candidate = base
suffix = 2
while candidate in taken or (candidate != base and candidate in reserved):
candidate = f"{base}__{suffix}"
suffix += 1
candidates[source_key] = candidate
reserved.add(candidate)
renames.update(((nid, source_key), candidate)
for source_key, candidate in candidates.items())
taken.update(candidates.values())
if not renames:
return nodes, edges
out_nodes = [
dict(node, id=renames[(node["id"], key(node.get("source_file")))])
if (node.get("id"), key(node.get("source_file"))) in renames else node
for node in nodes
]
for collection in (edges, hyperedges or []):
for item in collection:
if not isinstance(item, dict):
continue
if preserve_saved_semantics and item.get("_origin") == "ast":
continue
source_key = key(item.get("source_file"))
for endpoint in ("source", "target"):
value = item.get(endpoint)
replacement = renames.get((value, source_key))
if replacement:
item[endpoint] = replacement
members = item.get("nodes")
if isinstance(members, list):
item["nodes"] = [renames.get((member, source_key), member)
if isinstance(member, str) else member
for member in members]
return out_nodes, edges
# ── main entry point ──────────────────────────────────────────────────────────
def _remap_hyperedge_members(hyperedges: list[dict], remap: dict[str, str]) -> None:
@@ -956,6 +1130,7 @@ def deduplicate_entities(
root: str | Path | None = None,
hyperedges: "list[dict] | None" = None,
protected_ids: "set[str] | None" = None,
remap_out: "dict[str, str] | None" = None,
) -> tuple[list[dict], list[dict]]:
"""Deduplicate near-identical entities in a knowledge graph.
@@ -963,6 +1138,9 @@ def deduplicate_entities(
nodes: list of node dicts with at minimum {"id": str, "label": str}
edges: list of edge dicts with {"source": str, "target": str, ...}
communities: mapping of node_id -> community_id (from cluster())
remap_out: if given, filled with ``{merged-away id: surviving id}`` for
every node this call dropped. Lets a caller tell a node that was
folded into a twin from one that was lost (#4940).
dedup_llm_backend: if set, use LLM to resolve ambiguous pairs
root: scan root; ID-collision ranking judges source paths relative to
it so path form and checkout location cannot flip the survivor (#2532)
@@ -1003,7 +1181,11 @@ def deduplicate_entities(
# Genuine cross-file ID collisions stay isolated and are reported below (#1504).
nodes, edges = _disambiguate_defining_collisions(nodes, edges, hyperedges, root_resolved)
nodes, edges = _path_qualify_dropped_collisions(nodes, edges, hyperedges, root_resolved)
nodes, edges = _namespace_reference_stub_collisions(
nodes, edges, hyperedges, root_resolved,
)
mentions = _mentions(nodes, edges, root_resolved) | _slice_references(nodes, root_resolved)
outranked = _outranked_by_ast(nodes, root_resolved, mentions)
seen_ids: dict[str, dict] = {}
dropped: dict[str, list[dict]] = defaultdict(list)
for node in nodes:
@@ -1013,8 +1195,8 @@ def deduplicate_entities(
incumbent = seen_ids.get(nid)
if incumbent is None:
seen_ids[nid] = node
elif (_collision_rank(node, root_resolved, mentions)
< _collision_rank(incumbent, root_resolved, mentions)):
elif (_collision_rank(node, root_resolved, mentions, outranked)
< _collision_rank(incumbent, root_resolved, mentions, outranked)):
# Smallest-ranked node wins; the min over a total order is independent
# of the order nodes arrive in, so the survivor no longer depends on
# chunk ordering (#1851).
@@ -1032,7 +1214,7 @@ def deduplicate_entities(
survivor = seen_ids[nid]
same_source = sorted(
(l for l in losers if _same_source_entity(survivor, l)),
key=lambda l: _collision_rank(l, root_resolved, mentions),
key=lambda l: _collision_rank(l, root_resolved, mentions, outranked),
)
for loser in same_source:
survivor = _merge_missing_attributes(survivor, loser)
@@ -1391,6 +1573,8 @@ def deduplicate_entities(
if not remap:
return unique_nodes, edges
if remap_out is not None:
remap_out.update(remap)
total = len(remap)
msg = f"[graphify] Deduplicated {total} node(s)"
# Both counters are reported when non-zero. Previous form nested the fuzzy
+399 -131
View File
@@ -22,7 +22,7 @@ from graphify.google_workspace import (
convert_google_workspace_file,
google_workspace_enabled,
)
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME, out_path
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME, os_long_path, out_path
from graphify.rcfile import activate_language_overrides, cache_salt, effective_suffix
@@ -45,16 +45,24 @@ _MANIFEST_PATH = str(out_path("manifest.json"))
_MTIME_COARSE_S = 2.0
_MTIME_SUBSECOND_S = 0.05
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.ejs', '.ets', '.go', '.rs', '.vb', '.cbl', '.cob', '.cobol', '.cpy', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.cu', '.cuh', '.metal', '.rb', '.rake', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.ml', '.mli', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.vh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.xaml', '.razor', '.cshtml', '.cls', '.trigger', '.lisp', '.cl', '.lsp', '.asd', '.robot', '.resource', '.sol', '.erl', '.hrl', '.escript'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.skill', '.txt', '.rst', '.html', '.yaml', '.yml', '.j2', '.jinja', '.jinja2'}
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.ejs', '.ets', '.go', '.rs', '.vb', '.cbl', '.cob', '.cobol', '.cpy', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.cu', '.cuh', '.metal', '.rb', '.rake', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.ml', '.mli', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.vh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.yaml', '.yml', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.xaml', '.razor', '.cshtml', '.cls', '.trigger', '.lisp', '.cl', '.lsp', '.asd', '.robot', '.resource', '.sol', '.erl', '.hrl', '.escript'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.skill', '.txt', '.rst', '.html', '.j2', '.jinja', '.jinja2'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
_BINARY_MEDIA_EXTENSIONS = (IMAGE_EXTENSIONS - {'.svg'}) | VIDEO_EXTENSIONS
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
FILE_COUNT_UPPER = 500 # files - above this, warn about token cost
# #2942: a large *fraction* of the corpus having no supported extractor (not
# just a small, expected sliver of e.g. lockfiles or binaries) means the
# resulting graph looks complete but structurally represents only part of the
# codebase. Gated on an absolute floor too, so a tiny repo with one stray
# unsupported file does not trip this.
UNCLASSIFIED_WARN_MIN_FILES = 20
UNCLASSIFIED_WARN_FRACTION = 0.2
# Resource caps for parsing untrusted office/PDF files (F2). A corpus is
# attacker-controllable (graphify runs on cloned/shared folders), and .docx/.xlsx
@@ -931,6 +939,8 @@ def convert_office_file(path: Path, out_dir: Path, root: "Path | None" = None) -
def count_words(path: Path) -> int:
try:
ext = path.suffix.lower()
if ext in _BINARY_MEDIA_EXTENSIONS:
return 0
if ext == ".pdf":
return len(extract_pdf_text(path).split())
if ext == ".docx":
@@ -1003,6 +1013,30 @@ _SKIP_FILES = {
".graphifyinclude",
}
# Files a JS/TS toolchain reads to resolve modules: workspace package roots,
# tsconfig `paths`/`baseUrl`, and the installed dependency tree. Changing one of
# these can change a .ts/.tsx/.js result without touching a single source file, so
# the no-change gate in watch._rebuild_code() has to see them (#4740).
# tsconfig*.json / jsconfig.json / package.json are ordinary scan input (they land
# in the "code" bucket and are stamped in the manifest like any other file). The
# lock files are in _SKIP_FILES, so detect() records them separately instead.
_RESOLUTION_INPUT_NAMES = frozenset({
"package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock",
"jsconfig.json",
})
_TS_CONFIG_NAME_RE = re.compile(r"^tsconfig(\.[^/\\]+)?\.json$")
def is_resolution_input(path: "Path | str") -> bool:
"""True when ``path`` steers JS/TS module resolution (#4740).
Deliberately over-approximate: a false positive only costs a slower run, a
false negative ships a stale graph.
"""
name = Path(path).name.lower()
return name in _RESOLUTION_INPUT_NAMES or bool(_TS_CONFIG_NAME_RE.match(name))
# A bare "snapshots" dir is a Jest/Vitest artifact only when it actually holds
# snapshot files or lives directly under a JS test root. Elsewhere it is often a
# real code namespace (e.g. Rails app/services/snapshots/), so pruning it by name
@@ -1011,7 +1045,8 @@ _SKIP_FILES = {
_JS_SNAPSHOT_TEST_ROOTS = frozenset({"__tests__", "__test__"})
# Platforms whose project-scope skills dir is one level below the hidden dir
# (install.py: pi -> .pi/agent/skills, kilo -> .config/kilo/skills).
# (install.py: kilo -> .config/kilo/skills; pi wrote .pi/agent/skills before
# #5011 and projects installed then still carry it).
_NESTED_SKILL_HOLDERS = frozenset({(".pi", "agent"), (".config", "kilo")})
# Single files `graphify install` writes whole into a project (#4057): the
@@ -1146,6 +1181,53 @@ def _has_venv_markers(d: "Path") -> bool:
return False
# Files only MSBuild/NuGet write. ``obj/`` gets the restore outputs (every
# SDK-style restore writes project.assets.json) and, for legacy non-SDK
# projects, the per-configuration FileListAbsolute.txt. ``bin/`` gets the
# runtime manifests the SDK emits next to every executable, plus the PDBs.
# .dll/.exe are deliberately absent: a checked-in tools/bin/ of vendored
# binaries next to its wrapper scripts is source, not output.
_MSBUILD_OBJ_MARKERS = (
"project.assets.json", ".nuget.dgspec.json", ".nuget.g.props",
".filelistabsolute.txt",
)
_MSBUILD_BIN_MARKERS = (".deps.json", ".runtimeconfig.json", ".pdb")
def _has_msbuild_markers(d: "Path", markers: tuple, max_depth: int) -> bool:
"""True when a file ending in one of *markers* sits within *max_depth*
directory levels below *d*.
``bin`` and ``obj`` are MSBuild's output and intermediate dirs, and an
unignored C# project carries both after its first build: the generated
GlobalUsings/AssemblyInfo sources land in the graph as file nodes with
import edges to every implicit namespace, and the build-copied
appsettings*.json are scanned twice. ``dotnet new`` writes no .gitignore,
so nothing else stops them. Neither name is safe to prune alone — ``bin``
is source in Rust's src/bin/, Ruby binstubs and script dirs — so prune
only on MSBuild's own artifacts, the same keep-on-doubt gating ``out``
gets (#3347). The walk is bounded by entries scanned, not just depth.
"""
budget = 4000
pending = [(str(d), 0)]
while pending:
current, depth = pending.pop()
try:
with os.scandir(current) as it:
for entry in it:
budget -= 1
if budget <= 0:
return False
if entry.is_file():
if entry.name.lower().endswith(markers):
return True
elif depth < max_depth and entry.is_dir(follow_symlinks=False):
pending.append((entry.path, depth + 1))
except OSError:
continue
return False
def _is_noise_dir(part: str, parent: "Path | None" = None) -> bool:
"""Return True if this directory name looks like a venv, cache, or dep dir."""
if part in _SKIP_DIRS:
@@ -1170,6 +1252,15 @@ def _is_noise_dir(part: str, parent: "Path | None" = None) -> bool:
if parent is None:
return False # cannot verify; keep a possibly-real code dir
return _has_build_output_markers(parent / part)
if part in ("obj", "bin"):
# Ambiguous: MSBuild intermediate/output dirs OR real source (Rust's
# src/bin/, script dirs). Depths reach a legacy obj/<config>/ and a
# RID-specific bin/<config>/<tfm>/<rid>/.
if parent is None:
return False # cannot verify; keep a possibly-real code dir
if part == "obj":
return _has_msbuild_markers(parent / part, _MSBUILD_OBJ_MARKERS, 1)
return _has_msbuild_markers(parent / part, _MSBUILD_BIN_MARKERS, 3)
if part == "snapshots":
# Prune only when it looks like an actual JS/Vitest snapshot dir.
if parent is None:
@@ -1402,6 +1493,51 @@ def _git_info_exclude(vcs_root: Path) -> Path | None:
return exclude if exclude.is_file() else None
def _linked_worktree_main_root(directory: Path) -> Path | None:
"""Return the main worktree's root for a linked-worktree dir, else None.
``git worktree add`` gives the linked checkout a ``.git`` FILE reading
``gitdir: <main>/.git/worktrees/<name>``, and writes a ``commondir`` file
inside that gitdir pointing back at the shared git dir ``<main>/.git`` —
so the main checkout's root is the common dir's parent. A submodule's
``.git`` file points at ``<super>/.git/modules/<name>``, which carries no
``commondir``; a bare repo's shared git dir is not named ``.git`` (it has
no main working tree); and a moved/deleted main checkout leaves ``cd``
dangling — all three fall through to None and stay scannable (#4683).
No git subprocess is used.
"""
dot_git = directory / ".git"
try:
if not dot_git.is_file():
return None
content = dot_git.read_text(encoding="utf-8", errors="ignore").strip()
except OSError:
return None
if not content.startswith("gitdir:"):
return None
gd = Path(content[len("gitdir:"):].strip())
if not gd.is_absolute():
try:
gd = (directory / gd).resolve()
except (OSError, RuntimeError):
return None
try:
cd_raw = (gd / "commondir").read_text(encoding="utf-8", errors="ignore").strip()
except OSError:
return None
if not cd_raw:
return None
cd = Path(cd_raw)
if not cd.is_absolute():
try:
cd = (gd / cd).resolve()
except (OSError, RuntimeError):
return None
if cd.name != ".git" or not cd.is_dir():
return None
return cd.parent
def _git_global_excludes(vcs_root: Path) -> Path | None:
"""Resolve git's user-wide excludes file (``core.excludesFile``).
@@ -1884,6 +2020,7 @@ def ignored_predicate(
if line:
patterns.append((root, line))
explicit_patterns.append((root, line))
linked_boundaries: dict[Path, bool] = {}
cache: dict[Path, bool] = {}
explicit_cache: dict[Path, bool] = {}
# root's own ignore file is the last entry of _load_graphifyignore's chain.
@@ -1904,6 +2041,13 @@ def ignored_predicate(
if _is_noise_dir(part, parent):
return True
parent = parent / part
if parent not in linked_boundaries:
main_root = _linked_worktree_main_root(parent)
linked_boundaries[parent] = (
main_root is not None and _resolves_under_root(main_root, root)
)
if linked_boundaries[parent]:
return True
# Load ignore files along this path's own lineage — detect()'s walk
# would have loaded exactly these before reaching the file (#1206).
ancestor = root
@@ -2007,6 +2151,10 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
# this bounded — a pruned `data/` is one entry, not one per contained file.
ignored: list[str] = []
pruned_noise: list[str] = []
# JS/TS resolution inputs that _SKIP_FILES keeps out of the corpus. They are
# not scan input, but they do steer resolution, so they are reported
# separately for the no-change gate to compare (#4740).
resolution_inputs: list[str] = []
ignore_patterns = _load_graphifyignore(root, gitignore=gitignore)
explicit_ignore_patterns = _load_graphifyignore(root, gitignore=False)
# See ignored_predicate: skip the `git ls-files` subprocess when .gitignore
@@ -2120,6 +2268,16 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
# than vanishing silently (#2058).
pruned_noise.append(str(child) + os.sep)
continue
# A linked worktree whose main checkout is also inside the
# scan root is a second copy of the same repo — every file
# counted twice (#4683). Neither the name-based rules (the
# worktree's name is arbitrary) nor info/exclude (the scan
# root need not be a repo) reach this sibling layout, but
# its .git file + commondir back-pointer identify it.
_wt_main = _linked_worktree_main_root(child)
if _wt_main is not None and _resolves_under_root(_wt_main, root):
pruned_noise.append(str(child) + os.sep)
continue
# Directory-level pruning: ONE ignore evaluation excludes the
# whole subtree — os.walk never descends, so a 29k-file
# ignored dir costs one check, not one per contained file.
@@ -2139,6 +2297,11 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
dirnames[:] = safe_dirs
for fname in filenames:
if fname in _SKIP_FILES:
if is_resolution_input(fname):
# Not corpus input, but a JS/TS resolution input: record
# it so the no-change gate can compare its content
# (#4740). It stays out of the scan exactly as before.
resolution_inputs.append(str(dp / fname))
continue
p = dp / fname
if _is_installed_graphify_file(p):
@@ -2234,7 +2397,8 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
skipped_sensitive.append(str(p) + " [office conversion failed - pip install graphifyy[office]]")
continue
files[ftype].append(str(p))
if ftype != FileType.VIDEO:
# Bypass legacy cached counts derived from binary media bytes.
if p.suffix.lower() not in _BINARY_MEDIA_EXTENSIONS:
total_words += _wc(p)
for ftype in files:
@@ -2257,48 +2421,46 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
f"Consider running on a subfolder."
)
# #2942: a few unclassified files (lockfiles, binaries, stray config) are
# routine and already reported above by count. A large SHARE of the files
# actually seen having no supported extractor at all is a different,
# louder signal: the graph may look complete while structurally missing
# a large part of the codebase (e.g. a repo whose business logic lives in
# XML, or another language graphify does not parse).
unclassified_warning: str | None = None
_seen_total = total_files + len(unclassified)
if (
len(unclassified) >= UNCLASSIFIED_WARN_MIN_FILES
and _seen_total
and len(unclassified) / _seen_total >= UNCLASSIFIED_WARN_FRACTION
):
unclassified_warning = (
f"{len(unclassified)} of {_seen_total} files seen "
f"({round(len(unclassified) / _seen_total * 100)}%) have no supported "
f"extractor and are missing from this graph entirely. It may look "
f"complete while representing only part of the codebase."
)
return {
"files": {k.value: v for k, v in files.items()},
"total_files": total_files,
"total_words": total_words,
"needs_graph": needs_graph,
"warning": warning,
"unclassified_warning": unclassified_warning,
"skipped_sensitive": skipped_sensitive,
"unclassified": sorted(unclassified),
"walk_errors": walk_errors,
"ignored": sorted(ignored),
"pruned_noise_dirs": sorted(pruned_noise),
"resolution_inputs": sorted(set(resolution_inputs)),
"graphifyignore_patterns": len(ignore_patterns),
"scan_root": str(root.resolve()),
}
def _os_path(path: Path) -> str:
r"""Return an OS path string safe for open()/stat() on Windows long paths.
On win32, paths longer than the legacy MAX_PATH (260 chars) are rejected by
the plain file APIs unless prefixed with the extended-length marker ``\\?\``
(which also requires a fully-qualified path). Without it, _md5_file /
save_manifest / count_words silently fail to hash deeply-nested files, so
their manifest entry never stabilizes and detect_incremental re-flags them
as changed on every run (#1655). cache._normalize_path strips this prefix
for stable KEYS; this adds it for I/O. Non-win32 and already-prefixed paths
pass through unchanged.
"""
import sys
if sys.platform != "win32":
return str(path)
s = str(path)
if s.startswith("\\\\?\\"):
return s
try:
s = os.path.abspath(s) # \\?\ requires a fully-qualified path
except Exception:
return str(path)
if s.startswith("\\\\"):
# UNC share \\server\share -> \\?\UNC\server\share
return "\\\\?\\UNC\\" + s[2:]
return "\\\\?\\" + s
# Shared with cache.py (paths.os_long_path); the name stays for detect's callers.
_os_path = os_long_path
def _md5_file(path: Path) -> str:
@@ -2601,6 +2763,7 @@ def save_manifest(
scan_corpus: set[str] | list[str] | None = None,
clear_semantic: set[str] | list[str] | None = None,
clear_ast: set[str] | list[str] | None = None,
ast_empty: set[str] | list[str] | None = None,
) -> None:
"""Save current file mtimes + content hashes for change detection.
@@ -2644,6 +2807,12 @@ def save_manifest(
``semantic_hash`` on the seeded row so either detect_incremental kind
re-queues the file after the failure is fixed, without deleting
graphify-out/.
``ast_empty`` (#2879): code files the AST extractor declined by design this
run (data JSON, etc.) — stamped as up-to-date yet contributing zero nodes.
Marks their row ``ast_empty: true`` so the #2543 heal can tell an intentional
empty from a poisoned stamp and stop re-queuing them. Preserved across
incrementals for unchanged rows; dropped once a file starts producing nodes.
"""
# Another root may have activated different overrides in this thread.
if root is not None:
@@ -2664,6 +2833,7 @@ def save_manifest(
scan_set = _path_index(scan_corpus)
clear_set = _path_index(clear_semantic)
clear_ast_set = _path_index(clear_ast)
ast_empty_set = _path_index(ast_empty)
try:
root_res: Path | None = Path(root).resolve() if root is not None else None
except (OSError, RuntimeError):
@@ -2700,6 +2870,17 @@ def save_manifest(
except (OSError, RuntimeError):
return False
def _in_ast_empty(path_str: str) -> bool:
if ast_empty_set is None:
return False
if path_str in ast_empty_set or _nfc(path_str) in ast_empty_set:
return True
try:
resolved = str(Path(path_str).resolve())
return resolved in ast_empty_set or _nfc(resolved) in ast_empty_set
except (OSError, RuntimeError):
return False
def _in_root(path_str: str) -> bool:
# Without a root we cannot tell in-root from out-of-root; fail open
# (keep the row) so out-of-root corpora are never pruned by accident.
@@ -2764,7 +2945,9 @@ def save_manifest(
continue # excluded-but-alive: drop the stale row (#1908)
if clear_ast_set is not None and _in_clear_ast(f):
# AST failure this run (missing extra / zero nodes, #2543): blank
# both hashes so either detect_incremental kind re-queues.
# both hashes so either detect_incremental kind re-queues. A genuine
# failure is not an intentional empty, so drop any stale marker too.
normalised = {k: v for k, v in normalised.items() if k != "ast_empty"}
normalised = {**normalised, "ast_hash": "", "semantic_hash": ""}
elif clear_set is not None and _in_clear(f):
# Dispatched-but-omitted this run: don't inherit the stale
@@ -2822,6 +3005,13 @@ def save_manifest(
if current_lang is not None:
# No override keeps legacy rows unchanged.
entry["language"] = current_lang
# Intentional-empty marker (#2879): set when the extractor declined the
# file this run; otherwise inherited across an unchanged incremental the
# same way ast_hash is, and dropped once the file produces nodes.
if _in_ast_empty(f):
entry["ast_empty"] = True
elif not lang_changed and prev.get("ast_empty") and ast_h == prev.get("ast_hash", ""):
entry["ast_empty"] = True
manifest[key] = entry
if storage_root is not None:
manifest = _collapse_manifest_duplicates(
@@ -2867,14 +3057,173 @@ def _mtime_may_hide_a_rewrite(current_mtime: float, stored: dict) -> bool:
if not isinstance(seen, (int, float)):
return False
delta = float(seen) - float(current_mtime)
if delta < 0:
return False # file is newer than the row; the mtime check already fired
# Derive granularity from the timestamp: a whole-second mtime means the
# filesystem cannot separate writes inside that second.
coarse = float(current_mtime).is_integer()
return delta < (_MTIME_COARSE_S if coarse else _MTIME_SUBSECOND_S)
window = _MTIME_COARSE_S if coarse else _MTIME_SUBSECOND_S
if delta < 0:
# The row was stamped a hair BEFORE the mtime it describes (#5036). That
# is not "the file is newer": the caller only gets here when the stored
# and current mtime are equal, and ``seen`` comes from time.time() while
# mtime comes from the filesystem, so either clock can come out a few
# hundred nanoseconds the other way. Same-tick either way, so still
# worth the MD5. A row stamped a full window before the mtime is from an
# earlier run and stays on the stat-only fastpath.
return -delta < window
return delta < window
def classify_manifest_files(
file_buckets: dict[str, list[str]],
manifest: dict,
*,
kind: str = "ast",
unstamped_is_changed: bool = True,
) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
"""Split ``file_buckets`` into (changed, unchanged) against ``manifest``.
This is the comparison ``detect_incremental`` has always used: mtime first
(free, no disk IO beyond stat), content hash only when mtime moved or when
the racily-clean window needs it. A missing row, a row with no usable hash,
a language change, or an unknown row format all count as changed, so a caller
can only ever over-report change.
Factored out so the ``graphify update`` no-change gate in
:func:`graphify.watch._rebuild_code` reaches the same verdict from an
already-computed ``detect()`` result instead of paying for a second scan
(#4740). ``file_buckets`` is not required to come from ``detect()["files"]``:
the gate passes a synthetic bucket holding the JS/TS resolution inputs that
the manifest stamps but the scan skips.
``unstamped_is_changed=False`` is for that gate. A file with no row (or a row
whose hash was blanked after a failed extraction, #2543) is then treated as
unchanged: it contributed no nodes, so re-extraction cannot change the graph,
and only the gate's own file-set digest can tell "same file, still failing"
from "new file". The incremental path keeps the default, where such a file is
re-queued until it extracts.
"""
new_files: dict[str, list[str]] = {k: [] for k in file_buckets}
unchanged_files: dict[str, list[str]] = {k: [] for k in file_buckets}
for ftype, file_list in file_buckets.items():
for f in file_list:
# Manifest keys are NFC; scan paths may arrive NFD (#2221).
stored = manifest.get(_nfc(f))
try:
current_mtime = os.stat(_os_path(Path(f))).st_mtime
except Exception:
current_mtime = 0
# Legacy manifest: plain float value stores only mtime.
# Compare with `!=` so backwards mtime motion (git checkout of an
# older commit, tarball restore, rsync --times) still triggers a
# re-extract; the previous `>` silently kept the stale cache and
# the graph drifted from disk (#1859). No stored hash means we
# cannot verify content — any mtime delta forces a re-extract,
# and the next save promotes the entry into the dict schema.
# A language change invalidates even identical bytes and legacy rows.
stored_lang = stored.get("language") if isinstance(stored, dict) else None
if stored is None:
changed = unstamped_is_changed
elif cache_salt(f) != stored_lang:
changed = True
elif isinstance(stored, (int, float)):
changed = current_mtime != stored
elif isinstance(stored, dict):
# Normalise legacy {mtime, hash} to new schema
if "hash" in stored and "ast_hash" not in stored:
stored = {"mtime": stored.get("mtime", 0), "ast_hash": stored["hash"], "semantic_hash": ""}
hash_key = "semantic_hash" if kind == "semantic" else "ast_hash"
stored_hash = stored.get(hash_key, "")
# Missing semantic_hash means update ran but extract hasn't — always re-extract
if not stored_hash:
changed = unstamped_is_changed
else:
stored_mtime = stored.get("mtime")
# Schema-drift guard (#1163): tolerate a nested {mtime: ...}
# dict or any non-numeric value without crashing.
if isinstance(stored_mtime, dict):
stored_mtime = stored_mtime.get("mtime")
if not isinstance(stored_mtime, (int, float)):
stored_mtime = None
if stored_mtime is None or current_mtime != stored_mtime:
# mtime bumped — verify with content hash before re-extracting
changed = _md5_file(Path(f)) != stored_hash
elif _mtime_may_hide_a_rewrite(current_mtime, stored):
# mtime is unchanged, but it was recorded in the same
# filesystem tick the file was written in — a later
# same-length edit lands in that tick without moving
# mtime, and the file silently skips re-extraction
# while the graph keeps serving the old content.
# Only this narrow window pays for a content hash.
changed = _md5_file(Path(f)) != stored_hash
else:
changed = False
else:
changed = True # unknown format, re-extract to be safe
if changed:
new_files[ftype].append(f)
else:
unchanged_files[ftype].append(f)
return new_files, unchanged_files
def classify_manifest_deletions(
manifest: dict,
scanned: Iterable[str],
*,
root: Path | None = None,
) -> tuple[list[str], list[str]]:
"""Split manifest rows that left the scan into (deleted, excluded).
A row whose file is gone from DISK is a genuine deletion (its cached nodes
are ghosts); a row whose file still exists but is out of the current scan was
EXCLUDED by a changed ignore rule and must not be reported as deleted
(#1908). Mirrors the watch-side excluded-vs-deleted distinction (#1795).
``scanned`` must name every row the caller expects to see, including sources
that carry manifest rows without being part of the scan corpus
(``detect()["resolution_inputs"]``, #4740), or those rows read as excluded on
every run.
"""
try:
root_res: Path | None = Path(root).resolve() if root is not None else None
except (OSError, RuntimeError):
root_res = Path(root) if root is not None else None
def _in_root(path_str: str) -> bool:
if root_res is None:
return True
p = Path(path_str)
try:
p.relative_to(root_res)
return True
except ValueError:
pass
try:
p.resolve().relative_to(root_res)
return True
except (ValueError, OSError, RuntimeError):
return False
current_files = {_nfc(f) for f in scanned}
deleted_files: list[str] = []
excluded_files: list[str] = []
for f in manifest:
if not _in_root(f):
continue
if _nfc(f) in current_files:
continue
try:
alive = Path(f).exists()
except OSError:
alive = False
(excluded_files if alive else deleted_files).append(f)
return deleted_files, excluded_files
def detect_incremental(
root: Path,
manifest_path: str = _MANIFEST_PATH,
@@ -2938,108 +3287,27 @@ def detect_incremental(
full["excluded_files"] = []
return full
new_files: dict[str, list[str]] = {k: [] for k in full["files"]}
unchanged_files: dict[str, list[str]] = {k: [] for k in full["files"]}
for ftype, file_list in full["files"].items():
for f in file_list:
# Manifest keys are NFC; scan paths may arrive NFD (#2221).
stored = manifest.get(_nfc(f))
try:
current_mtime = os.stat(_os_path(Path(f))).st_mtime
except Exception:
current_mtime = 0
# Legacy manifest: plain float value stores only mtime.
# Compare with `!=` so backwards mtime motion (git checkout of an
# older commit, tarball restore, rsync --times) still triggers a
# re-extract; the previous `>` silently kept the stale cache and
# the graph drifted from disk (#1859). No stored hash means we
# cannot verify content — any mtime delta forces a re-extract,
# and the next save promotes the entry into the dict schema.
# A language change invalidates even identical bytes and legacy rows.
stored_lang = stored.get("language") if isinstance(stored, dict) else None
if stored is not None and cache_salt(f) != stored_lang:
changed = True
elif isinstance(stored, (int, float)):
changed = current_mtime != stored
elif isinstance(stored, dict):
# Normalise legacy {mtime, hash} to new schema
if "hash" in stored and "ast_hash" not in stored:
stored = {"mtime": stored.get("mtime", 0), "ast_hash": stored["hash"], "semantic_hash": ""}
hash_key = "semantic_hash" if kind == "semantic" else "ast_hash"
stored_hash = stored.get(hash_key, "")
# Missing semantic_hash means update ran but extract hasn't — always re-extract
if not stored_hash:
changed = True
else:
stored_mtime = stored.get("mtime")
# Schema-drift guard (#1163): tolerate a nested {mtime: ...}
# dict or any non-numeric value without crashing.
if isinstance(stored_mtime, dict):
stored_mtime = stored_mtime.get("mtime")
if not isinstance(stored_mtime, (int, float)):
stored_mtime = None
if stored_mtime is None or current_mtime != stored_mtime:
# mtime bumped — verify with content hash before re-extracting
changed = _md5_file(Path(f)) != stored_hash
elif _mtime_may_hide_a_rewrite(current_mtime, stored):
# mtime is unchanged, but it was recorded in the same
# filesystem tick the file was written in — a later
# same-length edit lands in that tick without moving
# mtime, and the file silently skips re-extraction
# while the graph keeps serving the old content.
# Only this narrow window pays for a content hash.
changed = _md5_file(Path(f)) != stored_hash
else:
changed = False
else:
changed = True # unknown format, re-extract to be safe
if changed:
new_files[ftype].append(f)
else:
unchanged_files[ftype].append(f)
new_files, unchanged_files = classify_manifest_files(full["files"], manifest, kind=kind)
# Manifest rows that left the corpus, split by disk existence (#1908):
# a row whose file is gone from DISK is a genuine deletion (its cached
# nodes are ghosts); a row whose file still exists but is out of the
# current scan was EXCLUDED (ignore rules / --exclude changed) and must
# not be reported as deleted. Mirrors the watch-side excluded-vs-deleted
# distinction (#1795).
try:
root_res: Path | None = Path(root).resolve() if root is not None else None
except (OSError, RuntimeError):
root_res = Path(root) if root is not None else None
def _in_root(path_str: str) -> bool:
if root_res is None:
return True
p = Path(path_str)
try:
p.relative_to(root_res)
return True
except ValueError:
pass
try:
p.resolve().relative_to(root_res)
return True
except (ValueError, OSError, RuntimeError):
return False
current_files = {_nfc(f) for flist in full["files"].values() for f in flist}
deleted_files: list[str] = []
excluded_files: list[str] = []
for f in manifest:
if not _in_root(f):
continue
if _nfc(f) in current_files:
continue
try:
alive = Path(f).exists()
except OSError:
alive = False
(excluded_files if alive else deleted_files).append(f)
# distinction (#1795). Resolution inputs carry manifest rows while being
# deliberately kept out of detect()'s corpus, so they are named here too;
# without that they would read as rows that left the scan on every run
# (#4740).
deleted_files, excluded_files = classify_manifest_deletions(
manifest,
[
f
for flist in full["files"].values()
for f in flist
]
+ list(full.get("resolution_inputs", [])),
root=root,
)
new_total = sum(len(v) for v in new_files.values())
full["incremental"] = True
+82 -25
View File
@@ -15,7 +15,7 @@ import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.analyze import _node_community_map
from graphify.build import edge_data, has_parallel_links
from graphify.build import edge_datas, has_parallel_links
from graphify.paths import (
os_replace_with_fallback,
stem_filename_budget,
@@ -75,18 +75,25 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
backup_dir = out / today
graph_src = out / "graph.json"
# Skip re-copying if today's backup already has identical graph.json content.
# If content differs (graph changed since the last backup today), overwrite
# the backup in place — one folder per day, always the latest pre-overwrite state.
if backup_dir.exists() and (backup_dir / "graph.json").exists():
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
if src_hash == bak_hash:
return backup_dir # identical content, nothing to do
try:
# Skip re-copying if today's backup already holds every artifact with an
# identical graph.json. graph.json alone is not proof of completeness: a
# snapshot missing a sidecar (an earlier copy attempt failed part-way)
# must fall through and retry the copy instead of reporting itself
# complete forever (#3769). If content differs, overwrite the backup in
# place — one folder per day, always the latest pre-overwrite state.
if backup_dir.exists() and (backup_dir / "graph.json").exists():
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
if src_hash == bak_hash and all(
(backup_dir / name).exists()
for name in _BACKUP_ARTIFACTS
if (out / name).exists()
):
return backup_dir # identical content, nothing to do
backup_dir.mkdir(parents=True, exist_ok=True)
copied = 0
failed: list[str] = []
for name in _BACKUP_ARTIFACTS:
src = out / name
if src.exists():
@@ -94,12 +101,21 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
shutil.copy2(src, backup_dir / name)
copied += 1
except Exception:
pass
failed.append(name)
if failed:
# A partial snapshot reported as a successful backup lets a stale
# graph.json survive the next overwrite unnoticed (#3769). Best-effort
# is unchanged: warn, report no backup, do not block the write.
print(
f"[graphify] warning: backup incomplete - could not copy "
f"{', '.join(failed)} -> {backup_dir.name}/ - continuing with overwrite",
file=sys.stderr,
)
return None
if copied:
print(f"[graphify] backed up {reason} graph ({copied} files) -> {backup_dir.name}/")
return backup_dir
except Exception as exc:
import sys
print(f"[graphify] warning: backup failed ({exc}) - continuing with overwrite", file=sys.stderr)
return None
@@ -287,8 +303,14 @@ def existing_graph_node_count(path: "str | Path"):
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None, community_labels: dict[int, str] | None = None, original_links: "list[dict] | None" = None) -> bool:
# Drop #3774 accounting before any write. Extract pops these first; every
# other caller of to_json (the documented build_merge persist path) does not.
from graphify.build import take_shrink_accounting
from graphify.build import take_dedup_remap, take_shrink_accounting
# The guard below reads it; it is removed here so node_link_data cannot
# write it into graph.json (#4940).
dedup_remap = take_dedup_remap(G)
take_shrink_accounting(G)
# Sources build_merge replaced or pruned this run: their old semantic ids
# are not lost. Popped so it is never written into graph.json.
replaced_sources = set(G.graph.pop("_replaced_sources", None) or ())
# Safety check: refuse to silently shrink an existing graph (#479)
existing_path = Path(output_path)
if not force and existing_path.exists():
@@ -315,7 +337,10 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
else:
try:
existing_data = json.loads(raw)
del raw
existing_nodes = existing_data.get("nodes", [])
# Only the node list is compared; let the links go now.
del existing_data
if not isinstance(existing_nodes, list):
existing_nodes = []
existing_n = len(existing_nodes)
@@ -335,12 +360,15 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
)
return False
new_n = G.number_of_nodes()
from graphify.build import _lost_saved_semantic_nodes
from graphify.build import _dedup_shrink_allowance, _lost_saved_semantic_nodes
new_node_list = [
{"id": node_id, **{key: value for key, value in attrs.items() if key != "id"}}
for node_id, attrs in G.nodes(data=True)
]
missing = _lost_saved_semantic_nodes(existing_nodes, new_node_list, set())
folded: dict[str, str] = {}
missing = _lost_saved_semantic_nodes(
existing_nodes, new_node_list, replaced_sources, folded, dedup_remap=dedup_remap,
)
if missing:
import sys as _sys
ids = ", ".join(str(node.get("id")) for node in missing)
@@ -350,7 +378,17 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
file=_sys.stderr,
)
return False
if new_n < existing_n:
# A saved semantic node merged into an AST twin that was already
# saved is one node, not two; a reload-and-recluster folds it (#4389).
# A twin new to this run does not offset some other node's loss.
existing_ids = {n.get("id") for n in existing_nodes if isinstance(n, dict)}
merged = sum(twin in existing_ids for twin in folded.values())
# Ids entity dedup folded into a survivor are not lost either (#4940).
if dedup_remap:
merged += _dedup_shrink_allowance(
existing_ids, set(G.nodes), dedup_remap,
)
if new_n < existing_n - merged:
import sys as _sys
print(
f"[graphify] WARNING: new graph has {new_n} nodes but existing "
@@ -363,6 +401,8 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
file=_sys.stderr,
)
return False
# The guard passed; free its copies of both graphs before export.
del existing_nodes, new_node_list, existing_ids
node_community = _node_community_map(communities)
_labels: dict[int, str] = {int(k): v for k, v in (community_labels or {}).items()}
@@ -436,8 +476,14 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
rest = sorted(k for k in item if k not in leading)
return {k: item[k] for k in (*leading, *rest)}
data["nodes"] = [_canonical(n, ("id", "label")) for n in data["nodes"]]
data["links"] = [_canonical(link, ("source", "target", "relation")) for link in data["links"]]
def _canonicalize_in_place(items: list, lead: tuple[str, ...]) -> None:
# Replace each dict in place so the old one is freed at once, instead
# of holding two full copies of the node/link lists.
for i, item in enumerate(items):
items[i] = _canonical(item, lead)
_canonicalize_in_place(data["nodes"], ("id", "label"))
_canonicalize_in_place(data["links"], ("source", "target", "relation"))
data["nodes"].sort(key=_json_sort_key)
data["links"].sort(key=_json_sort_key)
if "hyperedges" not in getattr(G, "graph", {}):
@@ -458,6 +504,8 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
_prev = json.loads(existing_path.read_text(encoding="utf-8"))
if isinstance(_prev, dict):
_prev_hyperedges = _prev.get("hyperedges")
# Only the hyperedges are read; do not hold the whole parse.
del _prev
except Exception:
_prev_hyperedges = None
if _prev_hyperedges:
@@ -558,7 +606,7 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
(data.get("file_type", "unknown") or "unknown").capitalize(),
"Entity",
)
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}'}}) SET n.label = '{label}';")
lines.append("")
for u, v, data in G.edges(data=True):
u, v = data.get("_src", u), data.get("_tgt", v)
@@ -859,9 +907,9 @@ def to_obsidian(
# Build tags for this node
ftype = data.get("file_type", "")
ftype_tag = _FTYPE_TAG.get(ftype, f"graphify/{ftype}" if ftype else "graphify/document")
ftype_tag = _FTYPE_TAG.get(ftype, f"graphify/{_obsidian_tag(ftype)}" if ftype else "graphify/document")
dom_conf = _dominant_confidence(node_id)
conf_tag = f"graphify/{dom_conf}"
conf_tag = f"graphify/{_obsidian_tag(dom_conf)}"
comm_tag = f"community/{_obsidian_tag(community_name)}"
node_tags = [ftype_tag, conf_tag, comm_tag]
@@ -889,11 +937,20 @@ def to_obsidian(
if neighbors:
lines.append("## Connections")
for neighbor in sorted(neighbors, key=lambda n: G.nodes[n].get("label", n)):
edata = edge_data(G, node_id, neighbor)
neighbor_label = node_filename[neighbor]
relation = edata.get("relation", "")
confidence = edata.get("confidence", "EXTRACTED")
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
# One bullet per parallel edge, not per neighbour: graph.json is
# reloaded as a MultiGraph when it carries parallel edges
# (#4500), and `edge_data()` returns only the FIRST of them — so
# a pair joined by both `imports` and `calls` lost one relation
# from the note. Sorted so the note is byte-stable regardless of
# the order the parallel edges were inserted in.
for edata in sorted(
edge_datas(G, node_id, neighbor),
key=lambda d: (str(d.get("relation", "")), str(d.get("confidence", "EXTRACTED"))),
):
relation = edata.get("relation", "")
confidence = edata.get("confidence", "EXTRACTED")
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
lines.append("")
# Inline tags at bottom of note body (for Obsidian tag panel)
+2110 -117
View File
File diff suppressed because it is too large. Load diff
+64 -5
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import sys
from contextvars import ContextVar
from pathlib import Path
from graphify.ids import make_id
@@ -15,15 +16,33 @@ from graphify.ids import make_id
# function-local `import graphify.extract` + getattr(..., None) was a package ->
# parent dependency that also failed silently if the module global were renamed
# (#3666). None outside extract().
_ACTIVE_SCAN_ROOT: "Path | None" = None
#
# A ContextVar rather than a module global: extraction runs concurrently
# (ThreadPoolExecutor in tests, process pools in production), and a plain
# global lets overlapping save/restore pairs interleave — the second call
# saves the first one's root and restores it last, leaving the ambient root
# set after extract() returns (#4602). ContextVar gives every thread (and
# async task) its own value, so save/restore pairs nest correctly without a
# lock.
#
# Semantic note: because the value is context-local, a root set on one
# thread is NOT visible to worker threads spawned mid-extraction. Every
# real call path sets and reads the root inside the same pool worker
# (_safe_extract_with_xaml_root runs inside the worker; the scan root also
# travels to workers as an explicit `root` parameter, not via this
# global), so no production path crosses the boundary. If a future
# extractor needs cross-thread visibility, propagate explicitly with
# contextvars.copy_context() at the dispatch site.
_ACTIVE_SCAN_ROOT: "ContextVar[Path | None]" = ContextVar(
"_ACTIVE_SCAN_ROOT", default=None
)
def set_active_scan_root(root: "Path | None") -> "Path | None":
"""Set the in-flight scan root, returning the previous value so the caller
can restore it — extraction nests (a XAML shard re-enters extract())."""
global _ACTIVE_SCAN_ROOT
previous = _ACTIVE_SCAN_ROOT
_ACTIVE_SCAN_ROOT = root
previous = _ACTIVE_SCAN_ROOT.get()
_ACTIVE_SCAN_ROOT.set(root)
return previous
@@ -32,7 +51,7 @@ def active_scan_root() -> "Path | None":
A direct ``extract_markdown()`` / ``extract_xaml()`` call (no surrounding
``extract()``) sees None and the root-dependent behavior stays off."""
return _ACTIVE_SCAN_ROOT
return _ACTIVE_SCAN_ROOT.get()
# 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)).
@@ -79,6 +98,46 @@ _LANGUAGE_BUILTIN_GLOBALS: frozenset[str] = frozenset({
"View", "Color", "Font",
})
# Python's own builtin namespace, deliberately kept separate from
# ``_LANGUAGE_BUILTIN_GLOBALS``. That set is consulted at extraction time for a
# bare call, where dropping the raw call is correct for a true builtin but also
# throws away the evidence needed to resolve a legitimate imported class that
# merely shares a builtin's name (#4989). This set is only consulted after a
# cross-file candidate has been found, and only to require a direct import
# binding before accepting it: in Python a bare name resolves to the builtin
# unless the module binds it itself, so `raise NotImplementedError` in a file
# that never imports anything must not link to a package class named
# ``NotImplementedError``. Fixed rather than derived from ``dir(builtins)`` so
# extraction stays deterministic across interpreter versions.
_PYTHON_BUILTIN_NAMES: frozenset[str] = frozenset({
"ArithmeticError", "AssertionError", "AttributeError", "BaseException",
"BaseExceptionGroup", "BlockingIOError", "BrokenPipeError", "BufferError",
"BytesWarning", "ChildProcessError", "ConnectionAbortedError", "ConnectionError",
"ConnectionRefusedError", "ConnectionResetError", "DeprecationWarning", "EOFError",
"Ellipsis", "EncodingWarning", "EnvironmentError", "Exception", "ExceptionGroup",
"False", "FileExistsError", "FileNotFoundError", "FloatingPointError",
"FutureWarning", "GeneratorExit", "IOError", "ImportError", "ImportWarning",
"IndentationError", "IndexError", "InterruptedError", "IsADirectoryError",
"KeyError", "KeyboardInterrupt", "LookupError", "MemoryError",
"ModuleNotFoundError", "NameError", "None", "NotADirectoryError", "NotImplemented",
"NotImplementedError", "OSError", "OverflowError", "PendingDeprecationWarning",
"PermissionError", "ProcessLookupError", "RecursionError", "ReferenceError",
"ResourceWarning", "RuntimeError", "RuntimeWarning", "StopAsyncIteration",
"StopIteration", "SyntaxError", "SyntaxWarning", "SystemError", "SystemExit",
"TabError", "TimeoutError", "True", "TypeError", "UnboundLocalError",
"UnicodeDecodeError", "UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError",
"UnicodeWarning", "UserWarning", "ValueError", "Warning", "ZeroDivisionError",
"abs", "aiter", "all", "anext", "any", "ascii", "bin", "bool", "breakpoint",
"bytearray", "bytes", "callable", "chr", "classmethod", "compile", "complex",
"copyright", "credits", "delattr", "dict", "dir", "divmod", "enumerate", "eval",
"exec", "exit", "filter", "float", "format", "frozenset", "getattr", "globals",
"hasattr", "hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass",
"iter", "len", "license", "list", "locals", "map", "max", "memoryview", "min",
"next", "object", "oct", "open", "ord", "pow", "print", "property", "quit", "range",
"repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod",
"str", "sum", "super", "tuple", "type", "vars", "zip",
})
def _make_id(*parts: str) -> str:
return make_id(*parts)
+17 -4
View File
@@ -54,11 +54,24 @@ def extract_blade(path: Path) -> dict:
"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))
# wire:click="methodName" or wire:click="methodName(arg)", with an optional
# Livewire event modifier (wire:click.prevent=, wire:click.stop=) the bare
# `wire:click=` pattern never matched at all. A call's own arguments are not
# part of the method's name and must not end up in the bound id; a magic
# action ($set, $emit, $toggle, $refresh, ...) is Livewire's own runtime
# behavior, not a method the component defines, so it is left unbound rather
# than fabricating an edge to something that does not exist.
for m in re.finditer(r'wire:click(?:\.\w+)*=["\']([^"\']+)["\']', src):
raw = m.group(1).strip()
if raw.startswith("$"):
continue
name_match = re.match(r"[A-Za-z_]\w*", raw)
if not name_match:
continue
method_name = name_match.group(0)
tgt_nid = _make_id(method_name)
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
nodes.append({"id": tgt_nid, "label": method_name, "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,
+17
View File
@@ -22,6 +22,7 @@ _COPY = re.compile(
re.IGNORECASE,
)
_CALL = re.compile(r"\bCALL\s+(['\"])([A-Z0-9-]+)\1", re.IGNORECASE)
_END_PROGRAM = re.compile(r"\bEND\s+PROGRAM\b", re.IGNORECASE)
_DATA_ITEM = re.compile(
rf"^\s*(?:0[1-9]|[1-4][0-9]|66|77|88)\s+({_NAME})\b", re.IGNORECASE
)
@@ -169,6 +170,14 @@ def extract_cobol(path: Path) -> dict:
in_exec = False
paragraphs: dict[tuple[str, str], str] = {}
pending_performs: list[tuple[str, str, str, int]] = []
# A nested (contained) program's PROGRAM-ID switches current_program with
# no record of what it switched FROM; everything after its own END
# PROGRAM, including code physically back in the enclosing program, kept
# attributing to the nested one forever. Each PROGRAM-ID pushes the
# program it is nested under (possibly file_id, for a top-level one), and
# END PROGRAM pops back to it, so sibling and nested programs alike
# restore the right scope once their own body ends.
program_stack: list[str] = []
for line, code in code_lines:
upper = code.upper().strip()
@@ -182,9 +191,17 @@ def extract_cobol(path: Path) -> dict:
in_exec = True
continue
if _END_PROGRAM.search(upper):
if program_stack:
current_program = program_stack.pop()
current_scope = current_program
in_procedure = True
continue
program_match = _PROGRAM.search(upper)
if program_match:
name = program_match.group(1).upper()
program_stack.append(current_program)
current_program = add_node(
_make_id(file_id, "program", name.casefold()),
name,
+46 -4
View File
@@ -5,6 +5,7 @@ import warnings
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id, _read_source_bytes
from graphify.security import redact_secrets
# Standard CL definer forms that introduce data/type/variable bindings
@@ -166,9 +167,16 @@ def extract_commonlisp(path: Path) -> dict:
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."""
inheritance edge whose parent lives in a different file.
`local` is checked against `local_class_names` (every class this file
defines, gathered up front), not just `seen_ids`: forms are walked in
file order, so a class referenced before its own `defclass` form is
processed — e.g. a subclass listed above its parent — would otherwise
still be in `seen_ids` as absent, and this would wrongly mint an
external stub for a class that is right here in the same file."""
local = _cl_id(stem, name)
if local in seen_ids:
if local in seen_ids or name in local_class_names:
return local
stub = _cl_id(name)
if stub not in seen_ids:
@@ -330,7 +338,7 @@ def extract_commonlisp(path: Path) -> dict:
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_node(doc_nid, redact_secrets(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
@@ -420,7 +428,7 @@ def extract_commonlisp(path: Path) -> dict:
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_node(doc_nid, redact_secrets(doc_text)[:120], child.start_point[0] + 1, file_type="rationale")
add_edge(doc_nid, nid, "rationale_for",
child.start_point[0] + 1)
break
@@ -504,6 +512,40 @@ def extract_commonlisp(path: Path) -> dict:
elif top.type == "include_reader_macro":
_walk_forms(top)
def _prescan_class_names(parent) -> set[str]:
"""Collect every name this file defines via `defclass`, regardless of
where in the file the definition sits, so `ensure_class_ref` can tell
a forward-referenced same-file class apart from a genuinely external
one before `_walk_forms` reaches the defining form. Mirrors
`_walk_forms`'s own recursion rule (stop at a recognized top-level
form, descend into anything else) so it finds a `defclass` nested in
a wrapper macro the same way the real walk later will."""
names: set[str] = set()
for top in parent.children:
if top.type == "list_lit":
first = _first_sym(top)
first_lower = (first or "").lower()
if first_lower == "defclass":
# Mirror _handle_defclass's own name extraction exactly
# (direct-child sym_lits, second one is the name) so a
# form _handle_defclass would itself skip — e.g. a
# list-style name — isn't prescanned as a local class.
sym_lits = [c for c in top.children if c.type == "sym_lit"]
if len(sym_lits) >= 2:
names.add(_text(sym_lits[1]))
elif not first or (
first_lower not in ("defpackage", "in-package", "require", "ql:quickload")
and first_lower not in _CL_DATA_DEFINERS
and first_lower not in _CL_MACRO_DEFINERS
and not _is_def_prefixed(first_lower)
):
names |= _prescan_class_names(top)
elif top.type == "include_reader_macro":
names |= _prescan_class_names(top)
return names
local_class_names = _prescan_class_names(root)
_walk_forms(root)
# Call extraction pass
+130
View File
@@ -11,12 +11,28 @@ the core migration happens.
from __future__ import annotations
import html
from collections.abc import Iterable
from pathlib import Path
from graphify.extractors.base import _make_id
from graphify.rcfile import effective_suffix
def is_csharp_constructor_node(node: dict) -> bool:
"""A C# constructor node (instance, static or primary).
A constructor carries its type's name but is reached only through `new`
or a `: base(...)` / `: this(...)` initializer, never by that name, so the
name-keyed call indexes leave it out.
"""
metadata = node.get("metadata") or {}
return (
isinstance(metadata, dict)
and metadata.get("kind") == "constructor"
and effective_suffix(str(node.get("source_file") or "")) == ".cs"
)
def _build_csharp_type_def_index(
all_nodes: list[dict],
all_edges: list[dict] | None = None,
@@ -187,6 +203,92 @@ def _metadata(value: object) -> dict:
return value if isinstance(value, dict) else {}
def _is_plain_csharp_name(text: str) -> bool:
return bool(text) and not any(ch in text for ch in ".()") and not any(
ch.isspace() for ch in text
)
def bare_csharp_method_label(label: object, source_file: object) -> str | None:
"""Return the ``.Name()`` resolver form of a C# method label, else ``None``.
Accepts both the extractor's bare ``.Name()`` and the owner-qualified
``Owner.Name()`` display form the graph build assigns (#4883). Extraction
emits, and call resolution, interface dispatch, and the method-ghost index
match on, the bare form, so anything reading labels back from a persisted
graph normalizes through here. C# method and type names never contain a
dot (an explicit interface implementation is still labeled ``.Build()``),
so the split is unambiguous.
"""
if not _is_cs_file(source_file) or not isinstance(label, str):
return None
if not label.endswith("()"):
return None
owner, dot, name = label[:-2].rpartition(".")
if not dot or not _is_plain_csharp_name(name):
return None
if owner and not _is_plain_csharp_name(owner):
return None
return f".{name}()"
def bare_csharp_method_labels_in_nodes(nodes: list[dict]) -> list[dict]:
"""Copy of *nodes* with owner-qualified C# method labels reverted to ``.Name()``.
Nodes that need no change are returned as-is; changed nodes are shallow
copies, so the caller's list and dicts are never mutated.
"""
out: list[dict] = []
for node in nodes:
label = node.get("label")
bare = bare_csharp_method_label(label, node.get("source_file"))
out.append(node if bare is None or bare == label else {**node, "label": bare})
return out
def csharp_method_label_reassignments(
nodes: Iterable[tuple[object, dict]],
method_edges: Iterable[tuple[object, object]],
) -> dict[str, str]:
"""Return ``{method_id: "Owner.Name()"}`` display labels for C# methods (#4883).
*nodes* are ``(id, attrs)`` pairs and *method_edges* are ``(owner_id,
method_id)`` pairs from ``method`` edges. A method with zero or several
distinct owner labels, or an owner whose label is not a plain type name,
is omitted and keeps its bare ``.Name()`` label. Derived from the bare form,
so applying it to already-qualified labels is a no-op.
"""
owner_label_by_id: dict[str, str] = {}
bare_by_id: dict[str, str] = {}
for nid, attrs in nodes:
if not isinstance(nid, str) or not isinstance(attrs, dict):
continue
label = attrs.get("label")
source_file = attrs.get("source_file")
if not isinstance(label, str) or not _is_cs_file(source_file):
continue
if _is_plain_csharp_name(label):
owner_label_by_id[nid] = label
continue
bare = bare_csharp_method_label(label, source_file)
if bare is not None:
bare_by_id[nid] = bare
owner_labels_by_method: dict[str, set[str | None]] = {}
for owner, method in method_edges:
if isinstance(owner, str) and isinstance(method, str) and method in bare_by_id:
owner_labels_by_method.setdefault(method, set()).add(owner_label_by_id.get(owner))
out: dict[str, str] = {}
for method, owner_labels in owner_labels_by_method.items():
if len(owner_labels) != 1:
continue
owner_label = next(iter(owner_labels))
if owner_label is not None:
out[method] = f"{owner_label}{bare_by_id[method]}"
return out
class CsharpNameResolver:
"""Namespace/using/alias-aware C# simple-name resolution.
@@ -320,6 +422,34 @@ class CsharpNameResolver:
_append_unique(scopes, namespace)
return scopes
def visible_namespaces(self, source_node: dict, source_file: str) -> list[set[str]]:
"""Namespaces visible to extension-method lookup, innermost level first.
C# 12.8.10.3: for each enclosing namespace declaration — innermost first,
ending with the compilation unit — consider that namespace and the
``using namespace`` directives declared at that level. A file-level
using belongs to the compilation unit, so it is only considered at the
outermost level; that is why an extension declared in an inner namespace
wins over one imported at the top of the file (#4828).
A namespace-scoped using is treated as visible at every level inside it.
That is coarser than the spec but only ever adds candidates at a deeper
level than the directive's own, and the caller drops ties.
"""
chain = [part for part in self._namespace(source_node).split(".") if part]
usings = self.namespace_usings_by_file.get(source_file, [])
levels: list[set[str]] = []
for i in range(len(chain), -1, -1):
visible = {".".join(chain[:i])}
for target_fqn, scope_kind, scope_id in usings:
if scope_kind == "file":
if i == 0:
visible.add(target_fqn)
elif self._using_in_scope(scope_kind, scope_id, source_node):
visible.add(target_fqn)
levels.append(visible)
return levels
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, []):
+45 -29
View File
@@ -203,35 +203,45 @@ def extract_dart(path: Path) -> dict:
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)
def _consume_generic_args(text: str) -> tuple[str | None, str]:
if not text.strip().startswith("<"):
return None, text
start_idx = text.find("<")
depth = 1
i = start_idx + 1
while i < len(text) and depth > 0:
if text[i] == "<":
depth += 1
elif text[i] == ">":
depth -= 1
if depth == 0:
return text[start_idx + 1 : i], text[i + 1:]
i += 1
return None, text
# Parse extends or on. A mixin's `on` clause may list several
# superclass constraints, comma-separated (`mixin Foo on A, B {}`);
# `extends` never does, since Dart classes have single inheritance.
base_entries: list[tuple[str, str | None]] = []
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
is_on = extends_m.group(1) == "on"
base_class = extends_m.group(2)
header = header[extends_m.end():]
generics, header = _consume_generic_args(header)
base_entries.append((base_class, generics))
if is_on:
while True:
comma_m = re.match(r"\s*,\s*([a-zA-Z0-9_.]+)", header)
if not comma_m:
break
header = header[comma_m.end():]
extra_generics, header = _consume_generic_args(header)
base_entries.append((comma_m.group(1), extra_generics))
# Parse with
with_m = re.search(r"^\s*with\s+", header)
@@ -251,8 +261,8 @@ def extract_dart(path: Path) -> dict:
if impl_m:
interfaces_list = _split_types(header[impl_m.end():])
# Map extends inheritance relation
if base_class:
# Map extends/on inheritance relation(s)
for base_class, generics in base_entries:
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)
@@ -428,8 +438,14 @@ def extract_dart(path: Path) -> dict:
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+)"
# 3. Extensions (extension MyExt on MyClass, or the anonymous `extension on
# MyClass` form). The name and its generics sit in one optional group,
# together with the whitespace that follows them: splitting that
# whitespace into two separate `\s+` runs (one before the name, one
# before `on`) makes both demand at least one space of their own, which
# a single space between `extension` and `on` can never satisfy when the
# name is absent, so the anonymous form never matched at all.
ext_pattern = r"^\s{0,4}extension\s+(?:(\w+)\s*(?:<[^>]+>)?\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)
+24 -7
View File
@@ -327,9 +327,13 @@ def extract_elixir(path: Path) -> dict:
enclosing[func_nid] = parent_module_nid
if parent_module_nid:
add_edge(parent_module_nid, func_nid, "method", line)
module_defs.setdefault((parent_module_nid, func_name), func_nid)
else:
add_edge(file_nid, func_nid, "contains", line)
# Keyed by the def's own container (module, or the file for a
# top-level def) so a bare call can be resolved to the def that is
# actually in scope for its caller, never to an unrelated
# same-named def elsewhere in the file (see walk_calls below).
module_defs.setdefault((container, func_name), func_nid)
if do_block_node:
function_bodies.append((func_nid, do_block_node))
else:
@@ -359,11 +363,6 @@ def extract_elixir(path: Path) -> dict:
walk(root)
label_to_nid: dict[str, str] = {}
for n in nodes:
normalised = n["label"].strip("()").lstrip(".")
label_to_nid[normalised] = n["id"]
module_nid_by_name = {name: nid for nid, name in module_names.items()}
_MODULE_REF = re.compile(r"(__MODULE__|[A-Z]\w*)(\.[A-Z]\w*)*")
@@ -434,8 +433,26 @@ def extract_elixir(path: Path) -> dict:
if receiver_module is not None:
mod_nid = module_nid_by_name.get(receiver_module)
tgt_nid = module_defs.get((mod_nid, callee_name)) if mod_nid else None
elif is_member_call:
tgt_nid = None
else:
tgt_nid = None if is_member_call else label_to_nid.get(callee_name)
# A bare call only ever reaches a def that is actually in
# scope for this caller: its own module (or the file, for a
# top-level caller) first, then each module brought into
# scope by `import`/`use`. Without this a same-named def in
# an unrelated sibling module in the same file silently won
# over the caller's own def, since both shared one flat
# name -> id table.
own_container = enclosing.get(caller_nid) or file_nid
tgt_nid = module_defs.get((own_container, callee_name))
if tgt_nid is None:
for scope_name in _call_scope_for(caller_nid):
scope_nid = module_nid_by_name.get(scope_name)
if scope_nid is None:
continue
tgt_nid = module_defs.get((scope_nid, callee_name))
if tgt_nid is not None:
break
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
File diff suppressed because it is too large. Load diff
+26 -4
View File
@@ -237,14 +237,23 @@ def extract_fortran(path: Path) -> dict:
t = node.type
if t in ("subroutine", "function", "module", "program", "internal_procedures"):
return
# call FOO(args) — tree-sitter-fortran uses subroutine_call
# call FOO(args) — tree-sitter-fortran uses subroutine_call. Unlike
# call_expression below, `call` is unambiguous: there is no array-index
# reading, so a callee defined in another file (reached through its own
# `use` statement) is resolved the same way a cross-file parameter/return
# type already is, through a sourceless stub the corpus rewire can
# collapse onto the real definition. Computing the target id directly
# (the previous behaviour) always salted it with THIS file's own stem,
# so a cross-file call target never matched the callee's real node and
# dangled permanently.
if t == "subroutine_call":
name_node = next((c for c in node.children if c.type == "identifier"), None)
if name_node:
callee = _read_text(name_node, source).lower()
target_nid = _make_id(stem, callee)
add_edge(scope_nid, target_nid, "calls", node.start_point[0] + 1,
confidence="EXTRACTED", context="call")
target_nid = ensure_named_node(callee, node.start_point[0] + 1)
if target_nid != scope_nid:
add_edge(scope_nid, target_nid, "calls", node.start_point[0] + 1,
confidence="EXTRACTED", context="call")
# x = compute(args) — function invocations are `call_expression`, which
# shares Fortran's `name(...)` syntax with array indexing. Only emit a
# call edge when the callee resolves to a procedure defined in this file
@@ -305,6 +314,19 @@ def extract_fortran(path: Path) -> dict:
line = node.start_point[0] + 1
add_node(type_nid, type_name, line)
add_edge(scope_nid, type_nid, "defines", line)
# `type, extends(base) :: derived` is Fortran's derived-type
# inheritance syntax (the `type :: name` bare form has no base).
# Without this, every extends() clause was silently dropped and
# Fortran OOP hierarchies never got an inherits edge, unlike every
# other OOP language extractor.
base_spec = next((c for c in stmt.children if c.type == "base_type_specifier"), None)
if base_spec is not None:
base_name_node = next((c for c in base_spec.children if c.type == "identifier"), None)
if base_name_node is not None:
base_name = _read_text(base_name_node, source).lower()
base_nid = ensure_named_node(base_name, line)
if base_nid != type_nid:
add_edge(type_nid, base_nid, "inherits", line)
# Type-bound procedures in the `contains` section bind the
# derived type to the module procedures that implement its
# methods. Without this the binding was dropped and the type
+321 -58
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
from pathlib import Path
from graphify.ids import DeclIdRegistry
from graphify.extractors.base import (
_LANGUAGE_BUILTIN_GLOBALS,
_file_stem,
@@ -11,6 +12,7 @@ from graphify.extractors.base import (
_read_source_bytes,
_read_text,
)
from graphify.extractors.resolution import _go_import_path_for_file
_GO_PREDECLARED_TYPES = frozenset({
@@ -48,6 +50,28 @@ _GO_PREDECLARED_FUNCS = frozenset({
"recover",
})
# The tree-sitter-go nodes a type argument parses as (`new(T)`, `make([]pkg.T, n)`);
# an ordinary argument is an expression and never one of these.
_GO_TYPE_NODES = frozenset({
"type_identifier", "qualified_type", "pointer_type", "generic_type", "slice_type",
"array_type", "map_type", "channel_type", "parenthesized_type",
})
def _go_alias_re_exports(alias_node, source: bytes) -> bool:
"""Whether `type A = pkg.A` (or `pkg.A[...]`) re-exports another package's type
under its own name. Such an alias denotes that very type and declares no new
name, so it gets no node: references to `A` keep resolving to the original
instead of tying between the two. Any other alias introduces a name."""
target = alias_node.child_by_field_name("type")
if target is not None and target.type == "generic_type":
target = target.child_by_field_name("type")
if target is None or target.type != "qualified_type":
return False
name, target_name = alias_node.child_by_field_name("name"), target.child_by_field_name("name")
return (name is not None and target_name is not None
and _read_text(name, source) == _read_text(target_name, source))
def _go_type_param_names(decl_node, source: bytes) -> frozenset[str]:
"""Names bound by a declaration's generic type parameters.
@@ -152,55 +176,135 @@ def _go_strip_generic_args(type_text: str) -> str:
def _go_single_type_name(node, source: bytes) -> str | None:
"""The one declared type a Go type expression names, or None.
Only `Greeter` and `*Greeter` qualify. A slice, map or channel element is not the
receiver of `x.M()`, and a `qualified_type` (`pkg.Greeter`) names a type no bare
local name can stand for.
`Greeter`, `*Greeter`, `pkg.Greeter` and `*pkg.Greeter` qualify, and generic
arguments do not change the receiver's base type. A slice, map or channel
element is not the receiver of `x.M()`. A qualified type keeps its package
qualifier as written (`pkg.Greeter`): no bare local name can stand for it, so
the resolver binds it only through the file's import of `pkg`.
"""
if node is not None and node.type == "pointer_type":
node = next((c for c in node.children if c.is_named), None)
while node is not None and node.type in ("pointer_type", "parenthesized_type", "generic_type"):
node = node.child_by_field_name("type") or next(
(c for c in node.children if c.is_named), None,
)
if node is not None and node.type == "qualified_type":
package = node.child_by_field_name("package")
name_node = node.child_by_field_name("name")
if package is None or name_node is None:
return None
return f"{_read_text(package, source)}.{_read_text(name_node, source)}"
if node is None or node.type != "type_identifier":
return None
name = _read_text(node, source)
return name if name and name not in _GO_PREDECLARED_TYPES else None
def _go_receiver_type_table(root, source: bytes) -> dict[str, str]:
"""Collect ``name -> TypeName`` for every Go receiver whose type is written down.
def _go_inferred_composite_bindings(names, values, source: bytes):
"""Pair same-position declared names with composite-literal values.
Four sources: a struct field, a parameter (which covers the method receiver
`func (s *Server)`), `var x T`, and `x := T{}` / `x := &T{}`. Flat over the subtree it is
given, first binding wins — run over one function it is that function's own scope, and
over the file it is the fallback for a struct field. Children are pushed reversed so the
walk yields document order and "first" means first in the source.
Shared by `x := T{}` (`short_var_declaration`) and `var x = T{}` (a
type-less `var_spec`): both bind a name to the type of a same-position
`T{}` / `&T{}` value. Yields (name text, inferred type) for each pair
that is in fact a composite literal.
"""
table: dict[str, str] = {}
for name_node, value in zip(names, values):
if value.type == "unary_expression":
value = value.child_by_field_name("operand") or value
if value.type != "composite_literal":
continue
type_name = _go_single_type_name(value.child_by_field_name("type"), source)
if type_name:
yield _read_text(name_node, source), type_name
def _go_receiver_type_table(
root, source: bytes, *, package_only: bool = False,
) -> dict[str, str | None]:
"""Collect declared or composite-literal receiver types, preserving unknown bindings.
Unknown local bindings shadow package variables. Package-only tables exclude
fields and function bodies so unrelated scopes cannot supply a receiver type.
"""
table: dict[str, str | None] = {}
stack = [root]
while stack:
n = stack.pop()
t = n.type
if t in ("field_declaration", "parameter_declaration", "var_spec"):
type_name = _go_single_type_name(n.child_by_field_name("type"), source)
for c in n.children if type_name else ():
if c.type in ("field_identifier", "identifier"):
table.setdefault(_read_text(c, source), type_name)
if t == "block" or (t == "func_literal" and n != root):
continue
if package_only and t in (
"function_declaration", "method_declaration", "func_literal", "type_declaration",
):
continue
if t in (
"field_declaration", "parameter_declaration",
"variadic_parameter_declaration", "var_spec",
):
names = [c for c in n.children if c.type in ("field_identifier", "identifier")]
type_name = (None if t == "variadic_parameter_declaration"
else _go_single_type_name(n.child_by_field_name("type"), source))
inferred = {}
if t == "var_spec" and not type_name:
value = n.child_by_field_name("value")
if value is not None:
inferred = dict(_go_inferred_composite_bindings(
names, [c for c in value.children if c.is_named], source,
))
for name_node in names:
name = _read_text(name_node, source)
table.setdefault(name, type_name or inferred.get(name))
elif t == "short_var_declaration":
left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
if left is not None and right is not None:
names = [c for c in left.children if c.type == "identifier"]
values = [c for c in right.children if c.is_named]
for name_node, value in zip(names, values):
if value.type == "unary_expression":
value = value.child_by_field_name("operand") or value
if value.type != "composite_literal":
continue
type_name = _go_single_type_name(
value.child_by_field_name("type"), source)
if type_name:
table.setdefault(_read_text(name_node, source), type_name)
inferred = dict(_go_inferred_composite_bindings(names, values, source))
for name_node in names:
name = _read_text(name_node, source)
table.setdefault(name, inferred.get(name))
elif t == "range_clause" and any(c.type == ":=" for c in n.children):
left = n.child_by_field_name("left")
for name_node in left.named_children if left is not None else ():
if name_node.type == "identifier":
table.setdefault(_read_text(name_node, source), None)
stack.extend(reversed(n.children))
return table
def _go_struct_field_types(root, source: bytes) -> dict[str, dict[str, str]]:
"""``struct name -> {field name -> TypeName}`` for every struct this file declares.
Only a named field whose type `_go_single_type_name` accepts is kept, the same rule
the flat receiver table applies. Unlike that table it stays keyed by the struct, so a
method in another file of the package can read the fields of its own receiver.
"""
fields_by_struct: dict[str, dict[str, str]] = {}
stack = [root]
while stack:
n = stack.pop()
if n.type in ("function_declaration", "method_declaration"):
continue
if n.type == "type_spec":
name_node = n.child_by_field_name("name")
body = n.child_by_field_name("type")
if name_node is not None and body is not None and body.type == "struct_type":
fields: dict[str, str] = {}
for fdl in body.children:
if fdl.type != "field_declaration_list":
continue
for field in fdl.children:
if field.type != "field_declaration":
continue
type_name = _go_single_type_name(field.child_by_field_name("type"), source)
for c in field.children if type_name else ():
if c.type == "field_identifier":
fields.setdefault(_read_text(c, source), type_name)
if fields:
fields_by_struct[_read_text(name_node, source)] = fields
continue
stack.extend(n.children)
return fields_by_struct
def extract_go(path: Path) -> dict:
"""Extract functions, methods, type declarations, and imports from a .go file."""
try:
@@ -226,15 +330,17 @@ def extract_go(path: Path) -> dict:
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
# `(caller nid, body, receiver variable name, receiver type, own-scope types)` — the
# receiver name is what makes `s.logger.Log()` readable as a call on the `logger` field
# rather than on `s`, and the scope types are the bindings the file-flat table can get
# wrong: every function in a file is free to name a parameter `s` after its own type.
function_bodies: list[tuple[str, object, str | None, str | None, dict[str, str]]] = []
# The receiver name identifies `s.field` as an owned field; scope bindings keep
# parameters and locals distinct from package variables, even with unknown types.
function_bodies: list[tuple[str, object, str | None, str | None, dict[str, str | None]]] = []
# Fed to the `_callable` / `_callable_class` stamp below (#2438): the indirect-call
# guard and the cross-repo member-call pass both read them off the node.
callable_nids: set[str] = set()
callable_class_nids: set[str] = set()
# Go interfaces are satisfied implicitly, so nothing else in the output tells an
# interface's method requirements from a struct's methods; `graphify.go_dispatch`
# reads this stamp to know which owners are interfaces.
interface_nids: set[str] = set()
# local package name (including aliases) -> written Go import path
go_imported_pkgs: dict[str, str] = {}
@@ -267,6 +373,7 @@ def extract_go(path: Path) -> dict:
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
decl_registry = DeclIdRegistry(reserved_ids=(file_nid,))
def ensure_named_node(name: str, line: int) -> str:
nid = type_symbol_nid(name)
@@ -340,6 +447,33 @@ def extract_go(path: Path) -> dict:
if tgt != func_nid:
add_edge(func_nid, tgt, "references", line, context=ctx)
def emit_go_package_var_type_refs(var_decl) -> None:
# The types a package-level `var` names, in its declared type (`var x T`), a
# composite literal (`pkg.T{}`, `&T{}`) or a type argument (`new(*pkg.T)`,
# `make(map[K]V)`), are referenced by the file, which owns the initialiser
# (#2360). Without this a file holding only a dependency-injection set
# (`wire.Bind(new(Iface), new(*Impl))`) referenced nothing. A closure body is
# function code and is left to the call walk.
stack = [var_decl]
while stack:
n = stack.pop()
if n.type == "func_literal":
continue
type_nodes = []
if n.type in ("var_spec", "composite_literal"):
type_nodes.append(n.child_by_field_name("type"))
elif n.type == "argument_list":
type_nodes.extend(c for c in n.children if c.type in _GO_TYPE_NODES)
for type_node in type_nodes:
refs: list[tuple[str, str]] = []
_go_collect_type_refs(type_node, source, False, refs)
for ref_name, role in refs:
ctx = "generic_arg" if role == "generic_arg" else "variable_type"
line = type_node.start_point[0] + 1
add_edge(file_nid, ensure_named_node(ref_name, line), "references",
line, context=ctx)
stack.extend(c for c in n.children if c not in type_nodes)
# Node IDs are casefolded (ids.py), so `Run` and `run` declared in one file
# produce the same id and add_node silently dropped the second — the unexported
# half vanished from the graph and its call sites bound by bare name to a
@@ -393,8 +527,11 @@ def extract_go(path: Path) -> dict:
def _scan_type_names(node) -> None:
# Types first: a method is keyed under its owner's final id, which is
# salted when the owner's own name collides.
if node.type == "type_spec":
# salted when the owner's own name collides. An alias (`type A = B`) is a
# `type_alias`, not a `type_spec`, and declares a type name all the same.
if node.type == "type_spec" or (
node.type == "type_alias" and not _go_alias_re_exports(node, source)
):
name_node = node.child_by_field_name("name")
if name_node is not None:
name = _read_text(name_node, source)
@@ -428,21 +565,20 @@ def extract_go(path: Path) -> dict:
for child in node.children:
_scan_declarations(child)
def symbol_nid(plain_nid: str, name: str) -> str:
def symbol_nid(plain_nid: str, name: str, kind: str = "fn") -> str:
nid = plain_nid
names = case_groups.get(plain_nid) or set()
if len(names) < 2:
return plain_nid
exported = [n for n in names if n[:1].isupper()]
if len(exported) == 1 and name == exported[0]:
return plain_nid
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
return _make_id(plain_nid, salt)
if len(names) >= 2 and not (len([n for n in names if n[:1].isupper()]) == 1
and name == [n for n in names if n[:1].isupper()][0]):
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
nid = _make_id(plain_nid, salt)
return decl_registry.resolve(nid, name, kind, seen_ids)
def type_symbol_nid(name: str) -> str:
plain_nid = _make_id(pkg_scope, name)
if name not in case_groups.get(plain_nid, ()):
return plain_nid
return symbol_nid(plain_nid, name)
return decl_registry.resolve(plain_nid, name, "type", seen_ids)
return symbol_nid(plain_nid, name, "type")
def walk(node) -> None:
t = node.type
@@ -509,7 +645,9 @@ def extract_go(path: Path) -> dict:
if t == "type_declaration":
for child in node.children:
if child.type != "type_spec":
if child.type not in ("type_spec", "type_alias"):
continue
if child.type == "type_alias" and _go_alias_re_exports(child, source):
continue
name_node = child.child_by_field_name("name")
if not name_node:
@@ -520,6 +658,11 @@ def extract_go(path: Path) -> dict:
add_node(type_nid, type_name, line)
callable_class_nids.add(type_nid)
add_edge(file_nid, type_nid, "contains", line)
if child.type == "type_alias":
# `type A = B` is a declaration like `type A B`: references to
# it land here instead of minting a sourceless stub. Its
# right-hand side is not walked.
continue
# A generic type's own parameters (`type Box[T any]`) are local
# bindings; a field or method using `T` must not mint a stub.
type_params = _go_type_param_names(child, source)
@@ -561,6 +704,7 @@ def extract_go(path: Path) -> dict:
add_edge(type_nid, tgt, "references",
field.start_point[0] + 1, context=ctx)
elif type_body.type == "interface_type":
interface_nids.add(type_nid)
for elem in type_body.children:
if elem.type == "method_elem":
# A method requirement declared in the interface body
@@ -615,6 +759,17 @@ def extract_go(path: Path) -> dict:
elem.start_point[0] + 1, context="generic_arg")
return
if t == "var_declaration" and node.parent is not None and node.parent.type == "source_file":
# A package-level `var` initialiser runs at package init and has no enclosing
# function, so its calls, including those inside a `var f = func() {...}`
# closure, are credited to the file, the owner a module-level call already
# gets elsewhere. Without this they were never walked and the callee lost the
# caller (#2360).
emit_go_package_var_type_refs(node)
function_bodies.append(
(file_nid, node, None, None, _go_receiver_type_table(node, source)))
return
if t == "import_declaration":
for child in node.children:
if child.type == "import_spec_list":
@@ -652,17 +807,51 @@ def extract_go(path: Path) -> dict:
walk(root)
# A type carries both markers, as in the tree-sitter engine: `_callable_class` is
# the narrowing, not a separate kind.
# the narrowing, not a separate kind. A type also carries its import path from go.mod:
# a `pkg.T` receiver binds only to a `T` declared at the path the caller imports `pkg`
# from, and on an incremental rebuild an unchanged declaring file reaches the resolver
# only as its nodes.
package_path = _go_import_path_for_file(path.absolute(), path.absolute().parent)
for n in nodes:
if n["id"] in callable_nids or n["id"] in callable_class_nids:
n["_callable"] = True
if n["id"] in callable_class_nids:
n["_callable_class"] = True
if package_path:
n["_go_package_path"] = package_path
if n["id"] in interface_nids:
n["metadata"] = {"language": "go", "kind": "interface"}
# The field types of the structs this file declares ride on the file node, keyed by
# struct id, so a method in a sibling file can type `s.field` (#3368). Not on the
# struct node: every file holding a method of the struct emits that id too, so an
# incremental rebuild of a method file would shadow the declaring file's copy.
# A `pkg.T` field is stored as `<import path>.T`: the method file reading it may not
# import `pkg` at all, so the qualifier is settled by this file's imports.
struct_fields: dict[str, dict[str, str]] = {}
for name, fields in _go_struct_field_types(root, source).items():
typed: dict[str, str] = {}
for field, type_name in fields.items():
alias, dot, bare = type_name.partition(".")
if not dot:
typed[field] = type_name
elif alias in go_imported_pkgs:
typed[field] = f"{go_imported_pkgs[alias]}.{bare}"
if typed:
struct_fields[type_symbol_nid(name)] = dict(sorted(typed.items()))
if struct_fields:
file_node = next(n for n in nodes if n["id"] == file_nid)
file_node["_go_fields"] = dict(sorted(struct_fields.items()))
type_table = _go_receiver_type_table(root, source)
package_types = _go_receiver_type_table(root, source, package_only=True)
local_type_names = {n["label"] for n in nodes if n["id"] in callable_class_nids}
method_nids = {e["target"] for e in edges if e["relation"] == "method"}
label_to_nid: dict[str, str] = {}
for n in nodes:
if n["id"] in method_nids:
continue
raw = n["label"]
normalised = raw.strip("()").lstrip(".")
label_to_nid[normalised] = n["id"]
@@ -671,9 +860,17 @@ def extract_go(path: Path) -> dict:
raw_calls: list[dict] = []
def walk_calls(node, caller_nid: str, self_name: str | None,
self_type: str | None, scope_types: dict[str, str]) -> None:
self_type: str | None, scope_types: dict[str, str | None]) -> None:
if node.type in ("function_declaration", "method_declaration"):
return
if node.type in (
"block", "if_statement", "for_statement", "expression_switch_statement",
"type_switch_statement", "select_statement", "expression_case", "type_case",
"communication_case", "default_case", "func_literal",
):
scope_types = scope_types.copy()
if node.type == "func_literal":
scope_types.update(_go_receiver_type_table(node, source))
if node.type == "call_expression":
func_node = node.child_by_field_name("function")
callee_name: str | None = None
@@ -682,6 +879,7 @@ def extract_go(path: Path) -> dict:
package_receiver: str | None = None
member_receiver: str | None = None
member_receiver_type: str | None = None
field_owner: str | None = None
import_path: str | None = None
if func_node:
if func_node.type == "identifier":
@@ -699,19 +897,32 @@ def extract_go(path: Path) -> dict:
import_path = go_imported_pkgs[receiver_name]
elif operand is not None and operand.type == "identifier":
member_receiver = receiver_name
if self_name and receiver_name == self_name:
member_receiver_type = self_type
else:
member_receiver_type = scope_types.get(receiver_name)
member_receiver_type = scope_types.get(receiver_name)
if receiver_name not in scope_types and receiver_name in local_type_names:
member_receiver_type = receiver_name
elif operand is not None and operand.type == "parenthesized_expression":
expression = operand
while (expression.type == "parenthesized_expression"
and expression.named_children):
expression = expression.named_children[0]
if (expression.type == "unary_expression"
and _read_text(expression, source).startswith("*")):
expression = expression.child_by_field_name("operand")
name = _read_text(expression, source) if expression is not None else ""
if name in local_type_names and name not in scope_types:
member_receiver = name
member_receiver_type = name
elif operand is not None and operand.type == "selector_expression":
# `s.logger.Log()` names the receiver by the field only when `s` is
# this method's own receiver; any other head could be a package or
# a variable whose type the flat table does not know.
inner = operand.child_by_field_name("operand")
if (self_name and inner is not None and inner.type == "identifier"
and _read_text(inner, source) == self_name):
and _read_text(inner, source) == self_name
and scope_types.get(self_name) == self_type):
member_receiver = _read_text(
operand.child_by_field_name("field"), source)
field_owner = self_type
if field:
callee_name = _read_text(field, source)
if is_bare_identifier and callee_name in _GO_PREDECLARED_FUNCS:
@@ -721,8 +932,9 @@ def extract_go(path: Path) -> dict:
# of raw_calls, so the cross-file pass cannot bind it either.
callee_name = None
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
# Never resolve an imported selector through a bare local name.
tgt_nid = None if import_path else label_to_nid.get(callee_name)
# 成员调用必须按接收者类型解析;裸名不能证明方法属于该接收者。
tgt_nid = (None if import_path or is_member_call
else 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:
@@ -750,16 +962,67 @@ def extract_go(path: Path) -> dict:
# `is_member_call` plus `receiver` without checking the language,
# so a Go name placed there binds to their types in a mixed corpus.
"member_receiver": member_receiver,
# The enclosing function's own receiver and parameters/locals, whose
# declarations are in scope here; the flat table is the fallback for
# a struct field, and must not answer a name this scope rebinds.
"receiver_type": member_receiver_type,
"receiver_bound": not field_owner and member_receiver in scope_types,
# Field ownership remains explicit when the struct is declared
# in a sibling file of the package.
"field_owner": field_owner,
"import_path": import_path,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
# A method value passed as an argument (`routing.Wrap(s.Handle)`,
# `r.Get("/p", s.Handle)`) is how Go registers a handler or callback. It is
# not a call here, so it never reached the branch above and the method had
# no caller. Record it for the member-call resolver as an indirect call
# through the receiver's declared type (#1566). `s.field.Handle` is typed
# through the field, as a direct `s.field.M()` is, only when `s` is this
# method's own receiver.
args = node.child_by_field_name("arguments")
for arg in args.children if args is not None else ():
if arg.type != "selector_expression":
continue
operand = arg.child_by_field_name("operand")
field = arg.child_by_field_name("field")
if operand is None or field is None:
continue
arg_field_owner: str | None = None
if operand.type == "identifier":
name = _read_text(operand, source)
if name in go_imported_pkgs:
continue
arg_receiver_type = scope_types.get(name)
elif operand.type == "selector_expression":
inner = operand.child_by_field_name("operand")
if not (self_name and inner is not None and inner.type == "identifier"
and _read_text(inner, source) == self_name
and scope_types.get(self_name) == self_type):
continue
name = _read_text(operand.child_by_field_name("field"), source)
arg_receiver_type = None
arg_field_owner = self_type
else:
continue
raw_calls.append({
"caller_nid": caller_nid,
"callee": _read_text(field, source),
"is_member_call": True,
"indirect": True,
"context": "argument",
"language": "go",
"receiver": None,
"member_receiver": name,
"receiver_type": arg_receiver_type,
"receiver_bound": name in scope_types if not arg_field_owner else False,
"field_owner": arg_field_owner,
"import_path": None,
"source_file": str_path,
"source_location": f"L{arg.start_point[0] + 1}",
})
for child in node.children:
walk_calls(child, caller_nid, self_name, self_type, scope_types)
if child.type in ("short_var_declaration", "var_spec", "range_clause"):
scope_types.update(_go_receiver_type_table(child, source))
for caller_nid, body_node, self_name, self_type, scope_types in function_bodies:
walk_calls(body_node, caller_nid, self_name, self_type, scope_types)
@@ -776,5 +1039,5 @@ def extract_go(path: Path) -> dict:
"edges": clean_edges,
"raw_calls": raw_calls,
"go_imports": dict(go_imported_pkgs),
"go_type_table": {"path": str_path, "table": type_table},
"go_type_table": {"path": str_path, "table": type_table, "package_vars": package_types},
}
+25 -1
View File
@@ -234,7 +234,7 @@ def extract_json(path: Path) -> dict:
if ref_nid:
add_edge(parent_nid, ref_nid, "references", line)
elif parent_key in _DEP_KEYS and val_text:
elif parent_key in _DEP_KEYS and val_text.strip():
# Two defects fixed here, both from the #1764 shape:
#
# 1. The edge ran `key_nid -> dep_nid`, and both nodes carry
@@ -253,10 +253,34 @@ def extract_json(path: Path) -> dict:
# `types` could then be collapsed onto a same-named local
# module by build.py's alias index -- the #1638 failure
# mode reached through a different door.
#
# 3. Moving that edge to the manifest also cut the only link between the
# dependency's key node (its manifest entry, reached through
# `dependencies --contains-->`) and its ref node, so the entry and
# the code that imports the package landed in different communities
# (#4569). `key_nid --declares--> dep_nid` reconnects them, and the
# entry is relabelled `name@range` so the two nodes no longer share a
# label: a same-label edge is the `react -> react` view #1764
# removed, and two `react` nodes made `explain`/`affected`
# ambiguous. The ref node keeps the bare name, which is what
# `import "react"` resolves to. The range is one line, capped at 40
# characters; a blank one links nothing (like an empty one) and the
# entry keeps its bare name.
dep_nid = _make_id("ref", key)
if dep_nid:
add_node(dep_nid, key, line, file_type="concept")
add_edge(file_nid, dep_nid, "imports", line, context="import")
add_edge(key_nid, dep_nid, "declares", line)
version = " ".join(val_text.split())
if len(version) > 40:
version = version[:37] + "..."
# `add_node` kept the first node under this id (the same key under
# two sibling blocks shares it), so relabel only the pair that
# node's line belongs to: label and line then name one entry.
for node in nodes:
if node["id"] == key_nid and node["source_location"] == f"L{line}":
node["label"] = f"{key}@{version}"
break
# Entry: find root document → object
doc = root
+11 -6
View File
@@ -1,6 +1,7 @@
"""julia — moved verbatim from graphify/extract.py."""
from __future__ import annotations
from graphify.ids import DeclIdRegistry
from graphify.extractors.base import _file_stem, _make_id, _read_source_bytes, _read_text
from graphify.extractors.engine import _semantic_reference_edge
from pathlib import Path
@@ -59,6 +60,10 @@ def extract_julia(path: Path) -> dict:
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
decl_registry = DeclIdRegistry(reserved_ids=(file_nid,))
def decl_id(nid: str, name: str, kind: str) -> str:
return decl_registry.resolve(nid, name, kind, seen_ids)
def ensure_named_node(name: str, line: int) -> str:
nid = _make_id(stem, name)
@@ -274,7 +279,7 @@ def extract_julia(path: Path) -> dict:
name_node = next((c for c in node.children if c.type == "identifier"), None)
if name_node:
mod_name = _read_text(name_node, source)
mod_nid = _make_id(stem, mod_name)
mod_nid = decl_id(_make_id(stem, mod_name), mod_name, "ns")
line = node.start_point[0] + 1
add_node(mod_nid, mod_name, line)
add_edge(file_nid, mod_nid, "defines", line)
@@ -291,7 +296,7 @@ def extract_julia(path: Path) -> dict:
struct_name, super_name = _type_head_names(type_head)
if not struct_name:
return
struct_nid = _make_id(stem, struct_name)
struct_nid = decl_id(_make_id(stem, struct_name), struct_name, "type")
line = node.start_point[0] + 1
add_node(struct_nid, struct_name, line)
add_edge(scope_nid, struct_nid, "defines", line)
@@ -324,7 +329,7 @@ def extract_julia(path: Path) -> dict:
if type_head:
abs_name, super_name = _type_head_names(type_head)
if abs_name:
abs_nid = _make_id(stem, abs_name)
abs_nid = decl_id(_make_id(stem, abs_name), abs_name, "type")
line = node.start_point[0] + 1
add_node(abs_nid, abs_name, line)
add_edge(scope_nid, abs_nid, "defines", line)
@@ -340,7 +345,7 @@ def extract_julia(path: Path) -> dict:
named = _func_name_from_signature(sig_node)
if named:
func_name, label = named
func_nid = _make_id(stem, func_name)
func_nid = decl_id(_make_id(stem, func_name), func_name, "fn")
line = node.start_point[0] + 1
add_node(func_nid, f"{label}()", line)
add_edge(scope_nid, func_nid, "defines", line)
@@ -405,7 +410,7 @@ def extract_julia(path: Path) -> dict:
if type_node is not None:
enum_name = _read_text(type_node, source)
line = node.start_point[0] + 1
enum_nid = _make_id(stem, enum_name)
enum_nid = decl_id(_make_id(stem, enum_name), enum_name, "type")
add_node(enum_nid, enum_name, line)
add_edge(scope_nid, enum_nid, "defines", line)
for member in arg_nodes[1:]:
@@ -430,7 +435,7 @@ def extract_julia(path: Path) -> dict:
named = _def_name(_unwrap_call_expression(lhs))
if named:
func_name, label = named
func_nid = _make_id(stem, func_name)
func_nid = decl_id(_make_id(stem, func_name), func_name, "fn")
line = node.start_point[0] + 1
add_node(func_nid, f"{label}()", line)
add_edge(scope_nid, func_nid, "defines", line)
+251 -59
View File
@@ -26,16 +26,29 @@ _MD_INLINE_LINK_RE = re.compile(
r')\)')
_MD_REF_DEF_RE = re.compile(
r'^\s{0,3}\[[^\]]+\]:\s*(?:<([^<>\n]+)>(?=\s*(?:["\'(]|$))|<?([^\s>]+)>?)')
r'^\s{0,3}\[([^\]]+)\]:\s*(?:<([^<>\n]+)>(?=\s*(?:["\'(]|$))|<?([^\s>]+)>?)')
# Reference-style link uses: [text][label] or [label][]. The label resolves to
# a separate definition (`[label]: target`), so the use — not the definition —
# carries the citation evidence for its section (#4804).
_MD_REF_LINK_RE = re.compile(r'(?<!\!)\[([^\]]*)\]\[([^\]]*)\]')
_MD_WIKILINK_RE = re.compile(r'(?<!\!)\[\[([^\]|#]+?)(?:\\?\|[^\]]*|#[^\]]*)?\]\]')
# Document extensions a Markdown link may point at for a `references` edge, and
# the extensions the Obsidian wikilink index covers.
_MD_LINKABLE_EXTS = {".md", ".mdx", ".qmd", ".markdown", ".rst", ".txt"}
# Source files can be linked as citations and resolved to references edges (#4804).
_MD_CITEABLE_EXTS = _MD_LINKABLE_EXTS | CODE_EXTENSIONS
# Inline code spans, single or double backtick delimited. Fenced blocks are
# skipped before this runs, so a span here is prose citing a symbol by name.
_MD_CODE_SPAN_RE = re.compile(r'(?<!`)(`+)(?!`)(.+?)(?<!`)\1(?!`)')
# A code span naming a file path (e.g. `graphify/build.py`, `setup.py`).
_MD_FILE_SPAN_RE = re.compile(r'^([A-Za-z0-9_./\-]+\.([A-Za-z0-9]+))$')
# The two mention grammars a code span can carry. A path-qualified mention
# (``src/pkg/mod.py::Widget::render``) names the defining file and a
# ``::``-separated symbol chain, exactly as pytest node ids and cite-lint
@@ -48,6 +61,58 @@ _MD_PATH_MENTION_RE = re.compile(
_MD_BARE_MENTION_RE = re.compile(
r'^(?:[A-Za-z_]\w*\.)*([A-Za-z_]\w*)(?:\(\))?$'
)
# The namespace/member chain the other languages' docs write: ``App\Services\Mailer``
# (PHP namespaces) and ``Mailer::send()`` (PHP, Rust, C++ type-qualified members).
# Each segment is a plain identifier; the separators are ``\`` and ``::`` (#4610).
_MD_NS_MENTION_RE = re.compile(
r'^[A-Za-z_]\w*(?:(?:::|\\)[A-Za-z_]\w*)+(?:\(\))?$'
)
# ``Foo::CONST`` names a constant and ``Foo::class`` a keyword: neither has a
# node to land on, so the chain is not a mention.
_MD_NS_NON_SYMBOL_RE = re.compile(r'^(?:class|[A-Z][A-Z0-9_]*)$')
# An ATX heading (CommonMark): up to three spaces of indent (four is an indented
# code block), 1-6 `#`, then whitespace and the text. An optional closing run of
# `#` preceded by whitespace is not part of the text: `## Setup ##` is "Setup",
# while `## C#` and `## Trailing \#` keep their `#`.
_MD_ATX_HEADING_RE = re.compile(r'^ {0,3}(#{1,6})[ \t]+(.+)$')
_MD_ATX_CLOSING_RE = re.compile(r'(?:^|[ \t]+)#+[ \t]*$')
# A fenced code block line: a run of 3+ backticks or 3+ tildes, then the rest of
# the line (an info string on an opener). Leading whitespace is accepted at any
# depth, as before, so a fence inside a nested list item still counts.
_MD_FENCE_RE = re.compile(r'^\s*(`{3,}|~{3,})(.*)$')
def _fence_open(line: str) -> "tuple[str, int] | None":
"""(fence char, run length) when ``line`` opens a fenced code block.
CommonMark: a backtick fence's info string may not contain a backtick, so
a line that starts with an inline ```` ```code``` ```` span is prose, not a
fence. Tilde fences have no such restriction.
"""
m = _MD_FENCE_RE.match(line)
if not m:
return None
run, rest = m.group(1), m.group(2)
if run[0] == "`" and "`" in rest:
return None
return run[0], len(run)
def _fence_closes(line: str, fence: "tuple[str, int]") -> bool:
"""True when ``line`` closes the block opened by ``fence``.
CommonMark: the closing run uses the opener's character, is at least as
long, and carries nothing but whitespace after it. So ``` does not close a
~~~ block, ``` does not close a ```` block (the usual way a doc shows a
fenced example), and ``` followed by text is content.
"""
m = _MD_FENCE_RE.match(line)
if not m:
return False
run, rest = m.group(1), m.group(2)
return run[0] == fence[0] and len(run) >= fence[1] and not rest.strip()
# A YAML frontmatter block is only frontmatter when the opening `---` is the
# very first line of the file. A `---` further down is a horizontal rule and
@@ -257,14 +322,20 @@ def _is_external_link(target: str) -> bool:
def _resolve_markdown_link(raw: str, source_dir: Path,
wikilink: bool = False) -> "Path | None":
"""Resolve a markdown link target to the absolute path of a sibling document.
wikilink: bool = False,
exts: "set[str] | None" = None) -> "Path | None":
"""Resolve a markdown link target to the absolute path it names.
Returns the resolved (normalized, not necessarily existing) path when the
target is a *local* relative/absolute file-path link to a document, or None
when it should be skipped: external URLs (http/https/mailto/protocol-
relative/data), pure in-page anchors (``#section``), and links to non-doc
file types (code/assets are handled by their own extractors).
target is a *local* relative/absolute file-path link to a linkable file, or
None when it should be skipped: external URLs (http/https/mailto/protocol-
relative/data), pure in-page anchors (``#section``), and links to
unlinkable file types (assets, unknown extensions).
``exts`` is the set of linkable extensions; the default is document
extensions only. ``_MD_CITEABLE_EXTS`` additionally accepts source files,
which ``add_link`` turns into file citations (resolved to doc->file edges
at corpus time) rather than document edges.
The anchor fragment (``#section``) and query (``?x=1``) are stripped before
resolution so ``./repo.md#setup`` resolves to the same node as ``./repo.md``.
@@ -301,7 +372,8 @@ def _resolve_markdown_link(raw: str, source_dir: Path,
if suffix == "":
target = target + ".md"
suffix = ".md"
if suffix not in _MD_LINKABLE_EXTS:
linkable = _MD_LINKABLE_EXTS if exts is None else exts
if suffix not in linkable:
if not wikilink:
return None
# The suffix may be part of the note name ([[v1.2 release]]): try
@@ -334,16 +406,18 @@ def _resolve_markdown_link(raw: str, source_dir: Path,
return resolved
def _code_span_mention(span: str) -> "tuple[str | None, list[str]] | None":
"""Classify one inline code span as a symbol mention, or None.
"""Classify one inline code span as a symbol mention, file citation, or None.
Returns ``(path, names)``: ``path`` is the cited file for the
``path::Name`` form and None for a bare or dotted mention; ``names`` is the
symbol chain, outermost first, so ``pkg.sub.Widget`` yields
``["pkg", "sub", "Widget"]`` and the resolver can hold the match to that
evidence. A trailing ``()`` is dropped from the last name so ``render()``
and ``render`` cite the same symbol. Spans that read as a file
(``setup.py``, ``README.md``), a shell command, an expression or prose are
not mentions and yield None.
Returns ``(path, names)``:
- for a path-qualified mention (``src/mod.py::Widget::render``), ``path`` is
the cited file and ``names`` is the symbol chain;
- for a bare or dotted mention (``Widget``, ``pkg.Widget``), ``path`` is None
and ``names`` is the symbol chain;
- for a source-file span (``graphify/build.py``, ``setup.py``), ``path`` is
the file path and ``names`` is empty, so resolution can record it as file
evidence (#4804).
Spans that read as a shell command, an expression, a document name
(``README.md``) or prose yield None.
"""
text = span.strip()
if not text or " " in text:
@@ -351,19 +425,37 @@ def _code_span_mention(span: str) -> "tuple[str | None, list[str]] | None":
m = _MD_PATH_MENTION_RE.match(text)
if m:
return m.group(1), m.group(2).split("::")
if not text.endswith("()"):
fm = _MD_FILE_SPAN_RE.match(text)
if fm and "." + fm.group(2).lower() in CODE_EXTENSIONS:
return text, []
m = _MD_BARE_MENTION_RE.match(text)
if not m:
return None
if "." in text:
# ``a.b.Name`` is a qualified symbol; ``setup.py`` and ``README.md``
# are files. A dotted span whose last segment is a code or document
# extension is the latter. Other file-like spans (``pyproject.toml``)
# classify as a mention and are rejected at resolution, where the
# qualifier ``pyproject`` matches no callable's file or owner.
if "." + m.group(1) in CODE_EXTENSIONS or "." + m.group(1) in DOC_EXTENSIONS:
if m:
if "." in text:
# ``a.b.Name`` is a qualified symbol; ``setup.py`` is a source-file
# citation handled by _MD_FILE_SPAN_RE above (and re-caught here for a
# non-ASCII path). A document name (``README.md``) is not a mention:
# only code files are evidence for a bare mention. Other file-like
# spans (``pyproject.toml``) classify as a mention and are rejected at
# resolution, where the qualifier ``pyproject`` matches no callable.
if "." + m.group(1) in CODE_EXTENSIONS:
return text, []
if "." + m.group(1) in DOC_EXTENSIONS:
return None
return None, text.rstrip("()").split(".")
return None, [m.group(1)]
# ``App\Services\Mailer`` and ``Mailer::send()``: a namespace/member chain,
# split on ``\`` and ``::`` the way the dotted form splits on ``.``. A span
# that is only a namespace root (``App\``) is dropped: it names no symbol.
m = _MD_NS_MENTION_RE.match(text)
if m:
is_call = text.endswith("()")
body = text[:-2] if is_call else text
parts = re.split(r"::|\\", body)
if not is_call and body.endswith("::" + parts[-1]) and _MD_NS_NON_SYMBOL_RE.match(parts[-1]):
return None
return None, text.rstrip("()").split(".")
return None, [m.group(1)]
return None, parts
return None
def extract_markdown(path: Path) -> dict:
@@ -390,7 +482,9 @@ def extract_markdown(path: Path) -> dict:
instead of an under-connected orphan (#1376). The target node ID is built
from the resolved target path with the same recipe as the target file's
own node, so the edge merges into that node (no ghost node). External
URLs, in-page anchors, images and non-document targets are skipped.
URLs, in-page anchors, images and non-document targets are skipped; a
link that names a source file is not a document edge either, it is
recorded as a file citation (below).
Inline code spans on heading and body lines (backtick-quoted ``Widget``,
``render()``, ``pkg.Widget`` or ``src/mod.py::Widget::render``) are
@@ -403,12 +497,16 @@ def extract_markdown(path: Path) -> dict:
file path. That pass emits
heading --references--> code symbol (page --references--> symbol for a
mention above the first heading): EXTRACTED for the path-qualified form,
INFERRED for a bare name that matches exactly one code symbol. The shared
cross-file call pass skips these raw_calls, so a mention never becomes a
``calls`` edge.
INFERRED for a bare name that matches exactly one code symbol. A bare
free-function name whose label reads as prose (``token``, ``raw``) requires
evidence from its defining file in the citing section (#4804).
Source-file links are recorded as file citations and resolved at corpus time.
The shared cross-file call pass skips these raw_calls, so a mention never
becomes a ``calls`` edge.
Fenced code blocks (``` ... ```) are skipped during parsing so their
contents don't get treated as headings, but no node is emitted for
Fenced code blocks (``` ... ``` or ~~~ ... ~~~, closed by a run of the
same character at least as long, per CommonMark) are skipped during
parsing so their contents don't get treated as headings, but no node is emitted for
them — they were always orphans (only a single contains edge to the
parent doc) and inflated the disconnected-component count (#1077).
@@ -443,7 +541,7 @@ def extract_markdown(path: Path) -> dict:
seen_mentions.add(key)
raw_call = {
"caller_nid": caller_nid,
"callee": names[-1],
"callee": names[-1] if names else "",
"is_member_call": False,
"language": "markdown",
"context": span.strip(),
@@ -454,6 +552,12 @@ def extract_markdown(path: Path) -> dict:
raw_call["path"] = cited_path
if len(names) > 1:
raw_call["qualifiers"] = names[:-1]
if cited_path is None and _MD_NS_MENTION_RE.match(span.strip()):
# A `\`/`::` chain carries its namespace root as a qualifier the way
# a dotted mention does, but a PSR-4 root (`App\`) maps to the scan
# directory and has no path segment: the resolver may drop leading
# qualifiers a candidate cannot account for (#4610).
raw_call["ns_qualified"] = True
raw_calls.append(raw_call)
def add_node(nid: str, label: str, line: int, file_type: str = "document",
@@ -481,19 +585,76 @@ def extract_markdown(path: Path) -> dict:
fm_lines, body_start = _split_frontmatter(lines)
frontmatter = sanitize_metadata(_parse_frontmatter(fm_lines))
# Pre-scan reference definitions so a use can resolve to a definition that
# appears later in the document (#4804). Fenced code blocks are skipped.
ref_defs: dict[str, str] = {}
_in_fence = False
for _line in lines:
_stripped = _line.strip()
if _stripped.startswith("```"):
_in_fence = not _in_fence
continue
if _in_fence:
continue
_ref_def = _MD_REF_DEF_RE.match(_line)
if _ref_def:
_label = _ref_def.group(1)
_url = _ref_def.group(2) or _ref_def.group(3)
if _url:
ref_defs[_label] = _url
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1, node_kind="page",
extra={"frontmatter": frontmatter} if frontmatter else None)
source_dir = path.parent
def _is_code_file_link(raw: str, base: Path) -> bool:
"""Whether *raw* resolves to a source file (not a document or asset)."""
resolved = _resolve_markdown_link(raw, base, exts=_MD_CITEABLE_EXTS)
if resolved is None:
return False
suffix = resolved.suffix.lower()
return suffix in CODE_EXTENSIONS and suffix not in _MD_LINKABLE_EXTS
# Dedup link edges by resolved target node so a hub doc that links to the
# same sibling many times yields one edge, not N (keeps weights meaningful).
linked_targets: set[str] = set()
seeded_citations: set[tuple[str, str]] = set()
def add_link(raw: str, line: int, wikilink: bool = False) -> None:
resolved = _resolve_markdown_link(raw, source_dir, wikilink=wikilink)
def add_link(raw: str, line: int, owner: str = file_nid,
wikilink: bool = False) -> None:
resolved = _resolve_markdown_link(raw, source_dir, wikilink=wikilink,
exts=_MD_CITEABLE_EXTS)
if resolved is None:
return
suffix = resolved.suffix.lower()
if suffix in CODE_EXTENSIONS and suffix not in _MD_LINKABLE_EXTS:
# Record source file link as citation; resolver mints edge if scanned (#4804).
try:
cited = os.path.relpath(
str(resolved), str(source_dir)
).replace("\\", "/")
except ValueError: # different drives on Windows
cited = str(resolved).replace("\\", "/")
key = (owner, cited)
if key in seeded_citations:
return
seeded_citations.add(key)
raw_calls.append({
"caller_nid": file_nid,
"evidence_owner": owner,
"callee": "",
"is_member_call": False,
"language": "markdown",
"context": cited,
"source_file": str_path,
"source_location": f"L{line}",
"path": cited,
"file_link": True,
"wikilink": wikilink,
})
return
# Build the target ID with the SAME recipe as the target file's own
# node (_make_id(str(path)) at extract time, canonicalized to
# _file_node_id(rel) by the extract() post-pass). Using the absolute
@@ -521,44 +682,48 @@ def extract_markdown(path: Path) -> dict:
# Track heading stack for nesting: [(level, nid), ...]
heading_stack: list[tuple[int, str]] = []
in_code_block = False
fence: "tuple[str, int] | None" = None # (char, length) of the open fence
for line_num_0, line_text in enumerate(lines):
line_num = line_num_0 + 1
# Skip over fenced code blocks so their contents are not parsed as
# headings, but do not emit nodes/edges for them (#1077).
stripped = line_text.strip()
if stripped.startswith("```"):
in_code_block = not in_code_block
if fence is not None:
if _fence_closes(line_text, fence):
fence = None
continue
if in_code_block:
opened = _fence_open(line_text)
if opened is not None:
fence = opened
continue
# Markdown links -> document references (#1376). Scanned on every
# non-fenced line (including heading lines, which the heading branch
# below `continue`s past) so links anywhere in the doc are captured.
for m in _MD_INLINE_LINK_RE.finditer(line_text):
add_link(m.group(1) or m.group(2), line_num)
for m in _MD_WIKILINK_RE.finditer(line_text):
add_link(m.group(1), line_num, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
add_link(ref_def.group(1) or ref_def.group(2), line_num)
# Inside the frontmatter block a leading `#` is a YAML comment, not an
# H1. Links above are still scanned there on purpose: review workflows
# put wikilinks in frontmatter (e.g. a `consulted:` list), and those are
# real references. Only heading detection is suppressed.
if line_num_0 < body_start:
for m in _MD_INLINE_LINK_RE.finditer(line_text):
add_link(m.group(1) or m.group(2), line_num, owner=file_nid)
for m in _MD_REF_LINK_RE.finditer(line_text):
_text, _label = m.group(1), m.group(2)
_label = _label or _text
if _label in ref_defs:
add_link(ref_defs[_label], line_num, owner=file_nid)
for m in _MD_WIKILINK_RE.finditer(line_text):
add_link(m.group(1), line_num, owner=file_nid, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
_url = ref_def.group(2) or ref_def.group(3)
if _url and not _is_code_file_link(_url, source_dir):
add_link(_url, line_num, owner=file_nid)
continue
# Detect headings: # Heading, ## Heading, etc.
heading_match = re.match(r'^(#{1,6})\s+(.+)', line_text)
if heading_match:
heading_match = _MD_ATX_HEADING_RE.match(line_text)
title = _MD_ATX_CLOSING_RE.sub("", heading_match.group(2).strip()) if heading_match else ""
if heading_match and title:
level = len(heading_match.group(1))
title = heading_match.group(2).strip()
h_nid = _make_id(stem, title)
# Avoid duplicate heading IDs by appending line number
if h_nid in seen_ids:
@@ -574,14 +739,41 @@ def extract_markdown(path: Path) -> dict:
add_edge(parent, h_nid, "contains", line_num)
heading_stack.append((level, h_nid))
# Links in the heading itself belong to this heading.
for m in _MD_INLINE_LINK_RE.finditer(title):
add_link(m.group(1) or m.group(2), line_num, owner=h_nid)
for m in _MD_REF_LINK_RE.finditer(title):
_text, _label = m.group(1), m.group(2)
_label = _label or _text
if _label in ref_defs:
add_link(ref_defs[_label], line_num, owner=h_nid)
for m in _MD_WIKILINK_RE.finditer(title):
add_link(m.group(1), line_num, owner=h_nid, wikilink=True)
# A code span in the heading itself is that heading's mention.
for m in _MD_CODE_SPAN_RE.finditer(title):
add_mention(h_nid, m.group(2), line_num)
continue
# Body prose: a code span cites a symbol on behalf of the enclosing
# heading (the page when the text precedes the first heading).
# Body prose: links and code spans belong to the enclosing heading
# (the page when the text precedes the first heading).
owner = heading_stack[-1][1] if heading_stack else file_nid
for m in _MD_INLINE_LINK_RE.finditer(line_text):
add_link(m.group(1) or m.group(2), line_num, owner=owner)
for m in _MD_REF_LINK_RE.finditer(line_text):
_text, _label = m.group(1), m.group(2)
_label = _label or _text
if _label in ref_defs:
add_link(ref_defs[_label], line_num, owner=owner)
for m in _MD_WIKILINK_RE.finditer(line_text):
add_link(m.group(1), line_num, owner=owner, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
# A definition is not a use. A document definition keeps its
# page-level link edge; a source-file definition creates no
# citation at all — only its uses carry section evidence (#4804).
_url = ref_def.group(2) or ref_def.group(3)
if _url and not _is_code_file_link(_url, source_dir):
add_link(_url, line_num, owner=file_nid)
for m in _MD_CODE_SPAN_RE.finditer(line_text):
add_mention(owner, m.group(2), line_num)
+4 -2
View File
@@ -295,7 +295,9 @@ def extract_objc(path: Path) -> dict:
accepted = []
for macro in descendants(root, "macro_type_specifier"):
macro_name = macro.child_by_field_name("name")
if macro_name is None or _read(macro_name) not in ("NS_ENUM", "NS_OPTIONS"):
if macro_name is None or _read(macro_name) not in (
"NS_ENUM", "NS_OPTIONS", "NS_CLOSED_ENUM"
):
continue
# The closest preceding structural token in an enclosing node must
@@ -622,7 +624,7 @@ def extract_objc(path: Path) -> dict:
# `typedef enum { ... } Name;` / `typedef enum Tag { ... } Name;`.
# The enum body sits on a child enum_specifier that carries no usable
# name; the name callers reference is the typedef alias (the trailing
# type_identifier). NS_ENUM/NS_OPTIONS are handled separately through
# type_identifier). NS_ENUM/NS_OPTIONS/NS_CLOSED_ENUM are handled separately through
# their structural macro headers and isolated enum body fragments.
enum_spec = next((c for c in node.children if c.type == "enum_specifier"), None)
if enum_spec is not None and any(
+63 -48
View File
@@ -193,11 +193,19 @@ def extract_ocaml(path: Path) -> dict:
return
if t == "module_definition":
binding = next((c for c in node.children if c.type == "module_binding"), None)
if binding is not None:
# `module A = ... and B = ...` (mutually recursive modules) nests
# every binding under the ONE module_definition node, so taking
# only the first `module_binding` silently dropped every module
# after it, along with everything defined inside it. Walk every
# binding, each with its own line (the node's own line is only
# the first binding's), matching how type_definition already
# walks every type_binding in a type ... and ... chain.
for binding in node.children:
if binding.type != "module_binding":
continue
mname = named_child_text(binding, "module_name")
if mname:
line = line_of(node)
line = line_of(binding)
mnid = _make_id(stem, mname)
add_node(mnid, mname, line)
add_edge(container_nid, mnid,
@@ -206,7 +214,7 @@ def extract_ocaml(path: Path) -> dict:
local_modules.add(mname)
for child in binding.children:
walk(child, mnid, enclosing_value)
return
return
if t == "module_type_definition": # .mli
mname = named_child_text(node, "module_type_name")
@@ -273,51 +281,58 @@ def extract_ocaml(path: Path) -> dict:
# tree-sitter nests the name and the `object` body under a
# class_binding; the body is an `object_expression` in .ml and a
# `class_body_type` in .mli.
binding = next((c for c in node.children
if c.type == "class_binding"), None)
if binding is not None:
#
# `class a = ... and b = ...` (mutually recursive classes) nests
# every binding under the ONE class_definition node, so taking
# only the first `class_binding` silently dropped every class
# after it. Walk every binding, each with its own line (the
# node's own line is only the first binding's).
for binding in node.children:
if binding.type != "class_binding":
continue
cname = named_child_text(binding, "class_name")
if cname:
line = line_of(node)
cnid = _make_id(stem, cname)
add_node(cnid, cname, line)
add_edge(container_nid, cnid,
"defines" if container_nid == file_nid else "contains", line)
register_def(cname, cnid)
body = _find_object_body(binding)
if body is not None:
for member in body.children:
if member.type in ("method_definition", "method_specification"):
mname = named_child_text(member, "method_name")
if not mname:
continue
mline = line_of(member)
mnid = _make_id(stem, cname, mname)
add_node(mnid, mname, mline)
# A method is a callable class member, so use the
# "method" relation every other extractor emits
# (an instance `val` stays "contains" - it's a
# field). This keeps OCaml methods first-class in
# the call-flow view and caller/callee index,
# which key on "method" not "contains".
add_edge(cnid, mnid, "method", mline)
# Attribute calls in the method body to the
# method. Methods are NOT registered as local
# defs: they are only reachable through `obj#m`,
# never as a bare `m ...`, so binding a bare call
# to a same-named method would be a false edge.
for child in member.children:
walk(child, cnid, mnid)
elif member.type in ("instance_variable_definition",
"instance_variable_specification"):
vname = named_child_text(member, "instance_variable_name")
if not vname:
continue
vline = line_of(member)
vnid = _make_id(stem, cname, vname)
add_node(vnid, vname, vline)
add_edge(cnid, vnid, "contains", vline)
return
if not cname:
continue
line = line_of(binding)
cnid = _make_id(stem, cname)
add_node(cnid, cname, line)
add_edge(container_nid, cnid,
"defines" if container_nid == file_nid else "contains", line)
register_def(cname, cnid)
body = _find_object_body(binding)
if body is not None:
for member in body.children:
if member.type in ("method_definition", "method_specification"):
mname = named_child_text(member, "method_name")
if not mname:
continue
mline = line_of(member)
mnid = _make_id(stem, cname, mname)
add_node(mnid, mname, mline)
# A method is a callable class member, so use the
# "method" relation every other extractor emits
# (an instance `val` stays "contains" - it's a
# field). This keeps OCaml methods first-class in
# the call-flow view and caller/callee index,
# which key on "method" not "contains".
add_edge(cnid, mnid, "method", mline)
# Attribute calls in the method body to the
# method. Methods are NOT registered as local
# defs: they are only reachable through `obj#m`,
# never as a bare `m ...`, so binding a bare call
# to a same-named method would be a false edge.
for child in member.children:
walk(child, cnid, mnid)
elif member.type in ("instance_variable_definition",
"instance_variable_specification"):
vname = named_child_text(member, "instance_variable_name")
if not vname:
continue
vline = line_of(member)
vnid = _make_id(stem, cname, vname)
add_node(vnid, vname, vline)
add_edge(cnid, vnid, "contains", vline)
return
if t == "application_expression":
fn = node.named_children[0] if node.named_children else None
+5 -5
View File
@@ -28,7 +28,7 @@ _PAS_USES_RE = re.compile(
_PAS_TYPE_HEADER_RE = re.compile(
r"\b(?P<name>[A-Za-z_]\w*)(?:\s*<[^>]+>)?\s*=\s*(?:packed\s+)?"
r"(?P<kind>class|interface)\b"
r"(?P<kind>class|interface|record)\b"
r"(?:\s*\(\s*(?P<bases>[^)]*)\s*\))?",
re.IGNORECASE,
)
@@ -36,7 +36,7 @@ _PAS_TYPE_HEADER_RE = re.compile(
_PAS_END_SEMI_RE = re.compile(r"\bend\s*;", re.IGNORECASE)
_PAS_METHOD_DECL_RE = re.compile(
r"\b(?:procedure|function|constructor|destructor)\s+"
r"\b(?:procedure|function|constructor|destructor|operator)\s+"
r"(?P<name>[A-Za-z_]\w*)"
r"(?:\s*\([^)]*\))?"
r"(?:\s*:\s*[\w<>,\s.]+)?"
@@ -45,7 +45,7 @@ _PAS_METHOD_DECL_RE = re.compile(
)
_PAS_IMPL_HEADER_RE = re.compile(
r"\b(?:procedure|function|constructor|destructor)\s+"
r"\b(?:procedure|function|constructor|destructor|operator)\s+"
r"(?P<qual>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)"
r"(?:\s*<[^>]+>)?"
r"(?:\s*\([^)]*\))?"
@@ -66,8 +66,8 @@ _PAS_KEYWORDS = frozenset({
"with", "inherited", "result", "var", "const", "type", "nil", "true",
"false", "exit", "break", "continue", "uses", "unit", "program",
"library", "interface", "implementation", "initialization", "finalization",
"procedure", "function", "constructor", "destructor", "class", "record",
"object", "array", "string", "integer", "boolean", "real", "char",
"procedure", "function", "constructor", "destructor", "operator", "class",
"record", "object", "array", "string", "integer", "boolean", "real", "char",
"writeln", "write", "readln", "read", "assigned", "length", "high",
"low", "inc", "dec", "new", "dispose", "setlength", "copy", "pos",
"trim", "format", "inttostr", "strtoint", "ord", "chr", "sizeof",
+2 -2
View File
@@ -70,7 +70,7 @@ def extract_lazarus_form(path: Path) -> dict:
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
obj_re = re.compile(r"^\s*object\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
obj_re = re.compile(r"^\s*(?:object|inherited|inline)\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
event_re = re.compile(r"^\s*On\w+\s*=\s*(\w+)", re.IGNORECASE)
end_re = re.compile(r"^\s*end\s*$", re.IGNORECASE)
@@ -169,7 +169,7 @@ def extract_delphi_form(path: Path) -> dict:
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
obj_re = re.compile(r"^\s*object\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
obj_re = re.compile(r"^\s*(?:object|inherited|inline)\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
event_re = re.compile(r"^\s*On\w+\s*=\s*(\w+)", re.IGNORECASE)
end_re = re.compile(r"^\s*end\s*$", re.IGNORECASE)
stack: list[str] = [file_nid]
+19 -3
View File
@@ -292,12 +292,28 @@ def extract_powershell(path: Path) -> dict:
for el in child.children:
if el.type == "generic_token":
tokens.append(_read_text(el, source))
using_kind = tokens[0].lower() if tokens else ""
module_tokens = [t for t in tokens
if t.lower() not in ("namespace", "module", "assembly")]
if module_tokens:
module_name = module_tokens[-1].split(".")[-1]
add_edge(file_nid, _make_id(module_name), "imports_from",
node.start_point[0] + 1)
raw = module_tokens[-1]
if using_kind == "namespace":
module_name = raw.split(".")[-1]
else:
# `module`/`assembly` name a file or library
# (Helpers.psm1, System.Data.dll): a trailing module
# or assembly extension is not a namespace separator,
# so splitting on it like the namespace form returned
# the extension itself instead of the name. Strip only
# a known extension, so a dotted module name with no
# file extension (Az.Accounts) keeps its full name
# rather than losing its last segment.
module_name = re.sub(
r'\.(psm1|psd1|ps1|dll|exe)$', '', raw, flags=re.IGNORECASE
).split('/')[-1].split('\\')[-1]
if module_name:
add_edge(file_nid, _make_id(module_name), "imports_from",
node.start_point[0] + 1)
elif cmd_text == "import-module":
# Collect generic_token args; skip command_parameter flags like -Name
# The module name is the first generic_token (or the one after -Name)
+4 -1
View File
@@ -230,7 +230,10 @@ def extract_r(path: Path) -> dict:
key_node = argument.child_by_field_name("name")
value = argument_value(argument)
key = _read_text(key_node, source) if key_node is not None else ""
if key == "inherit" and value is not None:
# R6Class spells its superclass argument `inherit`; setClass and
# setRefClass both spell the same thing `contains` instead, so a
# `contains = "Base"` S4/R5 class silently lost its inheritance edge.
if key in {"inherit", "contains"} and value is not None:
base_name = string_or_identifier(value).split("$")[-1]
if base_name:
base_id = classes.get(base_name, _make_id("r", "class", base_name))
+9
View File
@@ -125,6 +125,15 @@ def extract_razor(path: Path) -> dict:
_add_ref(m.group(1), "inherits", i)
continue
# A component can list one @implements per line for each interface it
# satisfies (IDisposable, IAsyncDisposable, a custom one, ...), same as
# a C# class heritage clause. Only @inherits (the base class) was ever
# recorded; every @implements interface was silently invisible.
m = re.match(r'@implements\s+([\w.<>\[\]]+)', line)
if m:
_add_ref(m.group(1), "implements", i)
continue
m = re.match(r'@model\s+([\w.<>\[\]]+)', line)
if m:
_add_ref(m.group(1), "references", i)
+549 -89
View File
@@ -12,6 +12,7 @@ from graphify.extractors.base import ( # noqa: F401
_read_source_text,
_read_text,
)
from graphify.ids import normalize_id
from graphify.rcfile import effective_suffix, get_language_overrides
import functools
import hashlib
@@ -422,7 +423,16 @@ def _pnpm_workspace_globs(workspace_file: Path) -> list[str]:
in_packages = True
continue
if in_packages and line.startswith("-"):
value = line[1:].strip().strip("'\"")
value = line[1:].strip()
if value[:1] in ("'", '"'):
# Quoted: the value ends at the closing quote, so a `# comment` after it is dropped.
end = value.find(value[0], 1)
if end < 0:
continue
value = value[1:end].strip()
else:
# Unquoted: a `#` only starts a comment after whitespace.
value = re.split(r"(?:^|\s)#", value, maxsplit=1)[0].strip()
if value and not value.startswith("!"):
globs.append(value)
continue
@@ -465,7 +475,11 @@ def _load_workspace_packages(start_dir: Path) -> dict[str, Path]:
packages: dict[str, Path] = {}
for pattern in _workspace_globs(root):
package_dirs: list[Path] = [root] if pattern in (".", "./") else list(root.glob(pattern))
try:
package_dirs: list[Path] = [root] if pattern in (".", "./") else list(root.glob(pattern))
except (ValueError, NotImplementedError) as e:
print(f" warning: skipped workspace glob {pattern!r} ({type(e).__name__}: {e})", file=sys.stderr, flush=True)
continue
for package_dir in package_dirs:
manifest = package_dir / "package.json"
if not manifest.is_file():
@@ -853,7 +867,9 @@ def _resolve_js_module_path(raw: str | Path, start_dir: Path | None = None) -> P
if start_dir is None:
return _resolve_js_import_path(Path(raw))
if raw.startswith("."):
return _resolve_js_import_path(start_dir / raw)
# Strip ?query / #fragment before resolving, as bundlers do (#4860).
specifier = raw.split("#", 1)[0].split("?", 1)[0]
return _resolve_js_import_path(start_dir / specifier)
aliases = _load_tsconfig_aliases(start_dir)
hit = _resolve_tsconfig_alias(raw, aliases,
@@ -1197,6 +1213,12 @@ def _disambiguate_colliding_node_ids(
raw_call["caller_nid"] = remap[caller_key]
elif raw_call.get("caller_nid") in unambiguous_remaps:
raw_call["caller_nid"] = unambiguous_remaps[str(raw_call["caller_nid"])]
if raw_call.get("evidence_owner"):
eo_key = (raw_call.get("evidence_owner", ""), call_source_key)
if eo_key in remap:
raw_call["evidence_owner"] = remap[eo_key]
elif raw_call.get("evidence_owner") in unambiguous_remaps:
raw_call["evidence_owner"] = unambiguous_remaps[str(raw_call["evidence_owner"])]
def _is_type_like_definition(node: dict) -> bool:
if node.get("type") == "namespace":
@@ -1206,7 +1228,9 @@ def _is_type_like_definition(node: dict) -> bool:
return False
if label.endswith(")") or label.startswith("."):
return False
if "." in label:
# A dotted label names a namespace or module in most languages, but a SQL
# table is `schema.name`: it is a type-like definition a reference can bind to.
if "." in label and not str(node.get("source_file", "")).lower().endswith(".sql"):
return False
return node.get("file_type") == "code"
@@ -1250,6 +1274,7 @@ def _apply_symbol_resolution_facts(
root: Path,
facts: _SymbolResolutionFacts,
resolution_context_nodes: list[dict] | None = None,
raw_calls: list[dict] | None = None,
) -> None:
"""Apply language-provided import/export/use facts to graph edges."""
if not (
@@ -1262,6 +1287,9 @@ def _apply_symbol_resolution_facts(
or facts.uses
or facts.module_imports
):
for edge in edges:
edge.pop("_require_imported_name", None)
edge.pop("_require_target_file", None)
return
path_by_resolved = {_resolve_cached(path): path for path in paths}
@@ -1352,6 +1380,58 @@ def _apply_symbol_resolution_facts(
})
return node_id
# #4854: a reference to an imported name can be minted before the imported
# declaration is known, as a sourceless stub (or as this file's own id when
# the name equals the extension). Bind it to the declaration in the target
# file, keyed by (path, name) so two modules may declare the same symbol.
if facts.imports:
declared: dict[tuple[Path, str], str] = {}
for node in nodes:
node_path = _js_source_path(str(node.get("source_file") or ""), root)
if node_path is None:
continue
label = str(node.get("label") or "").strip()
if not label or label.startswith("."):
continue
bare = label[:-2] if label.endswith("()") else label
if "." in bare:
continue
declared.setdefault((node_path, normalize_id(bare)), node["id"])
node_by_id = {node.get("id"): node for node in nodes}
refs_by_source: dict[Path, list[dict]] = {}
for edge in edges:
if edge.get("relation") != "references":
continue
edge_source = _js_source_path(str(edge.get("source_file") or ""), root)
if edge_source is not None:
refs_by_source.setdefault(edge_source, []).append(edge)
for fact in facts.imports:
if effective_suffix(fact.file_path).lower() not in (
".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"
):
continue
source_path = _resolve_cached(fact.file_path)
target_path = _resolve_cached(fact.target_path)
names = {normalize_id(fact.imported_name), normalize_id(fact.local_name)}
target_nid = next(
(declared[(target_path, name)] for name in names
if (target_path, name) in declared),
None,
)
if not target_nid:
continue
for edge in refs_by_source.get(source_path, ()):
if edge.get("target") == target_nid:
continue
node = node_by_id.get(edge.get("target"))
if node is None or node.get("source_file"):
continue
stub_label = normalize_id(
str(node.get("label") or "").strip("()").lstrip(".")
)
if stub_label in names:
edge["target"] = target_nid
# Keyed by the emitting file as well: two files whose ids collide (`a-b/x.ts`
# and `a/b/x.ts` both make `a_b_x`) share `source` until
# _disambiguate_colliding_node_ids salts them by source_file, so without the
@@ -1563,6 +1643,24 @@ def _apply_symbol_resolution_facts(
candidates.add(origin)
return candidates, cyclic
# A destructured `require` names the immediate barrel's symbol. When that
# target is not a node (the barrel defines nothing), follow the barrel to
# the file that declares the symbol, so cross-file call resolution sees
# import evidence instead of a dangling barrel reference.
for edge in edges:
imported_name = edge.pop("_require_imported_name", None)
target_file = edge.pop("_require_target_file", None)
if edge.get("relation") != "imports" or not imported_name or not target_file:
continue
origin_path, origin_symbol = resolve_exported_origin(
Path(str(target_file)), str(imported_name)
)
target_id = symbol_nodes.get((origin_path, origin_symbol))
if target_id is None or edge.get("target") == target_id:
continue
edge["target"] = target_id
edge["target_file"] = str(path_by_resolved.get(origin_path, origin_path))
# The structural extractor names the immediate barrel's symbol. Resolve
# that exact authored export site through the shared import/export facts,
# including `import {x}; export {x}` bridges with no local declaration.
@@ -1620,6 +1718,55 @@ def _apply_symbol_resolution_facts(
import_fact.file_path,
)
if raw_calls and any(
fact.imported_name == "default"
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
for fact in facts.imports
):
default_imports = {
(_resolve_cached(fact.file_path), fact.local_name): _resolve_cached(fact.target_path)
for fact in facts.imports
if fact.imported_name == "default"
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
}
member_nodes: dict[tuple[Path, str, str], set[str]] = {}
fresh_paths = {_resolve_cached(path) for path in paths}
for node in nodes + [
node for node in resolution_context_nodes or []
if _js_source_path(str(node.get("source_file", "")), root) not in fresh_paths
]:
if not node.get("_callable"):
continue
source_path = _js_source_path(str(node.get("source_file", "")), root)
if source_path is None:
continue
key = (source_path, str(node.get("label", "")), str(node.get("source_location", "")))
member_nodes.setdefault(key, set()).add(str(node["id"]))
default_members: dict[Path, dict[str, tuple[str, str]]] = {}
for call in raw_calls:
if (not call.get("is_member_call") or call.get("_js_receiver_shadowed")
or call.get("_js_construct") or call.get("ts_this_field")):
continue
source_path = _js_source_path(str(call.get("source_file", "")), root)
if source_path is None:
continue
target_path = default_imports.get((source_path, str(call.get("receiver") or "")))
if target_path is None:
continue
if target_path not in default_members:
default_members[target_path] = _js_default_object_members(target_path)
member = default_members[target_path].get(str(call.get("callee") or ""))
if member is None:
continue
targets = member_nodes.get((target_path, *member), set())
if len(targets) != 1:
continue
add_edge(
call["caller_nid"], next(iter(targets)), "calls", "call",
int(str(call["source_location"]).removeprefix("L")),
Path(call["source_file"]), target_file=str(target_path),
)
# The structural extractor names the imported symbol on the immediate barrel,
# which defines nothing, so its edge dangles and build mints an external stub
# beside the edge the loop above added to the defining symbol (#4486). Drop
@@ -1748,6 +1895,48 @@ def _apply_symbol_resolution_facts(
# survives, and the file id is exactly what the #2231 remap
# canonicalizes — or drop it when no file node id is available.
owned = {str(n.get("id")) for n in nodes}
def _collision_aware(source_id: str, file_path: Path, line: int) -> str:
"""The declaration node a top-level ``def``'s call actually belongs to.
``make_id`` strips the underscore edges off each part, so ``_main`` and
``main`` mint one plain id. The engine salts the colliding pair apart
(#3302) and leaves only the unique public spelling — ``main()`` — on the
plain id, while a ``def`` collected by name here can only carry the plain
id. So every call inside ``_main`` was being credited to ``main`` (#4994).
The declarations sharing that plain id sit on distinct lines, so the one
enclosing the call line is the caller. Anything the line cannot settle
(no candidates, or several) keeps ``source_id`` unchanged, which is what
this pass did before.
"""
if not any(other.startswith(source_id + "_") for other in owned):
return source_id
candidates = [n for n in nodes if n.get("id") == source_id or (
isinstance(n.get("id"), str)
and n["id"].startswith(source_id + "_")
# Only an underscore-collision salt (`_underscore_salted_nid`, a
# 6-char sha1 hex) is a sibling spelling of the same def. A plain
# alphanumeric suffix is a child node id (`classid_methodname`), so
# matching it would wrongly steal a class member's edge (e.g. a
# type-annotated field's reference) onto a preceding method.
and re.fullmatch(r"[0-9a-f]{6}", n["id"][len(source_id) + 1:]) is not None
and _js_source_path(str(n.get("source_file") or ""), root) == file_path
)]
if len(candidates) < 2:
return source_id
def _start(node: dict) -> int:
try:
return int(str(node.get("source_location") or "").removeprefix("L"))
except ValueError:
return 0
enclosing = [n for n in candidates if _start(n) <= line]
if not enclosing:
return source_id
return str(max(enclosing, key=_start)["id"])
for use_fact in facts.uses:
file_path = _resolve_cached(use_fact.file_path)
target_id = None
@@ -1765,7 +1954,7 @@ def _apply_symbol_resolution_facts(
target_id = symbol_nodes.get((file_path, use_fact.local_name))
if target_id is None:
continue
source_id = use_fact.source_id
source_id = _collision_aware(use_fact.source_id, file_path, use_fact.line)
# Structural walking can omit named-function-local declarations while
# materializing callback-local ones. Only actual node ownership decides
# whether a type relationship has a represented source declaration.
@@ -1841,6 +2030,14 @@ def _js_module_specifier(node, source: bytes) -> str | None:
if child.type == "string":
source_node = child
break
# TS `import x = require("./m")`: the module string sits inside
# import_require_clause, not as a direct child of import_statement
# (same dig as `_import_js` in extract.py).
if child.type == "import_require_clause":
source_node = next(
(sub for sub in child.children if sub.type == "string"), None
)
break
if source_node is None:
return None
raw = _read_text(source_node, source).strip()
@@ -1950,7 +2147,8 @@ def _js_default_export_name(node, source: bytes) -> str | None:
`export default abstract class Foo {}` (name on the `declaration` field) and
`export default Foo` (an identifier on the `value` field). Anonymous defaults
(`export default class {}`, `export default {...}`) have no resolvable symbol
and return None.
and return None; the members of an anonymous default object are resolved
separately by :func:`_js_default_object_members`.
"""
if not any(child.type == "default" for child in node.children):
return None
@@ -1963,6 +2161,47 @@ def _js_default_export_name(node, source: bytes) -> str | None:
return _read_text(value, source)
return None
def _js_default_object_members(path: Path) -> dict[str, tuple[str, str]]:
"""Static methods of a direct default-exported object that resolve to an
existing node. Only members we can bind to a real node are returned."""
parsed = _parse_js_tree(path)
if parsed is None:
return {}
source, root_node = parsed
for node in root_node.named_children:
if node.type != "export_statement" or not any(
child.type == "default" for child in node.children
):
continue
value = node.child_by_field_name("value")
if value is None or value.type != "object":
continue
members: dict[str, tuple[str, str]] = {}
seen: set[str] = set()
for prop in value.named_children:
if prop.type == "comment":
continue
key = prop.child_by_field_name("name") or prop.child_by_field_name("key")
# A spread or computed key can override any method, so do not add an
# edge on the strength of a same-named node alone.
if key is None or key.type not in ("property_identifier", "string"):
return {}
raw_name = _read_text(key, source)
if "\\" in raw_name:
return {}
name = raw_name[1:-1] if key.type == "string" else raw_name
if name in seen:
members.pop(name, None)
continue
seen.add(name)
if prop.type == "method_definition" and not any(
child.type in ("get", "set") for child in prop.children
):
members[name] = (f"{raw_name}()", f"L{prop.start_point[0] + 1}")
return members
return {}
def _js_top_level_function_bodies(path: Path, root_node, source: bytes) -> list[tuple[str, object]]:
bodies: list[tuple[str, object]] = []
stem = _file_stem(path)
@@ -2196,12 +2435,174 @@ def _ts_walk_class_members(class_node, source: bytes, path: Path, class_nid: str
_SymbolUseFact(path, class_nid, name, "references", ctx, m_line)
)
def _js_require_call_and_specifier(value_node, source: bytes):
"""Return ``(call_node, raw_specifier)`` for a literal ``require('...')``
(or ``require('...').x``), else ``None``.
Name-checks the callee the same way ``_require_imports_js`` / ``_js_value_is_require``
do, so a ``factory()`` call is never treated as an import (#4634).
"""
if value_node is None:
return None
node = value_node
if node.type == "member_expression":
node = node.child_by_field_name("object")
if node is None:
return None
if node.type != "call_expression":
return None
fn = node.child_by_field_name("function")
if fn is None or fn.type != "identifier" or _read_text(fn, source) != "require":
return None
args = node.child_by_field_name("arguments")
if args is None:
return None
raw = None
for arg in args.children:
if arg.type == "string":
raw = _read_text(arg, source).strip("'\"` ")
break
if not raw:
return None
return node, raw
def _js_cjs_require_bindings(declarator, source: bytes) -> list[tuple[str, str]]:
"""``(local_name, imported_name)`` for a whole-module ``require`` declarator.
Only ``const/let/var X = require('./m')`` (not ``require('./m').y`` or
``const { X } = require('./m')``). Those other forms already get structural
``imports`` edges from ``_require_imports_js``; minting SymbolImportFacts for
them would also resolve call-uses through the symbol pass and regress the
EXTRACTED ``confidence_score`` path for destructured requires (#4688 / #4634).
Whole-module bindings are recorded as default imports, matching ESM
``import X from './m'``.
"""
value = declarator.child_by_field_name("value")
if value is None or value.type != "call_expression":
return []
req = _js_require_call_and_specifier(value, source)
if req is None:
return []
name_node = declarator.child_by_field_name("name")
if name_node is None or name_node.type != "identifier":
return []
local = _read_text(name_node, source)
if not local:
return []
return [(local, "default")]
def _js_cjs_default_export_local(right, source: bytes) -> str | None:
"""Local name of a ``module.exports = <expr>`` RHS, if resolvable.
Walks through chained assignments (``module.exports = exports = Foo``) to the
final RHS — an intermediate ``exports = …`` left is not the exported binding.
"""
node = right
while node is not None and node.type == "assignment_expression":
node = node.child_by_field_name("right")
if node is None:
return None
if node.type == "identifier":
return _read_text(node, source) or None
if node.type in (
"class", "class_declaration", "function", "function_declaration",
"generator_function", "generator_function_declaration",
):
name_node = node.child_by_field_name("name")
if name_node is not None:
return _read_text(name_node, source) or None
return None
def _js_cjs_export_facts(node, source: bytes, path: Path) -> list[_SymbolExportFact]:
"""Export facts for CommonJS ``module.exports`` / ``exports.X`` assignments.
Whole-module ``module.exports = Name`` is recorded as a default export so a
``const X = require('./m')`` import resolves through the same alias path as
ESM ``import X from './m'`` (#4688). Named property assignments
(``exports.Foo = …`` / ``module.exports.Foo = …``) become named exports.
Bare ``exports = Name`` is intentionally ignored: in CommonJS that only
rebinds the local ``exports`` binding and does not change what ``require()``
returns (unlike ``module.exports = Name``).
"""
if node.type != "expression_statement":
return []
assign = next((c for c in node.children if c.type == "assignment_expression"), None)
if assign is None:
return []
left = assign.child_by_field_name("left")
right = assign.child_by_field_name("right")
if left is None or right is None:
return []
line = node.start_point[0] + 1
left_str = _read_text(left, source)
out: list[_SymbolExportFact] = []
if left_str == "module.exports":
local = _js_cjs_default_export_local(right, source)
if local:
out.append(
_SymbolExportFact(path, "default", line, local_name=local)
)
# Also expose the binding under its own name so a same-named
# ``require`` without a default walk still finds it, and so
# ``module.exports = Generator`` remains visible as ``Generator``.
if local != "default":
out.append(
_SymbolExportFact(path, local, line, local_name=local)
)
elif right.type == "object":
for prop in right.children:
if prop.type == "shorthand_property_identifier":
name = _read_text(prop, source)
if name:
out.append(
_SymbolExportFact(path, name, line, local_name=name)
)
elif prop.type == "pair":
key = prop.child_by_field_name("key")
val = prop.child_by_field_name("value")
if key is None:
continue
exported = _read_text(key, source)
local_name = None
if val is not None and val.type == "identifier":
local_name = _read_text(val, source) or None
if exported:
out.append(
_SymbolExportFact(
path, exported, line, local_name=local_name or exported
)
)
return out
if left.type != "member_expression":
return []
# exports.Foo = ... / module.exports.Foo = ...
obj = left.child_by_field_name("object")
prop = left.child_by_field_name("property")
if obj is None or prop is None:
return []
exported = _read_text(prop, source)
if not exported:
return []
obj_str = _read_text(obj, source)
if obj_str not in ("exports", "module.exports"):
return []
local = _js_cjs_default_export_local(right, source) or exported
out.append(_SymbolExportFact(path, exported, line, local_name=local))
return out
# Node types the whole-tree passes of _collect_js_symbol_resolution_facts
# filter on.
_JS_FACT_NODE_TYPES = frozenset({
"export_statement",
"import_statement",
"lexical_declaration",
"variable_declaration",
"expression_statement",
"class_declaration",
"abstract_class_declaration",
"interface_declaration",
@@ -2216,10 +2617,11 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
if not js_paths:
return
trees: dict[Path, tuple[bytes, object, list]] = {}
# One parse per file, dropped before the next: holding every file's source and syntax tree
# across the passes held the whole corpus (1.9 GB on Next.js). Class-member uses still follow
# all call uses, so every fact list keeps its order.
member_facts = _SymbolResolutionFacts()
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = _parse_js_tree(path)
if parsed is None:
continue
@@ -2228,7 +2630,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
node for node in _walk_js_tree(root_node)
if node.type in _JS_FACT_NODE_TYPES
]
trees[resolved_path] = (source, root_node, indexed)
for node in indexed:
if node.type == "export_statement":
@@ -2237,6 +2638,44 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
_SymbolDeclarationFact(path, name, node.start_point[0] + 1)
)
if node.type == "expression_statement":
facts.exports.extend(_js_cjs_export_facts(node, source, path))
continue
if node.type in ("lexical_declaration", "variable_declaration"):
# CommonJS `const/let/var X = require('./m')` is an import alias,
# not a local declaration. Without a SymbolImportFact here,
# `class A extends X` has nothing to resolve through after #4634
# stopped minting a shadow binding node (#4688).
for child in node.children:
if child.type != "variable_declarator":
continue
bindings = _js_cjs_require_bindings(child, source)
if not bindings:
continue
req = _js_require_call_and_specifier(
child.child_by_field_name("value"), source
)
if req is None:
continue
_call, raw_module = req
target_path = _resolve_js_module_path(raw_module, path.parent)
if target_path is None:
continue
target_path = _resolve_cached(target_path)
line = node.start_point[0] + 1
for local_name, imported_name in bindings:
facts.imports.append(
_SymbolImportFact(
path,
local_name,
target_path,
imported_name,
line,
)
)
continue
if node.type != "import_statement":
continue
raw_module = _js_module_specifier(node, source)
@@ -2267,6 +2706,27 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
node.start_point[0] + 1,
)
)
# TS `import X = require("./m")` — same default-import shape as
# `const X = require("./m")` (#4688).
for child in node.children:
if child.type != "import_require_clause":
continue
local_node = next(
(c for c in child.children if c.type == "identifier"), None
)
if local_node is None:
continue
local_name = _read_text(local_node, source)
if local_name:
facts.imports.append(
_SymbolImportFact(
path,
local_name,
target_path,
"default",
node.start_point[0] + 1,
)
)
for node in indexed:
for alias, target in _js_lexical_aliases(node, source):
@@ -2274,13 +2734,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
_SymbolAliasFact(path, alias, target, node.start_point[0] + 1)
)
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = trees.get(resolved_path)
if parsed is None:
continue
source, _root_node, indexed = parsed
for node in indexed:
if node.type != "export_statement":
continue
@@ -2370,12 +2823,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
)
)
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = trees.get(resolved_path)
if parsed is None:
continue
source, root_node, _indexed = parsed
for source_id, body in _js_top_level_function_bodies(path, root_node, source):
for node in _walk_js_tree(body):
imported_name = _js_call_identifier(node, source)
@@ -2392,12 +2839,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
)
)
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = trees.get(resolved_path)
if parsed is None:
continue
source, _root_node, indexed = parsed
stem = _file_stem(path)
for node in indexed:
if node.type not in (
@@ -2413,7 +2854,8 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
if not class_name:
continue
class_nid = _make_id(stem, class_name)
_ts_walk_class_members(node, source, path, class_nid, facts)
_ts_walk_class_members(node, source, path, class_nid, member_facts)
facts.uses.extend(member_facts.uses)
@functools.lru_cache(maxsize=2048)
def _parse_python_tree_cached(path_str: str, _mtime_ns: int, _size: int):
@@ -2762,6 +3204,12 @@ def _resolve_python_namespace_dir(module_name: str, current_path: Path, root: Pa
return None
def _python_top_level_function_bodies(path: Path, root_node, source: bytes) -> list[tuple[str, object]]:
"""``(plain caller id, body)`` for every top-level ``def`` in the module.
Deliberately the *unsalted* id: ``_apply_symbol_resolution_facts`` resolves
the caller against the final graph, where the underscore-collision spread
(#3302) is baked into the ids.
"""
bodies: list[tuple[str, object]] = []
stem = _file_stem(path)
for node in root_node.children:
@@ -2792,13 +3240,12 @@ def _collect_python_symbol_resolution_facts(
if not py_paths:
return
trees: dict[Path, tuple[bytes, object]] = {}
# One parse per file, dropped before the next (the same reason as the JS facts above).
for path in py_paths:
parsed = _parse_python_tree(path)
if parsed is None:
continue
source, root_node = parsed
trees[_resolve_cached(path)] = parsed
for node in _walk_python_tree(root_node):
if node.type != "import_from_statement":
@@ -2865,11 +3312,6 @@ def _collect_python_symbol_resolution_facts(
)
)
for path in py_paths:
parsed = trees.get(_resolve_cached(path))
if parsed is None:
continue
source, root_node = parsed
for source_id, body in _python_top_level_function_bodies(path, root_node, source):
for node in _walk_python_tree(body):
imported_name = _python_call_identifier(node, source)
@@ -2893,6 +3335,7 @@ def _augment_symbol_resolution_edges(
root: Path,
ambiguous_python_modules: set[str] | None = None,
resolution_context_nodes: list[dict] | None = None,
raw_calls: list[dict] | None = None,
) -> None:
facts = _SymbolResolutionFacts()
_collect_js_symbol_resolution_facts(paths, facts)
@@ -2904,7 +3347,10 @@ def _augment_symbol_resolution_edges(
_apply_symbol_resolution_facts(
paths, nodes, edges, root, facts,
resolution_context_nodes=resolution_context_nodes,
raw_calls=raw_calls,
)
elif raw_calls:
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts, raw_calls=raw_calls)
else:
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts)
@@ -2975,6 +3421,13 @@ def _resolve_cross_file_imports(
node_by_id = {node["id"]: node for node in all_nodes if node.get("id")} if all_nodes else {}
repointed_from: set[str] = set()
TYPE_REPOINT_RELATIONS = frozenset({"references", "inherits", "implements", "extends"})
# The #3252 repoint below only ever touches an edge whose source_file belongs
# to the importing file. Index the edges by source_file once, when the first
# file needs it, instead of scanning all of them per file (files x edges,
# #4980). Each entry keeps the edge's position in all_edges, so a file's
# edges are visited in the same order as before.
edges_by_source: dict[object, list[tuple[int, dict]]] = {}
edges_indexed = False
for file_result, path in zip(per_file, paths):
str_path = str(path)
@@ -3152,9 +3605,15 @@ def _resolve_cross_file_imports(
# Repoint AST type-reference and inheritance edges from sourceless stubs
# to the exact imported target definition (#3252).
if all_edges and import_targets:
for edge in all_edges:
if edge.get("source_file") not in file_srcs:
continue
if not edges_indexed:
for position, edge in enumerate(all_edges):
edges_by_source.setdefault(edge.get("source_file"), []).append((position, edge))
edges_indexed = True
file_edges = sorted(
(entry for src in file_srcs for entry in edges_by_source.get(src, ())),
key=lambda entry: entry[0],
)
for _, edge in file_edges:
if edge.get("relation") not in TYPE_REPOINT_RELATIONS:
continue
tgt = edge.get("target")
@@ -3453,9 +3912,9 @@ def _resolve_cross_file_java_imports(
language = Language(tsjava.language())
parser = Parser(language)
# Pre-pass: declared package per source_file string (and parsed trees for
# pass 2, so each file is only parsed once).
parsed: dict[str, tuple[bytes, object]] = {}
# Pre-pass: declared package per source_file string and each file's imports,
# so pass 2 needs no syntax tree: holding every tree held the whole corpus.
imports_by_path: dict[str, list[tuple[str, str, int]]] = {}
pkg_by_src: dict[str, str] = {}
for path, file_result in zip(paths, per_file):
try:
@@ -3463,7 +3922,7 @@ def _resolve_cross_file_java_imports(
tree = parser.parse(source)
except Exception:
continue
parsed[str(path)] = (source, tree)
imports_by_path[str(path)] = _java_import_rows(tree.root_node, source)
pkg = ""
for child in tree.root_node.children:
if child.type == "package_declaration":
@@ -3510,55 +3969,56 @@ def _resolve_cross_file_java_imports(
seen_pairs: set[tuple[str, str]] = set()
for path in paths:
file_nid = _make_id(str(path))
entry = parsed.get(str(path))
if entry is None:
continue
source, tree = entry
def walk(n) -> None:
if n.type == "import_declaration":
raw = _read_text(n, source).strip()
body = raw[len("import"):].strip().rstrip(";").strip()
if body.startswith("static "):
body = body[len("static "):].strip()
if body.endswith(".*"):
return
parts = body.split(".")
if not parts:
return
last = parts[-1]
imp_pkg = ".".join(parts[:-1])
if last and last[0].islower() and len(parts) >= 2:
last = parts[-2]
imp_pkg = ".".join(parts[:-2])
at_line = n.start_point[0] + 1
for tgt_nid, tgt_pkg in name_to_ids.get(last, []):
if tgt_nid == file_nid:
continue
if not _pkg_matches(imp_pkg, tgt_pkg):
continue
key = (file_nid, tgt_nid)
if key in seen_pairs:
continue
seen_pairs.add(key)
new_edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str(path),
"source_location": f"L{at_line}",
"weight": 1.0,
})
for child in n.children:
walk(child)
walk(tree.root_node)
for last, imp_pkg, at_line in imports_by_path.get(str(path), ()):
for tgt_nid, tgt_pkg in name_to_ids.get(last, []):
if tgt_nid == file_nid:
continue
if not _pkg_matches(imp_pkg, tgt_pkg):
continue
key = (file_nid, tgt_nid)
if key in seen_pairs:
continue
seen_pairs.add(key)
new_edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str(path),
"source_location": f"L{at_line}",
"weight": 1.0,
})
return new_edges
def _java_import_rows(root_node, source: bytes) -> list[tuple[str, str, int]]:
"""Each non-wildcard import in a Java tree as (name, package, line), in source order."""
rows: list[tuple[str, str, int]] = []
def walk(n) -> None:
if n.type == "import_declaration":
raw = _read_text(n, source).strip()
body = raw[len("import"):].strip().rstrip(";").strip()
if body.startswith("static "):
body = body[len("static "):].strip()
if body.endswith(".*"):
return
parts = body.split(".")
last = parts[-1]
imp_pkg = ".".join(parts[:-1])
if last and last[0].islower() and len(parts) >= 2:
last = parts[-2]
imp_pkg = ".".join(parts[:-2])
rows.append((last, imp_pkg, n.start_point[0] + 1))
for child in n.children:
walk(child)
walk(root_node)
return rows
def _go_import_path_for_file(
source_file: str | Path,
root: Path,
+19 -1
View File
@@ -187,6 +187,20 @@ def extract_robot(path: Path) -> dict:
for tgt in kw_targets(name):
add_edge(src, tgt, "calls", line, context="call")
# Robot Framework allows two test cases in one file to share a name (it
# only warns, never a parse/run error, unlike a duplicate keyword
# definition) - stem-qualifying by name alone then collapses both onto
# one node, so the second test's own keyword calls land on the first
# test's id and line. Counted up front so every occurrence of a
# duplicated name salts by its own line number regardless of visit
# order, and a name used only once keeps the plain id it always had.
test_name_counts: dict[str, int] = {}
class _TestCaseCountVisitor(ModelVisitor):
def visit_TestCase(self, node):
if node.name:
test_name_counts[node.name] = test_name_counts.get(node.name, 0) + 1
class _RobotVisitor(ModelVisitor):
def __init__(self):
self.scope_nid = file_nid
@@ -253,7 +267,10 @@ def extract_robot(path: Path) -> dict:
def visit_TestCase(self, node):
if not node.name:
return
tc_nid = _make_id(stem, node.name)
if test_name_counts.get(node.name, 0) >= 2:
tc_nid = _make_id(stem, node.name, f"L{node.lineno}")
else:
tc_nid = _make_id(stem, node.name)
add_node(tc_nid, node.name, node.lineno)
add_edge(file_nid, tc_nid, "contains", node.lineno)
prev, self.scope_nid = self.scope_nid, tc_nid
@@ -290,6 +307,7 @@ def extract_robot(path: Path) -> dict:
add_call_edges(self.scope_nid, node.value, node.lineno)
try:
_TestCaseCountVisitor().visit(model)
_RobotVisitor().visit(model)
except Exception as e:
return {"nodes": nodes, "edges": edges, "error": str(e)}
+192 -22
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import hashlib
import re
from pathlib import Path
from graphify.ids import DeclIdRegistry
from graphify.extractors.base import (
_LANGUAGE_BUILTIN_GLOBALS,
_file_stem,
@@ -200,6 +201,48 @@ _RUST_PRIMITIVE_TYPES: frozenset[str] = frozenset({
})
# Macros whose arguments are ordinary Rust expressions. A DSL macro (`table!`,
# `quote!`, `html!`, nom combinators) also writes `name(...)` but means
# something else by it, so only these are scanned for calls.
_RUST_EXPRESSION_MACROS = frozenset({
"assert", "assert_eq", "assert_ne", "debug_assert", "debug_assert_eq",
"debug_assert_ne", "dbg", "eprint", "eprintln", "format", "format_args",
"panic", "print", "println", "todo", "unimplemented", "unreachable", "vec",
"write", "writeln", "debug", "error", "info", "trace", "warn",
})
def _rust_macro_arg_calls(token_tree) -> list[tuple[str, int]]:
"""Bare `f(...)` calls written inside a macro's arguments.
Tree-sitter keeps macro arguments as a flat token tree, so `println!("{}", f(x))`
has no call_expression: it is an `identifier` followed by a `(` token tree.
A name after `.` or `::` is a method or path call and is left out, as is a
name followed by `!` (a nested macro, which is its own macro_invocation).
"""
found: list[tuple[str, int]] = []
stack = [token_tree]
while stack:
tree = stack.pop()
children = tree.children
for i, child in enumerate(children):
if child.type == "token_tree":
stack.append(child)
continue
if child.type != "identifier" or i + 1 >= len(children):
continue
nxt = children[i + 1]
if nxt.type != "token_tree" or not nxt.children or nxt.children[0].type != "(":
continue
if i > 0 and children[i - 1].type in (".", "::", "fn", "$", "#"):
continue
name = child.text.decode("utf-8", errors="replace") if child.text else ""
if name:
found.append((name, child.start_point[0] + 1))
found.sort(key=lambda item: item[1])
return found
def _rust_qualifier_type(path_node, source: bytes) -> str | None:
"""The type a `Type::f()` call is qualified by, or None for a module path.
@@ -274,27 +317,48 @@ def extract_rust(path: Path) -> dict:
_scan_local_types(root)
local_type_names = frozenset(local_types)
# Where each imported name comes from: `crate` for this crate's own paths, otherwise
# the first path segment (`serde_json`, or a workspace crate's name). A sourceless
# stub under such a name carries it, so the corpus rewire can scope the binding.
use_roots: dict[str, set[str]] = {}
# `macro_rules!` macros defined in this file, keyed by bare name. A macro and a
# function can share a name in Rust (`vec!` vs `vec`), and a macro is invoked
# as `name!(...)` (a `macro_invocation`, never a `call_expression`), so macros
# are resolved through their own registry rather than the function/type
# label_to_nid to avoid cross-binding.
macro_nids_by_name: dict[str, str] = {}
# `mod m { .. }` blocks declared in this file, so a `m::f()` call can bind
# in-file; `mod m;` declares a module that lives in another file.
inline_mods: set[str] = set()
_mod_stack = [root]
while _mod_stack:
_n = _mod_stack.pop()
if _n.type == "mod_item" and _n.child_by_field_name("body") is not None:
_name = _n.child_by_field_name("name")
if _name is not None:
inline_mods.add(_read_text(_name, source))
_mod_stack.extend(_n.children)
# (bare impl type, method name) -> the method nodes this file's `impl` blocks
# define, so an in-file `Type::f()` / `self.f()` binds to a method of that type.
impl_methods: dict[tuple[str, str], set[str]] = {}
# Nodes by id, so a declaration's node is found without scanning every node
# (once per declaration, that scan was quadratic in the file's size).
node_by_id: dict[str, dict] = {}
def add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
node_by_id[nid] = {
"id": nid,
"label": label,
"file_type": "code",
"source_file": str_path,
"source_location": f"L{line}",
})
}
nodes.append(node_by_id[nid])
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0,
@@ -314,6 +378,7 @@ def extract_rust(path: Path) -> dict:
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
decl_registry = DeclIdRegistry(reserved_ids=(file_nid,))
# Pre-scan the struct/enum/trait names declared in this file so a type used
# above its declaration resolves exactly as a use below it already does,
@@ -337,15 +402,15 @@ def extract_rust(path: Path) -> dict:
def _scan_type_items(node) -> None:
t = node.type
if t in ("struct_item", "enum_item", "trait_item", "function_item",
"function_signature_item", "static_item", "const_item"):
if t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item",
"function_item", "function_signature_item", "static_item", "const_item"):
name_node = node.child_by_field_name("name")
if name_node:
name = _read_text(name_node, source)
if t in ("static_item", "const_item") and name == "_":
return
nid = _make_id(stem, name)
is_type = t in ("struct_item", "enum_item", "trait_item")
is_type = t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item")
items_by_id.setdefault(nid, set()).add((is_type, name))
if is_type:
declared_type_names.setdefault(nid, set()).add(name)
@@ -385,13 +450,12 @@ def extract_rust(path: Path) -> dict:
# outcome never depends on declaration order. Repeats of one name (`#[cfg]`
# twins, an `impl` of a local type) are one member and still share a node.
def file_item_nid(plain_nid: str, name: str) -> str:
nid = plain_nid
names = {item_name for _is_type, item_name in items_by_id.get(plain_nid, ())}
if len(names) < 2 or name not in names:
return plain_nid
if declared_type_names.get(plain_nid) == {name}:
return plain_nid
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
return _make_id(plain_nid, salt)
if len(names) >= 2 and name in names and declared_type_names.get(plain_nid) != {name}:
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
nid = _make_id(plain_nid, salt)
return decl_registry.resolve(nid, name, "type", seen_ids)
def ensure_named_node(name: str, line: int) -> str:
nid = file_item_nid(_make_id(stem, name), name)
@@ -407,14 +471,15 @@ def extract_rust(path: Path) -> dict:
# file's path (with extension) into the id and blocks the rewire, which is
# the phantom-duplicate-node bug (#1402).
seen_ids.add(nid)
nodes.append({
node_by_id[nid] = {
"id": nid,
"label": name,
"file_type": "code",
"source_file": "",
"source_location": "",
"origin_file": str_path,
})
}
nodes.append(node_by_id[nid])
return nid
def emit_param_return_refs(func_node, func_nid: str, line: int) -> None:
@@ -514,14 +579,20 @@ def extract_rust(path: Path) -> dict:
macro_nids_by_name.setdefault(macro_name, macro_nid)
return
if t in ("struct_item", "enum_item", "trait_item"):
# An associated type in an `impl` body (`type Output = Meters;`) is a
# type_item too, but not a file-level item: it would mint one colliding
# `Output` node per `impl Add`. Only an alias at module level is one.
if t == "type_item" and node.parent is not None and node.parent.parent is not None \
and node.parent.parent.type == "impl_item":
return
if t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item"):
name_node = node.child_by_field_name("name")
if name_node:
item_name = _read_text(name_node, source)
line = node.start_point[0] + 1
item_nid = file_item_nid(_make_id(stem, item_name), item_name)
add_node(item_nid, item_name, line)
declaration_node = next(n for n in nodes if n["id"] == item_nid)
declaration_node = node_by_id[item_nid]
declaration_node["_rust_declaration_count"] = (
declaration_node.get("_rust_declaration_count", 0) + 1
)
@@ -545,7 +616,7 @@ def extract_rust(path: Path) -> dict:
else:
add_edge(item_nid, tgt, "references", line,
context="generic_arg")
if t == "struct_item":
if t in ("struct_item", "union_item"):
for c in node.children:
if c.type != "field_declaration_list":
continue
@@ -729,7 +800,7 @@ def extract_rust(path: Path) -> dict:
impl_keys[impl_nid] = impl_key
elif impl_keys[impl_nid] != impl_key:
impl_keys[impl_nid] = None
impl_node = next(n for n in nodes if n["id"] == impl_nid)
impl_node = node_by_id[impl_nid]
if impl_keys[impl_nid]:
impl_node["_rust_impl_key"] = impl_keys[impl_nid]
else:
@@ -756,6 +827,17 @@ def extract_rust(path: Path) -> dict:
and (name_node := sibling.child_by_field_name("name")) is not None
}
# A plain `pub use` re-exports the named item from the crate its path
# starts with, so a later `use this_crate::Item` may reach a definition
# that lives in that crate (#4699). `pub(crate)` and `pub(super)` stay
# inside the re-exporting crate, so only a bare `pub` counts.
visibility = next(
(child for child in node.children if child.type == "visibility_modifier"),
None,
)
reexport = visibility is not None and _read_text(
visibility, source).strip() == "pub"
def name_use(written: str, path: str) -> None:
# The name as written, for the corpus rewire (#4439): the id folds its
# case. Only for a path rooted in this crate: `serde::Serialize` or
@@ -764,6 +846,7 @@ def extract_rust(path: Path) -> dict:
# too (`mod item; pub use item::Invoice;`), unless the path starts with
# `::`, which always names a crate (#4564).
first = path.lstrip(": ").split("::")[0].strip()
bound = written.split(" as ")[-1].strip()
ident = re.match(r"[A-Za-z_][A-Za-z0-9_]*", first) # `item as items` -> `item`
if first in ("crate", "self", "super") or (
ident is not None
@@ -771,6 +854,11 @@ def extract_rust(path: Path) -> dict:
and not path.lstrip().startswith("::")
):
edges[-1]["_rust_use_name"] = written.split(" as ")[0].strip()
use_roots.setdefault(bound, set()).add("crate")
else:
use_roots.setdefault(bound, set()).add(first)
if reexport and bound.isidentifier():
edges[-1]["_rust_pub_use"] = {"label": bound, "root": first}
module_name = _rust_use_module(_read_text(arg, source))
grouped = arg.type in ("use_list", "scoped_use_list")
if module_name:
@@ -816,6 +904,7 @@ def extract_rust(path: Path) -> dict:
seen_call_pairs: set[tuple[str, str]] = set()
raw_calls: list[dict] = []
macro_arg_edges: list[dict] = []
def walk_calls(
node,
@@ -849,10 +938,48 @@ def extract_rust(path: Path) -> dict:
"source_location": f"L{line}",
"weight": 1.0,
})
# Fall through to the generic child recursion below rather than
# returning, preserving the prior traversal of the invocation's
# subtree (its arguments are a raw token tree, so this neither adds
# nor drops any nested edges relative to before).
# A call inside the arguments is only a token pattern, not a parsed
# call: bind it in-file as INFERRED, or hand it to the cross-file pass.
args = next((c for c in node.children if c.type == "token_tree"), None)
invoked = macro_node.child_by_field_name("name") if (
macro_node is not None and macro_node.type == "scoped_identifier") else macro_node
if args is None or invoked is None or (
_read_text(invoked, source) not in _RUST_EXPRESSION_MACROS):
args = None
for callee_name, line in _rust_macro_arg_calls(args) if args is not None else ():
if (
callee_name[:1].isupper()
or callee_name in _LANGUAGE_BUILTIN_GLOBALS
or callee_name in _RUST_BUILTIN_TYPES
or callee_name.lower() in _RUST_TRAIT_METHOD_BLOCKLIST
):
continue
tgt_nid = label_to_nid.get(callee_name)
if tgt_nid in type_nids:
continue
if tgt_nid:
if tgt_nid != caller_nid:
macro_arg_edges.append({
"source": caller_nid,
"target": tgt_nid,
"relation": "calls",
"context": "macro_argument_call",
"confidence": "INFERRED",
"confidence_score": 0.85,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
continue
raw_calls.append({
"caller_nid": caller_nid,
"callee": callee_name,
"is_member_call": False,
"source_file": str_path,
"source_location": f"L{line}",
})
# Fall through to the generic child recursion below; the token tree
# holds no call_expression, so nothing is counted twice.
if node.type == "call_expression":
func_node = node.child_by_field_name("function")
callee_name: str | None = None
@@ -903,6 +1030,16 @@ def extract_rust(path: Path) -> dict:
tgt_nid = named if named in type_nids else None
elif is_member_call:
tgt_nid = method_label_to_nid.get(callee_name)
elif is_scoped_call:
# `m::f()` names module m. It is in this file only for
# `self::f()` or an inline `mod m { .. }` declared here; any
# other module lives in another file, so the bare-name match
# would bind `crate::b::helper()` to this file's own helper.
path_node = func_node.child_by_field_name("path") if func_node else None
qual = _read_text(path_node, source) if path_node is not None else ""
head = qual.split("::")[-1].strip()
tgt_nid = label_to_nid.get(callee_name) if (
qual == "self" or head in inline_mods) else None
else:
tgt_nid = label_to_nid.get(callee_name)
if tgt_nid and tgt_nid != caller_nid:
@@ -921,7 +1058,29 @@ def extract_rust(path: Path) -> dict:
"source_location": f"L{line}",
"weight": 1.0,
})
elif not is_scoped_call and callee_name.lower() not in _RUST_TRAIT_METHOD_BLOCKLIST:
elif is_scoped_call:
# A module-qualified call (`crate::m::f()`, `m::f()`, `super::m::f()`)
# goes to the cross-file pass with its qualifier, which binds it only
# when the qualifier matches the candidate's module path and exactly
# one candidate survives. Bare last-segment lookup stays off (#908).
qual_node = func_node.child_by_field_name("path")
qualifier = _read_text(qual_node, source) if qual_node else ""
# `use std::fs; fs::read()` names std's fs, never a local `fs.rs`.
first_seg = qualifier.split("::", 1)[0].split("<", 1)[0].strip()
roots = use_roots.get(first_seg, {"crate"})
if not roots <= {"crate", "super", "self"}:
qualifier = ""
if qualifier:
raw_calls.append({
"caller_nid": caller_nid,
"callee": callee_name,
"is_member_call": False,
"is_scoped_call": True,
"scope_qualifier": qualifier,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
elif callee_name.lower() not in _RUST_TRAIT_METHOD_BLOCKLIST:
rc_entry = {
"caller_nid": caller_nid,
"callee": callee_name,
@@ -939,6 +1098,17 @@ def extract_rust(path: Path) -> dict:
for caller_nid, body_node, impl_type, impl_key in function_bodies:
walk_calls(body_node, caller_nid, impl_type, impl_key)
# Added last: a parsed call to the same target in the same function keeps
# its EXTRACTED edge instead of being deduped behind the token-pattern one.
for edge in macro_arg_edges:
pair = (edge["source"], edge["target"])
if pair not in seen_call_pairs:
seen_call_pairs.add(pair)
edges.append(edge)
for node in nodes:
if not node["source_file"] and node["label"] in use_roots:
node["_rust_use_roots"] = sorted(use_roots[node["label"]])
valid_ids = seen_ids
clean_edges = []
File diff suppressed because it is too large. Load diff
+219 -11
View File
@@ -59,6 +59,22 @@ _TRIGGER_RECOVERY_RX = re.compile(
re.IGNORECASE | re.DOTALL,
)
# CREATE TABLE recovery, sibling to the routine/trigger patterns above. A
# column default the grammar cannot model — MySQL/MariaDB
# `DEFAULT current_timestamp()` / `ON UPDATE current_timestamp()`, whose
# parentheses tree-sitter-sql rejects (upstream DerekStride/tree-sitter-sql)
# — puts the whole statement in an ERROR node, so walk() never dispatches on
# it and the table vanished, leaving only the sourceless stub that other
# tables' REFERENCES minted for it (#4613). The name atom is _TRIGGER_IDENT
# (the same delimited-identifier shape); the label is the bare name, with no
# `()` suffix — a table is not callable either.
_TABLE_RECOVERY_RX = re.compile(
r"\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?TABLE\s+"
r"(?:IF\s+NOT\s+EXISTS\s+)?"
r"(" + _TRIGGER_IDENT + r")",
re.IGNORECASE,
)
# _mask_sql_comments is a linear character scanner, not a regex: the four
# span kinds interact in ways a single pattern cannot express safely —
# comment-opener parity inside strings, nested block comments, and
@@ -263,27 +279,173 @@ def _scan_sql(text: str) -> tuple[str, list[tuple[int, int]]]:
return "".join(out), ident_spans
# A procedure body is read as TEXT, not from the tree: tree-sitter-sql has no
# procedure production, and without `;` it merges the body's statements into
# one malformed expression. The body of a recovered routine runs from the end
# of its name to the next CREATE/ALTER at the start of a line (`CREATE TABLE
# #tmp` / `@tbl` inside a body does not end it), a line holding only `GO [n]`,
# or EOF. Run over the comment- and string-masked text from _scan_sql.
_BODY_END_RX = re.compile(
r"^[ \t]*(?:GO(?:[ \t]+\d+)?[ \t\r]*;?[ \t\r]*$|(?:CREATE|ALTER)\b(?!\s+TABLE\s+[#@]))",
re.IGNORECASE | re.MULTILINE,
)
# `(?![\w$]|\s*\.)` stops the identifier atom from backtracking to a prefix of
# a longer name (`tempdb..#x`, `dbo.fn(`) and matching that instead.
_BODY_TAIL = r"(?![\w$]|\s*\.)"
_BODY_READ_RX = re.compile(r"\b(?:FROM|JOIN)\s+(" + _TRIGGER_IDENT + r")" + _BODY_TAIL, re.IGNORECASE)
_BODY_WRITE_RX = re.compile(
r"\b(INSERT(?:\s+INTO)?|UPDATE(?:\s+TOP\s*\([^)]*\))?|DELETE(?:\s+TOP\s*\([^)]*\))?(?:\s+FROM)?"
r"|MERGE(?:\s+INTO)?|INTO)\s+(" + _TRIGGER_IDENT + r")" + _BODY_TAIL,
re.IGNORECASE,
)
_BODY_ALIAS_RX = re.compile(r"\s+(?:AS\s+)?([A-Za-z_][\w$]*)", re.IGNORECASE)
_BODY_CTE_RX = re.compile(r"(?:\bWITH\s+(?:RECURSIVE\s+)?|,\s*)([\w$]+)\s*(?:\([^()]*\))?\s+AS\s*\(", re.IGNORECASE)
# `ON DELETE`, `FOR UPDATE`, `AFTER INSERT, UPDATE`: an event or lock clause, not a statement.
_BODY_EVENT_RX = re.compile(r"(?:\b(?:ON|FOR|AFTER|BEFORE|OF)|,)\s*$", re.IGNORECASE)
# `EXTRACT(year FROM d)`, `TRIM(x FROM y)` and `FETCH NEXT FROM cur`: a FROM that names no table.
_BODY_FROM_NOT_TABLE_RX = re.compile(
r"(?:\b(?:EXTRACT|TRIM|SUBSTRING|OVERLAY|POSITION)\s*\([^()]*|\bDISTINCT\s+"
r"|\bFETCH\s+(?:NEXT|PRIOR|FIRST|LAST|(?:ABSOLUTE|RELATIVE)\s+\S+)\s+)$",
re.IGNORECASE,
)
# Words that can follow FROM/JOIN/INTO/UPDATE/... without naming a table, and
# words that cannot be an alias.
_BODY_NON_TABLES = frozenset({
"select", "where", "set", "dual", "null", "true", "false", "first", "skip",
"rows", "next", "only", "lateral", "values", "when", "then", "output", "default",
"cascade", "with", "top", "statistics", "into", "as", "on", "using", "not",
"exists", "inserted", "deleted", "openquery", "openrowset", "opendatasource",
"inner", "left", "right", "full", "cross", "outer", "join", "group", "order",
"having", "union", "except", "intersect", "option", "for", "from", "where",
"pivot", "unpivot", "tablesample", "natural", "apply",
})
def _routine_body_refs(masked: str) -> list[tuple[str, str, int]]:
"""(relation, table name as written, offset) for each table a masked
routine body reads (`FROM`/`JOIN`) or writes (`INSERT`/`UPDATE`/`DELETE`/
`MERGE`/`SELECT ... INTO`), in source order. Temp tables and variables never
match the identifier atom; CTE names and keywords are dropped; the target of
`UPDATE o ... FROM dbo.Orders o` is resolved through the alias."""
non_tables = set(_BODY_NON_TABLES)
for cm in _BODY_CTE_RX.finditer(masked):
non_tables.add(_norm_ident(cm.group(1)))
def _usable(name: str) -> bool:
return _norm_ident(name) not in non_tables
writes: list[tuple[int, int, str, str]] = [] # (start, end, relation, name)
for m in _BODY_WRITE_RX.finditer(masked):
if m.group(1).upper() != "INTO" and _BODY_EVENT_RX.search(masked[max(0, m.start() - 30):m.start()]):
continue
if _usable(m.group(2)):
writes.append((m.start(), m.end(), "writes_to", m.group(2)))
reads: list[tuple[int, str]] = []
aliases: dict[str, str] = {}
for m in _BODY_READ_RX.finditer(masked):
if any(s <= m.start() < e for s, e, _r, _n in writes):
continue # the FROM directly after DELETE names the write target
if _BODY_FROM_NOT_TABLE_RX.search(masked[max(0, m.start() - 200):m.start()]):
continue
# `FROM dbo.fn_split(@x)` calls a table-valued function: not a table.
if not _usable(m.group(1)) or masked[m.end():].lstrip().startswith("("):
continue
reads.append((m.start(), m.group(1)))
am = _BODY_ALIAS_RX.match(masked, m.end())
if am and am.group(1).lower() not in non_tables:
aliases.setdefault(am.group(1).lower(), m.group(1))
refs = [(pos, "reads_from", name) for pos, name in reads]
for pos, _end, relation, name in writes:
if "." not in name:
name = aliases.get(name.lower(), name)
refs.append((pos, relation, name))
return [(relation, name, pos) for pos, relation, name in sorted(refs)]
# A `GO` batch separator is a client-tool command, not SQL: tree-sitter-sql reads it as an
# identifier, so without a `;` before it the next statement is swallowed into an ERROR node.
# Found on the masked text (comments and strings blanked), alone on its line, optionally
# followed by a repeat count.
_GO_LINE_RX = re.compile(r"^[ \t]*(GO(?:[ \t]+\d+)?)[ \t\r]*;?[ \t\r]*$", re.IGNORECASE | re.MULTILINE)
def _go_separators(source: bytes) -> list[tuple[int, int]]:
"""Byte spans of the `GO [n]` batch-separator lines in a T-SQL script.
A bare `go` on its own line is a column or alias, not a separator, only when the last
non-blank character before it is a comma or the first one after it is a comma or `)`.
Any keyword may precede a real separator (`SET NOCOUNT ON` / `GO`), so none is consulted.
"""
try:
text = source.decode("utf-8")
except UnicodeDecodeError:
return []
masked = _scan_sql(text)[0]
spans: list[tuple[int, int]] = []
size = len(masked)
char_pos = byte_pos = 0 # a character offset and its byte offset, advanced as matches are met
for m in _GO_LINE_RX.finditer(masked):
before, after = m.start() - 1, m.end()
while before >= 0 and masked[before].isspace():
before -= 1
while after < size and masked[after].isspace():
after += 1
start, end = m.start(1), m.end(1)
byte_start = byte_pos + len(text[char_pos:start].encode("utf-8"))
byte_end = byte_start + len(text[start:end].encode("utf-8"))
char_pos, byte_pos = end, byte_end
if (before >= 0 and masked[before] == ",") or (after < size and masked[after] in ",)"):
continue
spans.append((byte_start, byte_end))
return spans
def _mask_sql_comments(text: str) -> str:
"""Masked text only — see _scan_sql for the span-reporting form."""
return _scan_sql(text)[0]
def _clean_part(part: str) -> str:
"""One name part without T-SQL brackets. The parser hands over `dbo].[Orders`
for `[dbo].[Orders]`, so a part may keep only one of its two brackets; `]]`
inside a bracketed name is an escaped `]`."""
return part.removeprefix("[").removesuffix("]").replace("]]", "]")
def _clean_ident(name: str) -> str:
"""Display form of an object name: T-SQL brackets removed, schema kept.
`[dbo].[Orders]` and the parser's `dbo].[Orders` both give `dbo.Orders`.
Double-quoted parts keep their quotes. Labels only: node ids come from the
text as written and are not touched.
"""
if "[" not in name and "]" not in name:
return name
return ".".join(
p if p.startswith('"') else _clean_part(p) for p in (part.strip() for part in name.split("."))
)
def _norm_ident(name: str) -> str:
"""Normalize a SQL identifier for name-based reference resolution.
Splits on `.`, strips one pair of surrounding delimiters from each part
(double quotes for Postgres/ANSI, backticks for MySQL, brackets for
T-SQL), lowercases, and rejoins. So `"public"."users"`, `public.users`,
and `PUBLIC.USERS` all normalize to `public.users`. Used ONLY for
and `PUBLIC.USERS` all normalize to `public.users`, and `[dbo].[Orders]`,
the parser's `dbo].[Orders` and `dbo.Orders` to `dbo.orders`. Used ONLY for
`table_nids` keys and lookups — node ids and display labels keep the
original text.
"""
parts = []
for part in name.split("."):
p = part.strip()
if len(p) >= 2 and ((p[0] == p[-1] and p[0] in ('"', "`"))
or (p[0] == "[" and p[-1] == "]")):
if len(p) >= 2 and p[0] == p[-1] and p[0] in ('"', "`"):
p = p[1:-1]
else:
p = _clean_part(p)
parts.append(p.lower())
return ".".join(parts)
@@ -314,7 +476,11 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
else content if content is not None
else _read_source_bytes(path)
)
tree = parser.parse(source)
# `GO` is not SQL; as `;` (same length, so offsets and lines hold) it ends the statement.
patched = bytearray(source)
for start, end in _go_separators(source):
patched[start:end] = b";" + b" " * (end - start - 1)
tree = parser.parse(bytes(patched))
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
@@ -371,7 +537,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
nid = _make_id(name)
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({"id": nid, "label": name, "file_type": "code",
nodes.append({"id": nid, "label": _clean_ident(name), "file_type": "code",
"source_file": "", "source_location": "",
"origin_file": str_path})
return nid
@@ -384,7 +550,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, name, line)
_add_node(nid, _clean_ident(name), line)
table_nids[_norm_ident(name)] = nid
# Foreign key REFERENCES
for col in node.children:
@@ -439,7 +605,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, name, line)
_add_node(nid, _clean_ident(name), line)
table_nids[_norm_ident(name)] = nid
# FROM/JOIN table references inside view body
_walk_from_refs(node, nid, line)
@@ -448,7 +614,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, f"{name}()", line)
_add_node(nid, f"{_clean_ident(name)}()", line)
routine_nids[_norm_ident(name)] = nid
_walk_from_refs(node, nid, line)
@@ -456,7 +622,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, f"{name}()", line)
_add_node(nid, f"{_clean_ident(name)}()", line)
routine_nids[_norm_ident(name)] = nid
_walk_from_refs(node, nid, line)
@@ -663,6 +829,8 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
for child in node.children:
_walk_from_refs(child, caller_nid, line, cte_names)
src_text = source.decode("utf-8", errors="replace")
# Pre-pass: register every table/view DEFINED in this file before walking,
# so forward references (a FK to a table created later in the same file)
# still resolve to the real sourced node instead of falling back to a stub.
@@ -676,6 +844,21 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
_collect_defined_names(root)
# A CREATE TABLE the grammar failed on (#4613) never reaches the pre-pass
# — its statement sits inside an ERROR node — so references to it would
# mint sourceless stubs and the REFERENCES fallback below would skip it.
# When the parse failed, pre-register the recovered table names from the
# masked source so resolution sees the real id; the node itself is
# emitted in the has_error fallback, alongside the recovered routines
# and triggers.
if root.has_error:
_masked, _ident_spans = _scan_sql(src_text)
for m in _TABLE_RECOVERY_RX.finditer(_masked):
if any(s <= m.start() < e for s, e in _ident_spans):
continue
table_nids.setdefault(
_norm_ident(m.group(1)), _make_id(stem, m.group(1)))
# Secondary bare-name aliases: a reference written without a schema
# (`REFERENCES users`) should resolve to a schema-qualified definition
# (`public.users`) when that is unambiguous. Never shadow an explicit
@@ -711,7 +894,6 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
# (e.g. Firebird COMPUTED BY columns push constraints out of the tree entirely).
# Snapshot after tree walk so we don't re-emit edges already captured above.
emitted = {(e["source"], e["target"]) for e in edges if e["relation"] == "references"}
src_text = source.decode("utf-8", errors="replace")
for m in re.finditer(r"CREATE\s+TABLE\s+([\w$]+)\s*\(", src_text, re.IGNORECASE):
tbl_name = m.group(1)
tbl_nid = table_nids.get(_norm_ident(tbl_name))
@@ -765,7 +947,21 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
continue
fn_name = m.group(1)
fn_line = src_text[: m.start()].count("\n") + 1
_add_node(_make_id(stem, fn_name), f"{fn_name}()", fn_line)
fn_nid = _make_id(stem, fn_name)
# A routine the tree already produced (a cleanly parsed function)
# keeps its tree-based reads_from; scanning it too would double them.
from_tree = fn_nid in seen_ids
_add_node(fn_nid, f"{_clean_ident(fn_name)}()", fn_line)
if from_tree:
continue
end = _BODY_END_RX.search(masked_src, m.end())
seen_refs: set[tuple[str, str]] = set()
for relation, tbl, pos in _routine_body_refs(masked_src[m.end():end.start() if end else len(masked_src)]):
tbl_nid = table_nids.get(_norm_ident(tbl)) or _ref_stub(_clean_ident(tbl))
if (relation, tbl_nid) in seen_refs:
continue
seen_refs.add((relation, tbl_nid))
_add_edge(fn_nid, tbl_nid, relation, masked_src.count("\n", 0, m.end() + pos) + 1)
for m in _TRIGGER_RECOVERY_RX.finditer(masked_src):
if any(s <= m.start() < e for s, e in ident_spans):
@@ -782,4 +978,16 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
tbl_nid = table_nids.get(_norm_ident(tbl_name)) or _ref_stub(tbl_name)
_add_edge(trig_nid, tbl_nid, "triggers", trig_line)
# Tables the grammar dropped into an ERROR node (#4613), pre-registered
# above so references already resolved to this id. _add_node dedupes,
# so a table that parsed cleanly keeps its walk-emitted node.
for m in _TABLE_RECOVERY_RX.finditer(masked_src):
if any(s <= m.start() < e for s, e in ident_spans):
continue
tbl_name = m.group(1)
tbl_line = src_text[: m.start()].count("\n") + 1
# Clean the label (brackets/quotes) for display but key the id off the
# raw name so it matches the pre-pass registration the FK edges resolved to.
_add_node(_make_id(stem, tbl_name), _clean_ident(tbl_name), tbl_line)
return {"nodes": nodes, "edges": edges}
+65 -12
View File
@@ -9,6 +9,7 @@ from collections.abc import Sequence
from pathlib import Path
from graphify.extractors.base import _make_id, _read_source_bytes
from graphify.security import (
REDACTED_MARKER,
_CONTROL_CHAR_RE,
_METADATA_MAX_ATTRIBUTES,
_METADATA_MAX_LIST_ITEMS,
@@ -31,7 +32,7 @@ _SENSITIVE_KEY_RE = re.compile(
r"sas[-_]?token|auth|passphrase)",
re.IGNORECASE,
)
_REDACTED = "[redacted]"
_REDACTED = REDACTED_MARKER
_PAIRED_VALUE_KEYS = frozenset({"value", "valuefrom", "value_from"})
@@ -78,13 +79,17 @@ def _scope_id(directory: str) -> str:
def prepare_terraform(result: dict, path: Path, root: Path) -> None:
"""Make cached directory-scoped IDs portable before the common merge passes."""
"""Make cached directory-scoped IDs portable before the common merge passes.
Consume the internal scope metadata even when the file is outside root.
"""
directory = path.parent.resolve()
old = result.pop("_terraform_scope", _scope_id(directory.as_posix()))
try:
relative = directory.relative_to(root).as_posix()
except ValueError:
return
old, new = _scope_id(directory.as_posix()), _scope_id(relative)
new = _scope_id(relative)
for node in result.get("nodes", []):
nid = node["id"]
if nid.startswith(old + "_"):
@@ -257,7 +262,7 @@ def extract_terraform(path: Path) -> dict:
labels.append(_label_text(c))
return btype, labels
def _ref_address(expr):
def _head_and_attrs(expr) -> tuple[str, list[str]]:
head = _read(expr)
parent = expr.parent
attrs: list[str] = []
@@ -278,6 +283,10 @@ def extract_terraform(path: Path) -> dict:
attrs.append(name)
elif seen_self and c.type not in ("get_attr",):
break
return head, attrs
def _ref_address(expr):
head, attrs = _head_and_attrs(expr)
if head in _TF_META_HEADS or not head:
return None
if head == "var":
@@ -290,21 +299,36 @@ def extract_terraform(path: Path) -> dict:
return f"data.{attrs[0]}.{attrs[1]}" if len(attrs) >= 2 else None
return f"{head}.{attrs[0]}" if attrs else None
def _collect_refs(node, owner_nid: str, relation: str) -> None:
def _provider_ref_address(expr):
# A `provider = aws.west` value names a provider BLOCK by type and
# alias, the same `head.attr` shape `_ref_address` already reads for
# a resource reference (`aws_instance.web.id` -> `aws_instance.web`).
# Without this, `aws.west` fell through to that generic reading and
# pointed at a node that was never minted.
head, attrs = _head_and_attrs(expr)
if not head:
return None
return f"provider.{head}.{attrs[0]}" if attrs else f"provider.{head}"
def _collect_refs(node, owner_nid: str, relation: str, in_provider_attr: bool = False) -> None:
rel = relation
provider_attr = in_provider_attr
if node.type == "attribute":
key_node = node.child_by_field_name("key") or (
node.children[0] if node.children else None
)
if key_node is not None and _read(key_node) == "depends_on":
rel = "depends_on"
if key_node is not None:
key_text = _read(key_node)
if key_text == "depends_on":
rel = "depends_on"
provider_attr = key_text == "provider"
if node.type == "variable_expr":
addr = _ref_address(node)
addr = _provider_ref_address(node) if provider_attr else _ref_address(node)
if addr:
_add_edge(owner_nid, addr, rel, node.start_point[0] + 1)
for c in node.children:
if c.is_named:
_collect_refs(c, owner_nid, rel)
_collect_refs(c, owner_nid, rel, provider_attr)
def _clean_val_str(text: str) -> str:
text = _CONTROL_CHAR_RE.sub("", str(text))
@@ -428,7 +452,29 @@ def extract_terraform(path: Path) -> dict:
elif btype == "output" and labels:
owner = _add_node(f"output.{labels[0]}", f"output.{labels[0]}", line)
elif btype == "provider" and labels:
owner = _add_node(f"provider.{labels[0]}", f"provider.{labels[0]}", line)
# An aliased provider block (`provider "aws" { alias = "west" }`)
# configures a SECOND, distinct provider of the same type. Without
# the alias in the id, a second `provider "aws" {...}` block for a
# different alias collapsed onto the same node as the first,
# silently losing its own attributes to whichever block the walk
# reached last.
alias = None
if blk_body is not None:
for attr in blk_body.children:
if attr.type != "attribute":
continue
k_node = attr.children[0] if attr.children else None
if k_node is None or _read(k_node) != "alias":
continue
v_node = attr.named_children[-1] if attr.named_children else None
if v_node is None:
continue
alias_val = _parse_attr_value(v_node)
if isinstance(alias_val, str) and alias_val:
alias = alias_val
break
address = f"provider.{labels[0]}.{alias}" if alias else f"provider.{labels[0]}"
owner = _add_node(address, address, line)
elif btype == "locals" and blk_body is not None:
for attr in blk_body.children:
if attr.type != "attribute":
@@ -438,7 +484,14 @@ def extract_terraform(path: Path) -> dict:
continue
key = _read(key_node)
lnid = _add_node(f"local.{key}", f"local.{key}", attr.start_point[0] + 1)
_collect_refs(attr, lnid, "references")
# Walk the VALUE only, not the attribute itself -- the local's
# own name sits in the same `key` slot `_collect_refs` reads to
# detect a `provider = ...`/`depends_on = ...` attribute, so a
# local literally named either would otherwise be misread as
# one.
value_node = attr.named_children[-1] if attr.named_children else None
if value_node is not None:
_collect_refs(value_node, lnid, "references")
continue
else:
continue
@@ -459,4 +512,4 @@ def extract_terraform(path: Path) -> dict:
nodes_by_id[owner]["attributes"] = attrs
_collect_refs(blk_body, owner, "references")
return {"nodes": nodes, "edges": edges}
return {"nodes": nodes, "edges": edges, "_terraform_scope": scope}
+10 -6
View File
@@ -128,11 +128,10 @@ def extract_vbnet(path: Path) -> dict:
"id": nid,
"label": label,
"file_type": "code",
"source_location": f"L{node.start_point[0] + 1}",
"source_file": source_file if source_backed else "",
"source_location": f"L{node.start_point[0] + 1}" if source_backed else "",
"metadata": details,
}
if source_backed:
item["source_file"] = source_file
if callable_node:
item["_callable"] = True
nodes.append(item)
@@ -267,7 +266,9 @@ def extract_vbnet(path: Path) -> dict:
if member.type == "event_declaration":
events[(owner_key, data_name.casefold())] = member_id
continue
if member.type not in {"method_declaration", "constructor_declaration"}:
if member.type not in {
"method_declaration", "constructor_declaration", "operator_declaration",
}:
continue
if member.type == "constructor_declaration":
@@ -278,7 +279,9 @@ def extract_vbnet(path: Path) -> dict:
if method_name_node is None:
continue
method_name = _read_text(method_name_node, source)
method_kind = "method"
method_kind = (
"operator" if member.type == "operator_declaration" else "method"
)
parameters = member.child_by_field_name("parameters")
parameter_nodes = (
[child for child in parameters.named_children if child.type == "parameter"]
@@ -381,7 +384,8 @@ def extract_vbnet(path: Path) -> dict:
while stack:
node = stack.pop()
if node != body and node.type in {
"method_declaration", "constructor_declaration", "property_declaration"
"method_declaration", "constructor_declaration", "property_declaration",
"operator_declaration",
}:
continue
if node.type == "invocation":
+43 -6
View File
@@ -47,8 +47,20 @@ _SV_PARENS_INNER = r"(?:[^()]|\([^()]*\))*"
_SV_PARENS = r"\(" + _SV_PARENS_INNER + r"\)"
# The return type is optional: a `new` constructor never has one, and a plain
# `function foo(...);` implicitly returns a 1-bit value. Without the `?` here,
# every constructor method - the single most common one in a SystemVerilog
# class - matched nothing at all: no node, no parameter-type references.
_SV_FUNC_RE = re.compile(
r"\bfunction\s+([A-Za-z_]\w*(?:\s*#\s*" + _SV_PARENS + r")?)\s+(\w+)\s*"
r"\bfunction\s+(?:([A-Za-z_]\w*(?:\s*#\s*" + _SV_PARENS + r")?)\s+)?(\w+)\s*"
r"\((" + _SV_PARENS_INNER + r")\)\s*;",
re.MULTILINE,
)
# A class method declared `task` instead of `function` has no return type to
# capture, otherwise the same header shape.
_SV_TASK_RE = re.compile(
r"\btask\s+(\w+)\s*"
r"\((" + _SV_PARENS_INNER + r")\)\s*;",
re.MULTILINE,
)
@@ -167,21 +179,30 @@ def _augment_systemverilog_semantics(
for iface_name in _sv_split_type_list(impl.group(1)):
add_edge(class_nid, iface_name.split("#", 1)[0].strip(), "implements", line)
body_without_functions = re.sub(
# A `task` method's own locals (and any typed declaration inside its
# body) must not leak into the field scan below, exactly like a
# function's body already doesn't - so both get stripped the same way.
body_without_methods = re.sub(
r"\bfunction\b.*?\bendfunction\b",
lambda m: "\n" * m.group(0).count("\n"),
body,
flags=re.DOTALL,
)
body_without_methods = re.sub(
r"\btask\b.*?\bendtask\b",
lambda m: "\n" * m.group(0).count("\n"),
body_without_methods,
flags=re.DOTALL,
)
# Optional leading class-property qualifiers (rand/local/protected/etc.)
# must be consumed: otherwise a qualified field like `rand Config x;`
# (three tokens) fails the `<type> <name>;` shape and its type reference
# is silently dropped.
for field in re.finditer(r"^\s*(?:(?:rand|randc|local|protected|static|const|automatic|var)\s+)*([A-Za-z_]\w*(?:\s*#\s*\([^;]+?\))?)\s+\w+\s*;", body_without_functions, re.MULTILINE):
for field in re.finditer(r"^\s*(?:(?:rand|randc|local|protected|static|const|automatic|var)\s+)*([A-Za-z_]\w*(?:\s*#\s*\([^;]+?\))?)\s+\w+\s*;", body_without_methods, re.MULTILINE):
# Count to the start of the type token (group 1), not the match
# start: `^\s*` consumes the leading newline(s), so field.start()
# would resolve to the class's line instead of the field's.
field_line = line + body_without_functions.count("\n", 0, field.start(1))
field_line = line + body_without_methods.count("\n", 0, field.start(1))
for ref_name, role in _sv_collect_type_refs(field.group(1), skip=type_params):
add_edge(class_nid, ref_name, "references", field_line, "generic_arg" if role == "generic_arg" else "field")
@@ -193,8 +214,9 @@ def _augment_systemverilog_semantics(
edges.append({"source": class_nid, "target": func_nid, "relation": "method",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str_path, "source_location": f"L{func_line}", "weight": 1.0})
for ref_name, role in _sv_collect_type_refs(return_type, skip=type_params):
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "return_type")
if return_type:
for ref_name, role in _sv_collect_type_refs(return_type, skip=type_params):
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "return_type")
for param in _sv_split_type_list(params):
pm = _SV_PARAM_RE.match(param)
if not pm:
@@ -202,6 +224,21 @@ def _augment_systemverilog_semantics(
for ref_name, role in _sv_collect_type_refs(pm.group(1), skip=type_params):
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "parameter_type")
for tm in _SV_TASK_RE.finditer(body):
task_name, params = tm.group(1), tm.group(2)
task_line = line + body.count("\n", 0, tm.start())
task_nid = _make_id(class_nid, task_name)
add_node(task_nid, task_name, task_line)
edges.append({"source": class_nid, "target": task_nid, "relation": "method",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str_path, "source_location": f"L{task_line}", "weight": 1.0})
for param in _sv_split_type_list(params):
pm = _SV_PARAM_RE.match(param)
if not pm:
continue
for ref_name, role in _sv_collect_type_refs(pm.group(1), skip=type_params):
add_edge(task_nid, ref_name, "references", task_line, "generic_arg" if role == "generic_arg" else "parameter_type")
def extract_verilog(path: Path) -> dict:
"""Extract modules, functions, tasks, package imports, instantiations, and
SystemVerilog class semantics (inherits/implements edges, field/parameter/
+299
View File
@@ -0,0 +1,299 @@
"""YAML structural extractor.
Deterministic, PyYAML-based extraction for ``.yaml``/``.yml`` files so that
config-heavy repositories (Helm charts, Kubernetes manifests, CI pipelines)
contribute nodes to code-only / AST-only runs (``graphify update``) instead of
being skipped entirely (#2214).
Mirrors ``extract_json`` in shape: a file node plus ``contains`` edges to
top-level (and nested) keys, with a pair/depth cap to keep data-heavy YAML from
exploding into orphan nodes. Like ``extract_json``'s ``_is_config_json`` gate,
data-shaped YAML (a top-level data array, an OpenAPI/Swagger spec, a flat
key:value data bundle) is skipped so it does not mint up to 500 orphan nodes
(the #1224/#2255 class of problem).
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from graphify.extractors.base import _file_stem, _make_id
from graphify.ids import normalize_id
_YAML_MAX_BYTES = 1_048_576 # 1 MiB
_MAX_PAIRS = 500
# Built lazily by _permissive_loader() once PyYAML is known to be importable
# (the module stays import-optional, so this cannot be a module-level class).
_permissive_loader_cls: Any = None
def _construct_permissive(loader: Any, tag_suffix: str, node: Any) -> Any:
"""Build a plain value for an unrecognized ``!`` tag (#5071).
CloudFormation/SAM intrinsic functions (``!Ref``, ``!Sub``, ``!GetAtt``,
``!Equals``, ...) are short, local tags SafeLoader has no constructor
for, so ``safe_load_all`` raised ``ConstructorError`` and the whole file
produced zero nodes. The intrinsic itself is never evaluated here, only
the tagged value's own shape: a scalar tag becomes its scalar value, a
sequence tag its list, and a mapping tag its dict, exactly as if the tag
were absent.
"""
import yaml # type: ignore
if isinstance(node, yaml.ScalarNode):
return loader.construct_scalar(node)
if isinstance(node, yaml.SequenceNode):
return loader.construct_sequence(node)
if isinstance(node, yaml.MappingNode):
return loader.construct_mapping(node)
return None
def _permissive_loader() -> Any:
"""A ``yaml.SafeLoader`` subclass that also accepts any unknown ``!`` tag.
Adds no safety-relevant behavior over ``SafeLoader``: it only widens which
tags construct a plain value, never which types a value can construct
into, so a ``!!python/...`` tag still raises exactly as it does under
plain ``safe_load_all``.
"""
global _permissive_loader_cls
if _permissive_loader_cls is None:
import yaml # type: ignore
class _PermissiveSafeLoader(yaml.SafeLoader):
pass
_PermissiveSafeLoader.add_multi_constructor("!", _construct_permissive)
_permissive_loader_cls = _PermissiveSafeLoader
return _permissive_loader_cls
_MAX_DEPTH = 6
# Config/manifest filenames worth structural extraction regardless of shape.
_CONFIG_YAML_NAMES = frozenset({
"values.yaml", "values.yml", "chart.yaml", "chart.yml",
"docker-compose.yaml", "docker-compose.yml", "compose.yaml", "compose.yml",
"kustomization.yaml", "kustomization.yml", "skaffold.yaml", "skaffold.yml",
"serverless.yaml", "serverless.yml", "mkdocs.yaml", "mkdocs.yml",
".gitlab-ci.yml", ".gitlab-ci.yaml", ".pre-commit-config.yaml",
"cloudbuild.yaml", "cloudbuild.yml", "pubspec.yaml", "environment.yml",
"action.yml", "action.yaml", "catalog-info.yaml", ".travis.yml",
"appveyor.yml", "azure-pipelines.yml",
})
# Top-level keys that signal a config/manifest (k8s, CI, compose, ansible, helm).
_CONFIG_YAML_KEYS = frozenset({
"apiversion", "kind", "metadata", "spec", # k8s
"services", "volumes", "networks", # compose
"jobs", "steps", "stages", "on", "workflows", "pipeline", # CI
"hosts", "tasks", "roles", # ansible
"name", "version", "dependencies", "scripts", # generic
"resources", "provider", "functions", # serverless
})
def _is_config_yaml(path: Path, data: Any, key_texts: set[str] | None = None) -> bool:
"""True if a YAML document is a recognized config/manifest worth extracting.
Matches by filename first, then a ``.github/workflows`` path, then a
top-level key probe. Skips clear data: a plain data array, an OpenAPI/Swagger
spec, a JSON-Schema-in-YAML, and a flat all-scalar mapping with no config
key (for example an i18n string bundle). Errs toward extracting (a mapping
with any nested value is treated as config) so an arbitrarily-named real
config is not silently dropped.
``key_texts`` are the top-level keys as written in the source. PyYAML
resolves YAML 1.1 booleans, so the constructed key of a workflow's ``on:``
is ``True``; the written spelling is what the key probe must see.
"""
name = path.name.casefold()
if name in _CONFIG_YAML_NAMES:
return True
if "/.github/workflows/" in path.as_posix().casefold():
return True
if isinstance(data, list):
# A top-level sequence is config only when it is an ansible-style list of
# plays/tasks; a plain data array is not.
return any(
isinstance(item, dict)
and ({"hosts", "tasks", "roles"} & {str(k).casefold() for k in item})
for item in data
)
if not isinstance(data, dict):
return False
keys = key_texts if key_texts is not None else {str(k).casefold() for k in data.keys()}
if ("openapi" in keys or "swagger" in keys) and "paths" in keys:
return False # an API spec is data-heavy, not a config to walk (#2255-style)
if "$schema" in keys and ({"$defs", "definitions", "$id"} & keys):
return False # a JSON schema in YAML clothing
if keys & _CONFIG_YAML_KEYS:
return True
# A mapping with at least one nested value is config-like; a flat all-scalar
# mapping with no config key is treated as a data bundle and skipped.
return any(isinstance(v, (dict, list)) for v in data.values())
def _doc_label(doc: Any, index: int) -> str:
"""A stable label for one document of a multi-document YAML stream."""
if isinstance(doc, dict):
kind = doc.get("kind")
if isinstance(kind, str) and kind:
meta = doc.get("metadata")
nm = meta.get("name") if isinstance(meta, dict) else None
return f"{kind} {nm}" if isinstance(nm, str) and nm else kind
return f"doc {index}"
_MERGE_TAG = "tag:yaml.org,2002:merge"
def _mapping_pairs(node: Any) -> list[tuple[str, Any, Any]]:
"""(key text, key node, value node) for a composed mapping, in the order the
constructed dict would hold them.
Keys come back as written (``on``, not the YAML 1.1 boolean ``True``) and
carry their own line. A ``<<`` merge contributes its mapping's pairs first,
and a repeated key keeps its first position but takes the last value and
line, mirroring PyYAML's ``flatten_mapping`` plus dict insertion. A non-scalar key
has no written name to label a node with and is skipped.
"""
import yaml # type: ignore
merged: list[tuple[str, Any, Any]] = []
explicit: list[tuple[str, Any, Any]] = []
for key_node, value_node in node.value:
if key_node.tag == _MERGE_TAG:
sources = value_node.value if isinstance(value_node, yaml.SequenceNode) else [value_node]
# Per the YAML merge spec, an earlier map in a ``<<: [a, b]`` sequence
# overrides a later one. Because the dict below is last-write-wins, feed
# the sources in reverse so the earliest keeps the final value/line —
# matching PyYAML's ``flatten_mapping`` (which reverses the submerge).
for src in reversed(sources):
if isinstance(src, yaml.MappingNode):
merged.extend(_mapping_pairs(src))
elif isinstance(key_node, yaml.ScalarNode):
explicit.append((key_node.value, key_node, value_node))
pairs: dict[str, tuple[str, Any, Any]] = {}
for text, key_node, value_node in merged + explicit:
# Reassigning keeps the dict position; the later key node (an explicit
# override of a merged key) is the one whose line holds the value.
pairs[text] = (text, key_node, value_node)
return list(pairs.values())
def extract_yaml(path: Path) -> dict:
"""Extract structural nodes/edges from a ``.yaml``/``.yml`` file.
Uses a ``SafeLoader`` (never ``load``; a ``!!python/...`` tag raises
rather than executing), widened to accept any unrecognized ``!`` tag as a
plain scalar/sequence/mapping (#5071 — CloudFormation/SAM's ``!Ref``,
``!Equals``, etc. otherwise raise ``ConstructorError`` and the whole file
produces zero nodes), and walks every document in a multi-document
stream. Returns an error payload when PyYAML is missing so callers
degrade gracefully instead of crashing.
"""
try:
import yaml # type: ignore
except ImportError:
return {"nodes": [], "edges": [],
"error": "pyyaml not installed; install with `pip install pyyaml`"}
try:
with path.open("rb") as _f:
raw = _f.read(_YAML_MAX_BYTES + 1)
if len(raw) > _YAML_MAX_BYTES:
return {"nodes": [], "edges": [], "error": "yaml file too large to index"}
text = raw.decode("utf-8", errors="ignore")
docs = list(yaml.load_all(text, Loader=_permissive_loader()))
# The constructed values drive the config gate and document labels; the
# composed node tree (same documents, same order, nothing constructed)
# supplies keys as written and their lines, which construction discards.
trees = list(yaml.compose_all(text, Loader=yaml.SafeLoader))
except Exception as exc: # noqa: BLE001 - surface any parse failure to caller
return {"nodes": [], "edges": [], "error": str(exc)}
structured = [(d, n) for d, n in zip(docs, trees) if isinstance(d, (dict, list))]
if not structured:
return {"nodes": [], "edges": [], "skipped": "scalar yaml"}
def _top_keys(tree: Any) -> set[str] | None:
if isinstance(tree, yaml.MappingNode):
return {text.casefold() for text, _k, _v in _mapping_pairs(tree)}
return None
config_docs = [(d, n) for d, n in structured if _is_config_yaml(path, d, _top_keys(n))]
if not config_docs:
return {"nodes": [], "edges": [], "skipped": "data yaml (not a config/manifest)"}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
def add_node(nid: str, label: str, line: int = 1, file_type: str = "code") -> None:
if nid and nid not in seen_ids:
seen_ids.add(nid)
nodes.append(
{"id": nid, "label": str(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 = 1,
context: str | None = None) -> None:
if not src or not tgt or src == tgt:
return
edge = {"source": src, "target": tgt, "relation": relation,
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line}", "weight": 1.0}
if context:
edge["context"] = context
edges.append(edge)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
pair_count = [0]
def walk(node: Any, parent_nid: str, parent_key: str | None, depth: int) -> None:
if depth > _MAX_DEPTH:
return
if isinstance(node, yaml.MappingNode):
for key_str, key_node, val in _mapping_pairs(node):
if pair_count[0] >= _MAX_PAIRS:
return
pair_count[0] += 1
if not normalize_id(key_str):
continue
key_nid = _make_id(stem, *(([parent_key] if parent_key else []) + [key_str]))
if not key_nid:
continue
line = key_node.start_mark.line + 1
add_node(key_nid, key_str, line)
add_edge(parent_nid, key_nid, "contains", line)
if isinstance(val, (yaml.MappingNode, yaml.SequenceNode)):
walk(val, key_nid, key_str, depth + 1)
elif isinstance(node, yaml.SequenceNode):
# Lists of scalars carry no key structure; only recurse into
# structured items without minting index nodes (avoids explosion).
for item in node.value:
if isinstance(item, (yaml.MappingNode, yaml.SequenceNode)):
walk(item, parent_nid, parent_key, depth + 1)
multi = len(config_docs) > 1
for index, (doc, tree) in enumerate(config_docs):
if multi:
# Keep each document of a multi-document stream distinct (a k8s file
# holding a Deployment and a Service must not merge their metadata).
label = _doc_label(doc, index)
doc_nid = _make_id(stem, f"doc{index}", label) or _make_id(stem, f"doc{index}")
if not doc_nid:
continue
doc_line = tree.start_mark.line + 1
add_node(doc_nid, label, doc_line)
add_edge(file_nid, doc_nid, "contains", doc_line)
walk(tree, doc_nid, label, 1)
else:
walk(tree, file_nid, None, 0)
return {"nodes": nodes, "edges": edges}
+8 -2
View File
@@ -217,8 +217,14 @@ def extract_zig(path: Path) -> dict:
fn_text = _read_text(fn, source)
callee = fn_text.split(".")[-1]
is_member_call = "." in fn_text
tgt_nid = next((n["id"] for n in nodes if n["label"] in
(f"{callee}()", f".{callee}()")), None)
# A dotted call (`obj.helper()`) names a method, never a free
# function; a bare call (`helper()`) names a free function,
# never a method. Matching either label for both call shapes
# let a bare call cross-resolve onto an unrelated struct's
# method of the same name (and vice versa) whenever the two
# just happened to coexist in the file.
wanted_label = f".{callee}()" if is_member_call else f"{callee}()"
tgt_nid = next((n["id"] for n in nodes if n["label"] == wanted_label), None)
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
+23 -5
View File
@@ -32,14 +32,16 @@ from graphify.extractors.base import _read_source_text
# This set has to keep pace with ``detect.DOC_EXTENSIONS``: anything classified
# as a document reaches the semantic pass, and anything the pass sees that is
# NOT listed here is silently cut at ``_FILE_CHAR_CAP`` by ``_read_files``. The
# two lists drifted as DOC_EXTENSIONS grew — .qmd, .skill, .html, .yaml and .yml
# were documents that never got sliced, so a 38k-character one reached the model
# as its first 20k with no warning and no partial marker (#2900).
# two lists drifted as DOC_EXTENSIONS grew — .qmd, .skill and .html were
# documents that never got sliced, so a 38k-character one reached the model as
# its first 20k with no warning and no partial marker (#2900). .yaml/.yml are
# intentionally NOT here: they are code, not documents (reclassified in #2214),
# and never reach the semantic pass.
# ``tests/test_oversized_document_slicing.py`` pins the relationship so a future
# addition to DOC_EXTENSIONS fails loudly instead of quietly losing content.
_SPLITTABLE_TEXT_SUFFIXES = frozenset({
".md", ".mdx", ".markdown", ".txt", ".rst",
".qmd", ".skill", ".html", ".yaml", ".yml",
".qmd", ".skill", ".html",
".j2", ".jinja", ".jinja2",
})
@@ -67,6 +69,7 @@ def _pdf_text(path: Path) -> str:
# rather than once per slice, and so a file rewritten mid-run is re-read instead
# of served a stale body. Bounded: the entries are whole documents, and a large
# corpus should not pin all of them in memory.
# Resolve the path so relative names in different corpus roots cannot share text.
_CONVERTED_TEXT_CACHE: "dict[tuple, str]" = {}
_CONVERTED_TEXT_CACHE_MAX = 64
@@ -82,7 +85,7 @@ def unit_source_text(path: Path) -> str:
return _read_source_text(path, warn=False)
try:
st = path.stat()
key = (str(path), st.st_size, st.st_mtime_ns)
key = (str(path.resolve()), st.st_size, st.st_mtime_ns)
except OSError:
return _pdf_text(path)
hit = _CONVERTED_TEXT_CACHE.get(key)
@@ -247,3 +250,18 @@ def bisect_slice(fs: FileSlice) -> tuple[FileSlice, FileSlice] | None:
left = FileSlice(fs.path, fs.start, cut, fs.index, fs.total)
right = FileSlice(fs.path, cut, fs.end, fs.index, fs.total)
return left, right
def make_full_slice(path: Path) -> FileSlice | None:
"""Create a full-range ``FileSlice`` for an eligible splittable text file (#5072).
Returns None for non-splittable files (code, binary, unreadable).
"""
if not is_splittable_text(path):
return None
try:
text = unit_source_text(path)
except Exception:
return None
return FileSlice(path=path, start=0, end=len(text), index=0, total=1)
+19 -1
View File
@@ -15,7 +15,25 @@ _GLOBAL_MANIFEST = _GLOBAL_DIR / "global-manifest.json"
def _load_manifest() -> dict:
if _GLOBAL_MANIFEST.exists():
try:
return json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
manifest = json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
repos = manifest.get("repos") if isinstance(manifest, dict) else None
if not isinstance(repos, dict):
raise ValueError("expected a manifest object with a repos map")
# Isolate a malformed repo entry instead of discarding every tracked
# repo: a single bad value should not lose the user's other repos
# (#5020). Drop the bad ones, keep the rest, and say which went. Only
# a non-dict root or repos map is unrecoverable enough to back up.
bad = sorted(name for name, info in repos.items() if not isinstance(info, dict))
if bad:
for name in bad:
repos.pop(name)
print(
f"[graphify global] dropped {len(bad)} malformed repo "
f"entr{'y' if len(bad) == 1 else 'ies'} ({', '.join(bad)}) "
f"from {_GLOBAL_MANIFEST}; kept {len(repos)} valid repo(s).",
file=sys.stderr,
)
return manifest
except Exception as exc:
# Don't silently wipe the user's manifest on a parse error: that
# deletes every tracked repo. Back the bad file up and surface the
+129
View File
@@ -0,0 +1,129 @@
"""Member-level interface dispatch for Go.
`d.provider.GetWithDataSource()` where `provider` is a `pluginContextProvider`
resolves to the interface's own `.GetWithDataSource()` requirement, because that
is what the call site names. The concrete `Provider.GetWithDataSource()` is a
separate node, and nothing joins the two, so a directed walk stops at the
interface — the Go twin of the C# gap #3003 closed.
C# and Swift feed `graphify.interface_dispatch` with the `implements` edges
their extractors read off a declaration. Go has no such declaration: a type
implements an interface by having its methods. So this pass infers the pairs
from method sets and hands them to the shared mechanism, which does the rest
(per-method `dispatches_to` at INFERRED, 0.85 / 0.75 / 0.65 by implementer
count, the single-owner guard). The inferred `implements` pairs only feed the
mechanism; they are not added to the graph.
A named type T implements interface I here when T's methods (value and
pointer receivers alike: the extractor hangs both off T's node) include every
method name I requires. Names only: method nodes carry no signature, and Go has
no overloads to tell apart. The guards:
- Both ends are declared in a `.go` file, as in the C# and Swift passes.
- An interface with no methods (`interface{}`, `any`) or only a type set is
skipped: every type satisfies the first, and the second is a generics
constraint, not something a call goes through.
- An interface that embeds another is used only when every embedded interface
is declared in the corpus, with its methods counted in. `io.Reader` and
other external interfaces have unknown methods, so such an interface is
skipped rather than matched on part of its method set.
- An unexported method name (`run()`) can only be implemented in the
interface's own package, so only types in the same directory count.
- An interface matched by more than `_MAX_IMPLICIT_IMPLEMENTERS` types is
skipped. Name-only matching makes a lone common name (`Close`, `String`)
match unrelated types, and past this many the edges say little. The builtin
`error` and `fmt.Stringer` are not in the corpus, so they never match; a
local redeclaration of either is matched like any other interface.
Struct embedding is not followed: a type whose method comes from an embedded
field does not own that method node, so it is not matched.
"""
from __future__ import annotations
from pathlib import PurePath
from graphify.interface_dispatch import (
declared_in,
method_label,
resolve_interface_dispatch,
)
_GO_SUFFIXES = (".go",)
# Past this many structural implementers an interface is skipped, not truncated:
# which ten to keep would be arbitrary.
_MAX_IMPLICIT_IMPLEMENTERS = 10
def _is_go_interface(node: dict | None) -> bool:
meta = (node or {}).get("metadata")
return isinstance(meta, dict) and meta.get("language") == "go" and meta.get("kind") == "interface"
def resolve_go_interface_dispatch(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link each Go interface method to the methods of every type that satisfies the interface."""
interfaces = {n.get("id"): n for n in all_nodes if _is_go_interface(n) and declared_in(n, _GO_SUFFIXES)}
if not interfaces:
return
node_by_id = {n.get("id"): n for n in all_nodes}
method_names: dict[str, set[str]] = {}
embeds: dict[str, set[str]] = {}
type_set_constrained: set[str] = set()
for e in all_edges:
rel, source = e.get("relation"), e.get("source")
if rel == "method":
mnode = node_by_id.get(e.get("target"))
if mnode is not None and declared_in(mnode, _GO_SUFFIXES) and method_label(mnode):
method_names.setdefault(source, set()).add(method_label(mnode))
elif source in interfaces and rel == "embeds":
embeds.setdefault(source, set()).add(e.get("target"))
elif source in interfaces and rel == "references" and e.get("context") == "type_constraint":
type_set_constrained.add(source)
def required(iface: str, visiting: frozenset[str] = frozenset()) -> set[str] | None:
# None: the method set is not fully known (an embedded interface outside
# the corpus, or an embedding cycle, which Go rejects anyway).
names = set(method_names.get(iface, ()))
for embedded in embeds.get(iface, ()):
if embedded not in interfaces or embedded in visiting:
return None
inner = required(embedded, visiting | {iface})
if inner is None:
return None
names |= inner
return names
candidates = {
owner: names for owner, names in method_names.items()
if owner not in interfaces and declared_in(node_by_id.get(owner), _GO_SUFFIXES)
}
inferred: list[dict] = []
for iface, iface_node in interfaces.items():
if iface in type_set_constrained or not method_names.get(iface):
continue
needed = required(iface)
if not needed:
continue
package = PurePath(str(iface_node.get("source_file"))).parent
same_package_only = any(not name[:1].isupper() for name in needed)
impls = [
owner for owner, names in candidates.items()
if needed <= names
and (not same_package_only
or PurePath(str(node_by_id[owner].get("source_file"))).parent == package)
]
if 0 < len(impls) <= _MAX_IMPLICIT_IMPLEMENTERS:
inferred.extend({"source": impl, "target": iface, "relation": "implements"} for impl in impls)
if not inferred:
return
# The shared resolver reads `implements` from the edge list it is given and
# appends its `dispatches_to` edges to that list; keep only the latter.
edges = all_edges + inferred
resolve_interface_dispatch(per_file, all_nodes, edges, suffixes=_GO_SUFFIXES)
all_edges.extend(edges[len(all_edges) + len(inferred):])
+35 -1
View File
@@ -29,7 +29,41 @@ def google_workspace_enabled(value: str | None = None) -> bool:
def _safe_yaml_str(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
"""Escape a value for a YAML double-quoted scalar.
Same escaping as graphify.ingest._yaml_str (F-009): backslash, quote,
tab, NUL and other C0/DEL controls, plus the Unicode line breaks
U+2028, U+2029 and U+0085, so a hostile shortcut url or file id cannot
break out of the scalar and inject sibling frontmatter keys.
"""
if value is None:
return ""
out: list[str] = []
for ch in str(value):
cp = ord(ch)
if ch == "\\":
out.append("\\\\")
elif ch == '"':
out.append('\\"')
elif ch == "\n":
out.append("\\n")
elif ch == "\r":
out.append("\\r")
elif ch == "\t":
out.append("\\t")
elif ch == "\0":
out.append("\\0")
elif cp == 0x2028:
out.append("\\L")
elif cp == 0x2029:
out.append("\\P")
elif cp == 0x0085:
out.append("\\x85")
elif cp < 0x20 or cp == 0x7F:
out.append(f"\\x{cp:02x}")
else:
out.append(ch)
return "".join(out)
def _extract_file_id_from_url(url: str) -> str | None:
+31 -8
View File
@@ -405,14 +405,37 @@ def _detached_launch(rebuild_body: str) -> str:
# absolute while --git-common-dir is the relative ".git", and a raw compare would
# false-positive on the PRIMARY checkout and wrongly skip it.
_WORKTREE_GUARD = """\
_GFY_GITDIR=$(cd "$(git rev-parse --git-dir 2>/dev/null)" 2>/dev/null && pwd)
_GFY_COMMONDIR=$(cd "$(git rev-parse --git-common-dir 2>/dev/null)" 2>/dev/null && pwd)
_GFY_GITDIR=$(CDPATH= cd "$(git rev-parse --git-dir 2>/dev/null)" 2>/dev/null && pwd)
_GFY_COMMONDIR=$(CDPATH= cd "$(git rev-parse --git-common-dir 2>/dev/null)" 2>/dev/null && pwd)
if [ -n "$_GFY_COMMONDIR" ] && [ "$_GFY_GITDIR" != "$_GFY_COMMONDIR" ]; then
exit 0
fi
"""
# Run the rest of each hook from the checkout's top level, shared by all hooks
# and placed right after _WORKTREE_GUARD (it reuses _GFY_GITDIR/_GFY_COMMONDIR).
# The rebuild reads graphify-out/ and its .graphify_root relative to the cwd,
# but git does not always start hooks at the top: with GIT_DIR exported and no
# GIT_WORK_TREE (a nested git call from another hook or tool), git takes the
# caller's cwd as the work tree, and `--show-toplevel` echoes that same
# subdirectory. A stray graphify-out/ left there by an earlier run then roots the
# rebuild at the subdirectory - for .claude/worktrees/ that is every linked
# worktree (#3258). In the standard layout the work tree is the parent of the
# common .git dir; GIT_WORK_TREE and --separate-git-dir layouts keep git's own
# answer. GIT_DIR is rewritten to its absolute form (not newly exported) so the
# git calls below still resolve after the cd.
_TOPLEVEL_ANCHOR = """\
if [ -z "${GIT_WORK_TREE:-}" ] && [ "${_GFY_COMMONDIR##*/}" = ".git" ]; then
_GFY_TOP=${_GFY_COMMONDIR%/*}
else
_GFY_TOP=$(git rev-parse --show-toplevel 2>/dev/null)
fi
[ -n "$_GFY_TOP" ] && cd "$_GFY_TOP" || exit 0
[ -n "$_GFY_GITDIR" ] && GIT_DIR=$_GFY_GITDIR
"""
# Both hook bodies run inside a subshell `( ... )`. The generated block is
# appended to whatever post-commit / post-checkout already exists, and other
# tools chain their own logic after it; every skip condition in the block is a
@@ -449,7 +472,7 @@ GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
""" + _WORKTREE_GUARD + """
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + """
# CHERRY_PICK_HEAD can't be the skip signal: git leaves it on disk while post-commit
# runs, so every pick was silenced (#4490, same trap as MERGE_HEAD in #4463). For a
# range pick or revert, skip every step but the last and rebuild once from
@@ -579,7 +602,7 @@ GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
# suppressed commit-triggered rebuilds but not branch-switch ones (#1809).
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
""" + _WORKTREE_GUARD + _PYTHON_DETECT + """
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + _PYTHON_DETECT + """
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
@@ -632,7 +655,7 @@ GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
# Honor the same opt out the commit and checkout hooks already respect.
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
""" + _WORKTREE_GUARD + _PYTHON_DETECT + """
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + _PYTHON_DETECT + """
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
@@ -684,7 +707,7 @@ fi
# Honor the same opt out the commit and checkout hooks already respect.
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
""" + _WORKTREE_GUARD + _PYTHON_DETECT + """
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + _PYTHON_DETECT + """
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
@@ -753,7 +776,7 @@ def _rev_parse_path(root: Path, flag: str) -> Path | None:
try:
res = _sp.run(
["git", "-C", str(root), "rev-parse", flag],
capture_output=True, text=True,
capture_output=True, text=True, encoding="utf-8",
)
except (OSError, FileNotFoundError):
return None
@@ -815,7 +838,7 @@ def _hooks_dir(root: Path) -> Path:
try:
res = _sp.run(
["git", "-C", str(root), "rev-parse", "--git-path", "hooks"],
capture_output=True, text=True,
capture_output=True, text=True, encoding="utf-8",
)
if res.returncode != 0:
# git failing here is a real signal (corrupt .git/config, tampering,
+82 -1
View File
@@ -41,10 +41,11 @@ how many times the caller has already casefolded.
"""
from __future__ import annotations
import hashlib
import re
import unicodedata
__all__ = ["normalize_id", "make_id"]
__all__ = ["normalize_id", "make_id", "decl_salt", "DeclIdRegistry"]
def normalize_id(s: str) -> str:
@@ -83,6 +84,86 @@ def normalize_id(s: str) -> str:
return cur.strip("_")
def decl_salt(name: str) -> str:
"""Stable 12-hex digest appended when a declaration id collides (#4854)."""
return hashlib.sha1(
name.encode("utf-8", "replace"), usedforsecurity=False
).hexdigest()[:12]
class DeclIdRegistry:
"""Assign unique ids to declarations in one file.
Ownership is keyed by the id the declaration would have used, so two
declarations whose names normalize alike (``Foo`` / ``_Foo``, or ``Base`` in
two namespaces) stay distinct. A reference lookup by name only answers when
exactly one declaration in the file spells that name; an ambiguous name
keeps the caller's existing fallback.
"""
def __init__(self, reserved_ids=()):
self._assigned: dict[tuple[str, str], str] = {}
self._owners: dict[str, tuple[str, str]] = {
rid: ("file", rid) for rid in reserved_ids
}
self._by_name: dict[tuple[str, str], set[str]] = {}
self._salted: set[str] = set()
self._spelled: dict[str, str] = {}
def resolve(self, nid: str, name: str, kind: str, taken) -> str:
key = (kind, nid)
owner = self._owners.get(nid)
if owner == key:
return self._assigned[key]
if nid not in taken and owner is None:
self._owners[nid] = key
self._assigned[key] = nid
self._spelled[nid] = name
self._by_name.setdefault((kind, normalize_id(name)), set()).add(nid)
return nid
assigned = self._assigned.get(key)
if assigned is not None:
return assigned
# An id already used by a real declaration is a duplicate reference to
# that declaration (prototype owner, same name re-declared); reuse it
# instead of minting a second node. Only a salted id, whose owner stole
# the spelling from this declaration, forces a counter-salt (#4854). A
# different kind only counts as a duplicate when spelled the same (TS
# `class Foo` + `namespace Foo`): `class Foo` + `function foo` are two (#4904).
if (nid in taken and owner is not None and owner[0] != "file"
and nid not in self._salted
and (owner[0] == kind or self._spelled.get(nid) == name)):
return nid
base = make_id(nid, decl_salt(name))
candidate = base
counter = 2
while candidate in taken or candidate in self._owners:
candidate = make_id(base, str(counter))
counter += 1
self._owners[candidate] = key
self._assigned[key] = candidate
self._salted.add(candidate)
self._spelled[candidate] = name
self._by_name.setdefault((kind, normalize_id(name)), set()).add(candidate)
return candidate
def lookup(self, name: str, kinds=("type", "fn", "var", "ns", "alias")) -> str | None:
norm = normalize_id(name)
# A declaration spelled exactly like the reference wins over one that
# only normalizes alike: once #4904 keeps `Session` and `session()`
# apart, `Session s;` names the declaration spelled `Session`, whatever
# its kind. Without an exact spelling the kind order decides, as before.
exact = {i for kind in kinds for i in self._by_name.get((kind, norm), ())
if self._spelled.get(i) == name}
if len(exact) == 1:
return next(iter(exact))
for kind in kinds:
ids = self._by_name.get((kind, norm))
if ids:
return next(iter(ids)) if len(ids) == 1 else None
return None
def make_id(*parts: str) -> str:
"""Build a canonical node ID from one or more name parts.
+39 -17
View File
@@ -1,11 +1,14 @@
# fetch URLs (tweet/arxiv/pdf/web) and save as annotated markdown
from __future__ import annotations
from collections.abc import Callable
from contextlib import suppress
import json
import re
import uuid
import urllib.error
import urllib.parse
from datetime import datetime, timezone
from os import linesep
from pathlib import Path
from graphify.security import safe_fetch, safe_fetch_text, validate_url
@@ -221,24 +224,51 @@ Source: {url}
return content, filename
def _download_binary(url: str, suffix: str, target_dir: Path) -> Path:
"""Save a sequential capture without replacing an existing directory entry.
def _free_capture_path(target_dir: Path, filename: str) -> Path:
"""Pick *filename*, or the first free numbered variant, in *target_dir*.
Selection and writing are separate; concurrent captures are not atomic.
Uses lstat so no existing directory entry is replaced, including a
dangling symlink that a write would otherwise follow out of the corpus.
The writer still needs an exclusive open to reserve the selected name.
"""
filename = _safe_filename(url, suffix)
stem = Path(filename).stem
stem, suffix = Path(filename).stem, Path(filename).suffix
out_path = target_dir / filename
counter = 1
while True:
try:
out_path.lstat()
except FileNotFoundError:
break
return out_path
out_path = target_dir / f"{stem}_{counter}{suffix}"
counter += 1
out_path.write_bytes(safe_fetch(url))
return out_path
def _write_capture(target_dir: Path, filename: str, content: str | Callable[[], bytes]) -> Path:
"""Write a capture under a unique name without clobbering another writer."""
out_path = _free_capture_path(target_dir, filename)
# Inspect the destination before fetching, and fetch at most once per capture.
payload = content() if callable(content) else content
if isinstance(payload, str):
# Preserve the newline translation of Path.write_text on Windows.
payload = payload.replace("\n", linesep).encode("utf-8")
while True:
try:
handle = out_path.open("xb")
except FileExistsError:
out_path = _free_capture_path(target_dir, filename)
continue
try:
with handle:
handle.write(payload)
except (OSError, UnicodeError):
with suppress(OSError):
out_path.unlink()
raise
return out_path
def _download_binary(url: str, suffix: str, target_dir: Path) -> Path:
return _write_capture(target_dir, _safe_filename(url, suffix), lambda: safe_fetch(url))
def ingest(url: str, target_dir: Path, author: str | None = None, contributor: str | None = None) -> Path:
@@ -282,15 +312,7 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
except (urllib.error.HTTPError, urllib.error.URLError, OSError) as exc:
raise RuntimeError(f"ingest: failed to fetch {url!r}: {exc}") from exc
out_path = target_dir / filename
# Avoid overwriting - append counter if needed
counter = 1
while out_path.exists() and counter < 1000:
stem = Path(filename).stem
out_path = target_dir / f"{stem}_{counter}.md"
counter += 1
out_path.write_text(content, encoding="utf-8")
out_path = _write_capture(target_dir, filename, content)
print(f"Saved {url_type}: {out_path.name}")
return out_path
+318 -103
View File
@@ -22,6 +22,7 @@ import re
import shutil
import stat
import sys
import tempfile
import threading
import time
from pathlib import Path
@@ -149,23 +150,34 @@ def _skill_lock(skill_dir: Path, *, wait: bool = True):
def _write_version_stamp(skill_dst: Path, version: str) -> None:
"""Atomically write ``.graphify_version`` beside ``skill_dst``.
Matches the SKILL.md install path: temp file in the same directory, then
``os.replace``. Unlike ``Path.write_text`` (and unlike
Matches the SKILL.md install path: unique temp file in the same directory,
then ``os.replace``. Unlike ``Path.write_text`` (and unlike
``paths.write_text_atomic``, which resolves through symlinks), ``os.replace``
replaces a managed symlink in place — consistent with SKILL.md /
``references/`` and crash-safe against a half-written stamp (#3286).
"""
version_file = skill_dst.parent / ".graphify_version"
tmp = version_file.with_name(".graphify_version.tmp")
fd, tmp_name = tempfile.mkstemp(
dir=str(skill_dst.parent),
prefix=".graphify_version.",
suffix=".tmp",
)
tmp = Path(tmp_name)
fd_closed = False
try:
tmp.write_text(version, encoding="utf-8")
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fd_closed = True
fh.write(version)
with contextlib.suppress(OSError):
if version_file.exists() and not version_file.is_symlink():
os.chmod(tmp, stat.S_IMODE(version_file.stat().st_mode))
_os_replace_with_fallback(tmp, version_file)
except Exception:
try:
finally:
if not fd_closed:
with contextlib.suppress(OSError):
os.close(fd)
with contextlib.suppress(OSError):
tmp.unlink(missing_ok=True)
except OSError:
pass
raise
@functools.lru_cache(maxsize=None)
@@ -196,8 +208,9 @@ def _platform_skill_destination(platform_name: str, *, project: bool = False, pr
if platform_name == "gemini":
if project:
return (project_dir or Path(".")) / ".gemini" / "skills" / "graphify" / "SKILL.md"
if platform.system() == "Windows":
return Path.home() / ".agents" / "skills" / "graphify" / "SKILL.md"
# Gemini CLI reads ~/.gemini/skills on every OS. ~/.agents/skills is the
# `agents` platform's destination, and sharing it let each platform
# overwrite and uninstall the other's skill (#2800).
return Path.home() / ".gemini" / "skills" / "graphify" / "SKILL.md"
if platform_name == "opencode":
@@ -224,6 +237,14 @@ def _platform_skill_destination(platform_name: str, *, project: bool = False, pr
return (project_dir or Path(".")) / ".agents" / "skills" / "graphify" / "SKILL.md"
return Path.home() / ".config" / "agents" / "skills" / "graphify" / "SKILL.md"
if platform_name == "pi":
# Pi reads project skills from ./.pi/skills; ~/.pi/agent/skills is the
# user-scope path only. Writing the $HOME shape into a project left the
# skill where Pi never looks, with no error (#5011).
if project:
return (project_dir or Path(".")) / ".pi" / "skills" / "graphify" / "SKILL.md"
return Path.home() / _PLATFORM_CONFIG["pi"]["skill_dst"]
if platform_name == "agents":
# The generic Agent-Skills target: project ./.agents/skills, global the
# spec's user-global ~/.agents/skills (read by `npx skills` and compliant
@@ -280,15 +301,20 @@ def _packaged_skill_refs_dir(platform_name: str) -> Path | None:
def _install_skill_references(skill_dst: Path, refs_src: Path) -> None:
"""Atomically install a packaged references/ sidecar next to SKILL.md.
Stages the packaged dir into ``references.tmp`` (copytree), drops any stale
``references/`` already on disk, then ``os.replace``-renames the staged dir
into place. The rename is atomic on the same filesystem, so an interrupted
install never leaves a half-written references/ visible to the agent.
Stages the packaged dir into a unique temporary directory (copytree), drops
any stale ``references/`` already on disk, then ``os.replace``-renames the
staged dir into place. The rename is atomic on the same filesystem, so an
interrupted install never leaves a half-written references/ visible to the
agent.
"""
refs_dst = skill_dst.parent / "references"
refs_staged = skill_dst.parent / "references.tmp"
if refs_staged.exists():
shutil.rmtree(refs_staged)
legacy_staged = skill_dst.parent / "references.tmp"
if not legacy_staged.is_symlink() and legacy_staged.is_dir():
shutil.rmtree(legacy_staged, ignore_errors=True)
staging_root = Path(
tempfile.mkdtemp(dir=str(skill_dst.parent), prefix=".references.", suffix=".tmp")
)
refs_staged = staging_root / "references"
try:
shutil.copytree(refs_src, refs_staged)
# copytree preserves the source's mode bits, and a packaged bundle can
@@ -298,13 +324,17 @@ def _install_skill_references(skill_dst: Path, refs_src: Path) -> None:
# below would fail with EACCES. Restore owner-write on the staged copy.
for path in (refs_staged, *refs_staged.rglob("*")):
path.chmod(path.stat().st_mode | stat.S_IWUSR)
if refs_dst.exists():
if refs_dst.is_symlink():
refs_dst.unlink()
elif refs_dst.exists():
shutil.rmtree(refs_dst)
os.replace(refs_staged, refs_dst)
except Exception:
if refs_staged.exists():
shutil.rmtree(refs_staged, ignore_errors=True)
raise
finally:
if staging_root.is_symlink():
with contextlib.suppress(OSError):
staging_root.unlink()
elif staging_root.exists():
shutil.rmtree(staging_root, ignore_errors=True)
def _copy_skill_file(platform_name: str, *, project: bool = False, project_dir: Path | None = None) -> Path:
"""Copy a packaged skill file and write its version stamp.
@@ -362,16 +392,26 @@ def _copy_skill_file(platform_name: str, *, project: bool = False, project_dir:
except OSError:
pass # a failed backup must not block the install
# SKILL.md last (crash-safety), via an atomic temp + rename.
tmp_dst = skill_dst.with_suffix(skill_dst.suffix + ".tmp")
fd, tmp_name = tempfile.mkstemp(
dir=str(skill_dst.parent),
prefix=f".{skill_dst.name}.",
suffix=".tmp",
)
tmp_dst = Path(tmp_name)
fd_closed = False
try:
shutil.copy(skill_src, tmp_dst)
with os.fdopen(fd, "wb") as dst_fh:
fd_closed = True
with open(skill_src, "rb") as src_fh:
shutil.copyfileobj(src_fh, dst_fh)
shutil.copymode(skill_src, tmp_dst)
_os_replace_with_fallback(tmp_dst, skill_dst)
except Exception:
try:
finally:
if not fd_closed:
with contextlib.suppress(OSError):
os.close(fd)
with contextlib.suppress(OSError):
tmp_dst.unlink(missing_ok=True)
except OSError:
pass
raise
_write_version_stamp(skill_dst, __version__)
print(f" skill installed -> {skill_dst}")
@@ -406,29 +446,111 @@ def _project_scope_root(path: Path, project_dir: Path) -> Path:
except ValueError:
return path
return project_dir / rel.parts[0] if rel.parts else path
def _is_graphify_skill_registration(section: "list[str]") -> bool:
"""Whether a `# graphify` section is the registration graphify writes.
Every version of the registration has had the bullet naming the graphify
skill and the `/graphify` trigger, which a hand-written section has no
reason to repeat.
"""
return any(
line.strip().startswith("- **graphify** (`") and "Trigger: `/graphify`" in line
for line in section
)
def _skill_registration_sections(content: str) -> "list[list[str]]":
"""The body of each exact `# graphify` section, bounded as
_remove_marker_section bounds it: up to the next H1."""
lines = content.split("\n")
sections = []
for start, line in enumerate(lines):
if line.strip() == _SKILL_REGISTRATION_MARKER:
end = next(
(j for j in range(start + 1, len(lines)) if lines[j].startswith("# ")),
len(lines),
)
sections.append(lines[start + 1:end])
return sections
def _remove_skill_registration(target: Path, prefix: str, *, only_graphify_written: bool = False) -> None:
"""Remove the skill registration _register_always_on_block wrote into *target*.
*only_graphify_written* is for the user's global CLAUDE.md / CODEBUDDY.md,
which every `graphify uninstall` visits, also for users who never installed
the skill there. Only a `# graphify` section carrying graphify's
registration bullet goes; a hand-written `# graphify` section stays, and a
file holding both is left as is, with a hint, rather than guessed at.
Degrades instead of raising, as the install side does (#3474): a CLAUDE.md
that nix/home-manager links into a read-only store must not abort an
uninstall halfway, with later platforms not yet cleaned.
"""
try:
if not target.exists():
return
# A file without the heading is never decoded or rewritten, so an
# unrelated non-UTF-8 file draws no warning.
if _SKILL_REGISTRATION_MARKER.encode("utf-8") not in target.read_bytes():
return
content, newline = _read_keep_newline(target)
# A BOM would hide a heading on the first line; it is written back as found.
bom = "" if content.startswith("") else ""
content = content[len(bom):]
if only_graphify_written:
written = [_is_graphify_skill_registration(s) for s in _skill_registration_sections(content)]
if not any(written):
return
if not all(written):
print(
f"{prefix}left as is: {_shown_path(target)} also has a "
f"`{_SKILL_REGISTRATION_MARKER}` section graphify did not write",
file=sys.stderr,
)
print(
f" hint: remove graphify's own `{_SKILL_REGISTRATION_MARKER}` block "
"(the one naming the graphify skill) by hand",
file=sys.stderr,
)
return
# Match the exact H1 `# graphify` registration heading, never a substring of a
# user's `## graphify`/`### graphify` (#2062). Section runs to the next H1.
# _SKILL_REGISTRATION_MARKER is the single source of truth for this heading,
# shared with _register_always_on_block so an insert and its removal always
# agree on what they're matching (#3668).
cleaned = _remove_marker_section(content, _SKILL_REGISTRATION_MARKER, boundary_prefix="# ")
if cleaned is None:
return
# A symlink stays: writing through it cleans the file it points to.
if cleaned or target.is_symlink():
# The file's own line ending is restored, so the rest of its content is
# never re-translated on write (#3668/#4360).
_write_keep_newline(target, bom + cleaned + "\n", newline)
print(f"{prefix}graphify skill registration removed from {_shown_path(target)}")
else:
target.unlink()
print(f"{prefix}deleted {target}")
except (OSError, UnicodeDecodeError) as exc:
print(f"{prefix}skipped: {exc.__class__.__name__}: {exc}", file=sys.stderr)
print(
f" hint: remove the `{_SKILL_REGISTRATION_MARKER}` block from {target} "
"manually to finish the uninstall",
file=sys.stderr,
)
def _remove_claude_skill_registration(project_dir: Path) -> None:
"""Remove the project-scoped Claude skill registration file/section."""
claude_md = project_dir / ".claude" / "CLAUDE.md"
if not claude_md.exists():
return
content, newline = _read_keep_newline(claude_md)
# Match the exact H1 `# graphify` registration heading, never a substring of a
# user's `## graphify`/`### graphify` (#2062). Section runs to the next H1.
# _SKILL_REGISTRATION_MARKER is the single source of truth for this heading,
# shared with _register_always_on_block so an insert and its removal always
# agree on what they're matching (#3668).
cleaned = _remove_marker_section(content, _SKILL_REGISTRATION_MARKER, boundary_prefix="# ")
if cleaned is None:
return
# A symlink stays: writing through it cleans the file it points to.
if cleaned or claude_md.is_symlink():
# The file's own line ending is restored, so the rest of its content is
# never re-translated on write (#3668/#4360).
_write_keep_newline(claude_md, cleaned + "\n", newline)
print(f" CLAUDE.md -> graphify skill registration removed from {_shown_path(claude_md)}")
else:
claude_md.unlink()
print(f" CLAUDE.md -> deleted {claude_md}")
_remove_skill_registration(project_dir / ".claude" / "CLAUDE.md", " CLAUDE.md -> ")
def _claude_global_registration() -> "tuple[Path, str]":
"""The CLAUDE.md a global (non-project) Claude install registers the skill in,
and the skill path that registration names: the same choice install() makes.
CLAUDE_CONFIG_DIR relocates both, as it does the skill copy (#527, #2694).
"""
config = os.environ.get("CLAUDE_CONFIG_DIR")
if config:
config_dir = Path(config)
return config_dir / "CLAUDE.md", str(config_dir / "skills" / "graphify" / "SKILL.md")
return Path.home() / ".claude" / "CLAUDE.md", "~/.claude/skills/graphify/SKILL.md"
def _codebuddy_global_registration() -> Path:
"""The CODEBUDDY.md `install --platform codebuddy` registers the skill in."""
return Path.home() / ".codebuddy" / "CODEBUDDY.md"
def _print_project_git_add_hint(paths: list[Path]) -> None:
unique: list[str] = []
for path in paths:
@@ -456,9 +578,9 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li
content search through its dedicated Grep tool, not Bash (#1986) — a
Bash-only matcher never fired on the agent's primary search path.
When ``strict`` is set, the read hook carries ``--strict`` so it blocks the
first raw read per session (Claude Code only). The ``GRAPHIFY_HOOK_STRICT`` env
var can force it on or off at runtime without a reinstall.
When ``strict`` is set, both hooks carry ``--strict`` so Read and dedicated
Grep share one block per session; Bash and Glob remain advisory. The
``GRAPHIFY_HOOK_STRICT`` env var can force it on or off without a reinstall.
Each entry carries a ``timeout`` (#3314): unset, Claude Code defaults a
command hook to 600s, so a single wedged guard (a stuck filesystem, a
@@ -472,12 +594,30 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li
if " " in exe and not exe.startswith('"'):
exe = f'"{exe}"'
read_cmd = f"{exe} hook-guard read" + (" --strict" if strict else "")
search_cmd = f"{exe} hook-guard search" + (" --strict" if strict else "")
return [
{"matcher": "Bash|Grep",
"hooks": [{"type": "command", "command": f"{exe} hook-guard search", "timeout": 10}]},
"hooks": [{"type": "command", "command": search_cmd, "timeout": 10}]},
{"matcher": "Read|Glob",
"hooks": [{"type": "command", "command": read_cmd, "timeout": 10}]},
]
def _claude_sessionstart_hooks(project: bool = False) -> "list[dict]":
"""graphify's Claude Code SessionStart hook: matcher "compact" only.
Claude Code fires SessionStart with source "compact" after an auto or manual
compaction, keeping the session id. The model has lost the earlier nudges by
then, but their per-session budget is spent, so `hook-guard compact` resets
it (and the strict-mode deny marker) and restates the graph in one line.
Same command form and timeout as _claude_pretooluse_hooks; the command
carries "hook-guard", so the install/uninstall filters recognise it.
"""
exe = _resolve_graphify_exe(project=project)
if " " in exe and not exe.startswith('"'):
exe = f'"{exe}"'
return [
{"matcher": "compact",
"hooks": [{"type": "command", "command": f"{exe} hook-guard compact", "timeout": 10}]},
]
# Tokens that only ever appear in a command graphify itself writes: its
# `hook-guard <search|read|gemini>` and `hook-check` subcommands. Legacy
# (pre-#522) installs shipped an inline POSIX bash guard instead, whose command
@@ -979,7 +1119,7 @@ def install(platform: str = "claude", *, project: bool = False, project_dir: Pat
)
if platform == "opencode":
_install_opencode_plugin(project_dir if project else Path("."))
_install_opencode_plugin(_opencode_dir(project=project, project_dir=project_dir))
if project:
_print_project_git_add_hint([_project_scope_root(skill_dst, project_dir)])
@@ -996,8 +1136,9 @@ def _print_install_usage() -> None:
platforms = ", ".join([*_PLATFORM_CONFIG, "gemini", "cursor"])
print("Usage: graphify install [--project] [--strict] [--platform P|P]")
print(f"Platforms: {platforms}")
print(" --strict block the first raw file read per session until one "
"`graphify query` runs (Claude Code project hook only; needs --project)")
print(" --strict block the first raw Read or dedicated Grep per session "
"unless recently oriented with `graphify query` "
"(Claude Code project hooks only; needs --project; Bash/Glob stay advisory)")
_CLAUDE_MD_MARKER = "## graphify"
_CODEBUDDY_MD_MARKER = "## graphify"
_AGENTS_MD_MARKER = "## graphify"
@@ -1023,10 +1164,22 @@ def _gemini_hook(project: bool = False) -> dict:
"matcher": "read_file|list_directory",
"hooks": [{"type": "command", "command": f"{exe} hook-guard gemini"}],
}
def _warn_shadowing_agents_skill() -> None:
"""Gemini CLI prefers ~/.agents/skills over ~/.gemini/skills for a skill of
the same name. Before #2800 a Windows gemini install wrote there, so an old
copy can hide the one just installed. It may belong to the `agents`
platform, so point at it rather than delete it."""
shadow = _platform_skill_destination("agents")
if shadow.exists():
print(f" note: Gemini CLI loads {shadow} ahead of this install. If an older")
print(" `graphify install --platform gemini` wrote it, delete that folder;")
print(" if you use the `agents` platform, keep it.")
def gemini_install(project_dir: Path | None = None, *, project: bool = False) -> None:
"""Copy skill file, write GEMINI.md section, and install BeforeTool hook."""
project_dir = project_dir or Path(".")
skill_dst = _copy_skill_file("gemini", project=project, project_dir=project_dir)
if not project:
_warn_shadowing_agents_skill()
target = project_dir / "GEMINI.md"
@@ -1181,16 +1334,26 @@ def vscode_install(project_dir: Path | None = None) -> None:
skill_dst = _vscode_skill_destination()
with _skill_lock(skill_dst.parent):
skill_dst.parent.mkdir(parents=True, exist_ok=True)
tmp_dst = skill_dst.with_suffix(skill_dst.suffix + ".tmp")
fd, tmp_name = tempfile.mkstemp(
dir=str(skill_dst.parent),
prefix=f".{skill_dst.name}.",
suffix=".tmp",
)
tmp_dst = Path(tmp_name)
fd_closed = False
try:
shutil.copy(skill_src, tmp_dst)
with os.fdopen(fd, "wb") as dst_fh:
fd_closed = True
with open(skill_src, "rb") as src_fh:
shutil.copyfileobj(src_fh, dst_fh)
shutil.copymode(skill_src, tmp_dst)
_os_replace_with_fallback(tmp_dst, skill_dst)
except Exception:
try:
finally:
if not fd_closed:
with contextlib.suppress(OSError):
os.close(fd)
with contextlib.suppress(OSError):
tmp_dst.unlink(missing_ok=True)
except OSError:
pass
raise
# Progressive-capable: install the packaged references/ sidecar when present.
refs_src = Path(__file__).parent / "skills" / refs_bundle / "references"
if refs_src.exists():
@@ -1724,6 +1887,18 @@ export default {
"""
_OPENCODE_PLUGIN_PATH = Path(".opencode") / "plugins" / "graphify.js"
_OPENCODE_CONFIG_PATH = Path(".opencode") / "opencode.json"
def _opencode_dir(*, project: bool, project_dir: Path | None = None) -> Path:
"""OpenCode's config dir: <project>/.opencode, or ~/.config/opencode globally.
OpenCode loads plugins from <dir>/plugins/ in both. The global dir has no
.opencode/ segment, so it cannot be built by joining _OPENCODE_PLUGIN_PATH
onto a base the way the project one is (#3398).
"""
if project:
return (project_dir or Path(".")) / ".opencode"
return Path.home() / ".config" / "opencode"
# First line of every plugin graphify has written, back to the first one (#71).
_OPENCODE_PLUGIN_HEADER = "// graphify OpenCode plugin"
def _opencode_plugin_is_v1_only(body: str) -> bool:
@@ -1734,14 +1909,14 @@ def _opencode_plugin_is_v1_only(body: str) -> bool:
with "Plugin must export a default definition" (#3554, #3732).
"""
return body.startswith(_OPENCODE_PLUGIN_HEADER) and "export default" not in body
def _opencode_config_names_plugin(project_dir: Path) -> bool:
def _opencode_config_names_plugin(opencode_dir: Path) -> bool:
"""True when opencode.json still mentions the bare plugin path."""
try:
raw = (project_dir / _OPENCODE_CONFIG_PATH).read_text(encoding="utf-8")
raw = (opencode_dir / _OPENCODE_CONFIG_PATH.name).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return False
return f'"{_OPENCODE_PLUGIN_PATH.as_posix()}"' in raw
def _drop_opencode_config_entry(project_dir: Path) -> bool:
def _drop_opencode_config_entry(opencode_dir: Path) -> bool:
"""Remove the plugin entry older releases wrote into opencode.json.
The entry was the bare path ``.opencode/plugins/graphify.js``. OpenCode
@@ -1749,7 +1924,7 @@ def _drop_opencode_config_entry(project_dir: Path) -> bool:
never needed, and OpenCode 2 reads a bare path as an npm package name and
fails to install it (#3732). Returns True when the config changed.
"""
config_file = project_dir / _OPENCODE_CONFIG_PATH
config_file = opencode_dir / _OPENCODE_CONFIG_PATH.name
entry = _OPENCODE_PLUGIN_PATH.as_posix()
try:
raw = config_file.read_text(encoding="utf-8")
@@ -1762,7 +1937,7 @@ def _drop_opencode_config_entry(project_dir: Path) -> bool:
# would drop them, so say what to remove instead.
if f'"{entry}"' in raw:
print(
f" {_OPENCODE_CONFIG_PATH} -> not plain JSON, left as is; "
f" {config_file} -> not plain JSON, left as is; "
f'remove "{entry}" from its plugin list by hand'
)
return False
@@ -1780,27 +1955,28 @@ def _drop_opencode_config_entry(project_dir: Path) -> bool:
# ensure_ascii=False: keep the user's non-ASCII values readable.
_write_text_atomic(config_file, json.dumps(config, indent=2, ensure_ascii=False))
return changed
def _install_opencode_plugin(project_dir: Path) -> None:
"""Write graphify.js into .opencode/plugins/, where OpenCode discovers it.
def _install_opencode_plugin(opencode_dir: Path) -> None:
"""Write graphify.js into <opencode_dir>/plugins/, where OpenCode discovers it.
Both files are replaced atomically. The CLI refresh can run this while
OpenCode is watching them, and it must never see half a plugin.
``opencode_dir`` comes from _opencode_dir. Both files are replaced
atomically. The CLI refresh can run this while OpenCode is watching them,
and it must never see half a plugin.
"""
plugin_file = project_dir / _OPENCODE_PLUGIN_PATH
plugin_file = opencode_dir / _OPENCODE_PLUGIN_PATH.relative_to(".opencode")
_write_text_atomic(plugin_file, _OPENCODE_PLUGIN_JS)
print(f" {_OPENCODE_PLUGIN_PATH} -> tool.execute.before hook written")
print(f" {plugin_file} -> tool.execute.before hook written")
if _drop_opencode_config_entry(project_dir):
print(f" {_OPENCODE_CONFIG_PATH} -> stale plugin entry removed")
def _uninstall_opencode_plugin(project_dir: Path) -> None:
if _drop_opencode_config_entry(opencode_dir):
print(f" {opencode_dir / _OPENCODE_CONFIG_PATH.name} -> stale plugin entry removed")
def _uninstall_opencode_plugin(opencode_dir: Path) -> None:
"""Remove graphify.js plugin and deregister from opencode.json."""
plugin_file = project_dir / _OPENCODE_PLUGIN_PATH
plugin_file = opencode_dir / _OPENCODE_PLUGIN_PATH.relative_to(".opencode")
if plugin_file.exists():
plugin_file.unlink()
print(f" {_OPENCODE_PLUGIN_PATH} -> removed")
print(f" {plugin_file} -> removed")
if _drop_opencode_config_entry(project_dir):
print(f" {_OPENCODE_CONFIG_PATH} -> plugin deregistered")
if _drop_opencode_config_entry(opencode_dir):
print(f" {opencode_dir / _OPENCODE_CONFIG_PATH.name} -> plugin deregistered")
def _resolve_graphify_exe(project: bool = False) -> str:
"""Return the absolute path to the graphify executable, with forward slashes.
@@ -1849,6 +2025,12 @@ def _install_codex_hook(project_dir: Path, project: bool = False) -> None:
existing = _read_settings_for_merge(hooks_path)
graphify_exe = _resolve_graphify_exe(project=project)
if " " in graphify_exe and not graphify_exe.startswith('"'):
# Mirror _claude_pretooluse_hooks/_gemini_hook: a resolved path with
# spaces must be quoted, or every shell that runs the hook command
# (Git Bash, cmd.exe, sh) word-splits it at the first space and the
# hook can never fire.
graphify_exe = f'"{graphify_exe}"'
hook_entry = {
"hooks": {
"PreToolUse": [
@@ -1916,7 +2098,7 @@ def _agents_install(project_dir: Path, platform: str, project: bool = False) ->
if platform == "codex":
_install_codex_hook(project_dir or Path("."), project=project)
elif platform == "opencode":
_install_opencode_plugin(project_dir or Path("."))
_install_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
elif platform == "kilo":
_install_kilo_plugin(project_dir or Path("."))
@@ -2067,7 +2249,7 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
if not target.exists():
print("No AGENTS.md found in current directory - nothing to do")
if platform == "opencode":
_uninstall_opencode_plugin(project_dir or Path("."))
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
elif platform == "kilo":
_uninstall_kilo_plugin(project_dir or Path("."))
return
@@ -2077,7 +2259,7 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
if cleaned is None:
print("graphify section not found in AGENTS.md - nothing to do")
if platform == "opencode":
_uninstall_opencode_plugin(project_dir or Path("."))
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
elif platform == "kilo":
_uninstall_kilo_plugin(project_dir or Path("."))
return
@@ -2091,7 +2273,7 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
print(f"AGENTS.md was empty after removal - deleted {target.resolve()}")
if platform == "opencode":
_uninstall_opencode_plugin(project_dir or Path("."))
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
elif platform == "kilo":
_uninstall_kilo_plugin(project_dir or Path("."))
def _kilo_uninstall_global() -> list[str]:
@@ -2113,6 +2295,9 @@ def _kilo_uninstall_global() -> list[str]:
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
refs_dir = skill_dst.parent / "references"
if refs_dir.exists():
shutil.rmtree(refs_dir)
for d in (
skill_dst.parent,
skill_dst.parent.parent,
@@ -2160,8 +2345,9 @@ def claude_install(project_dir: Path | None = None, strict: bool = False, projec
print("Claude Code will now check the knowledge graph before answering")
print("codebase questions and rebuild it after code changes.")
if strict:
print("Strict mode: the first raw file read per session is blocked until")
print("one `graphify query` runs (toggle with GRAPHIFY_HOOK_STRICT=0).")
print("Strict mode: Read and dedicated Grep share one block per session")
print("unless recently oriented with `graphify query`; Bash/Glob stay advisory.")
print("Toggle with GRAPHIFY_HOOK_STRICT=0.")
def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool = False) -> None:
"""Add graphify PreToolUse hook to .claude/settings.json.
@@ -2180,11 +2366,18 @@ def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool
if not isinstance(pre_tool, list):
_refuse_to_modify(settings_path)
session_start = hooks.setdefault("SessionStart", [])
if not isinstance(session_start, list):
_refuse_to_modify(settings_path)
hooks["PreToolUse"] = _strip_graphify_hooks(pre_tool)
hooks["PreToolUse"].extend(_claude_pretooluse_hooks(strict=strict, project=project))
hooks["SessionStart"] = _strip_graphify_hooks(session_start)
hooks["SessionStart"].extend(_claude_sessionstart_hooks(project=project))
_write_settings_with_backup(settings_path, settings)
_mode = " (strict)" if strict else ""
print(f" .claude/settings.json -> PreToolUse hooks registered (Bash|Grep search + Read/Glob){_mode}")
print(" .claude/settings.json -> SessionStart hook registered (compact: resets the nudge budget)")
def _uninstall_claude_hook(project_dir: Path) -> None:
"""Remove the graphify PreToolUse hook from .claude/settings.json and its
local-only sibling .claude/settings.local.json.
@@ -2196,22 +2389,31 @@ def _uninstall_claude_hook(project_dir: Path) -> None:
for name in ("settings.json", "settings.local.json"):
_strip_graphify_hook(claude_dir / name)
def _strip_graphify_hook(settings_path: Path) -> None:
"""Drop graphify PreToolUse hooks from a single Claude settings file, if present."""
"""Drop graphify PreToolUse and SessionStart hooks from a single Claude
settings file, if present."""
if not settings_path.exists():
return
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
if not isinstance(pre_tool, list):
hooks = settings.get("hooks", {})
if not isinstance(hooks, dict):
return
filtered = _strip_graphify_hooks(pre_tool)
if filtered == pre_tool:
removed = []
for event in ("PreToolUse", "SessionStart"):
groups = hooks.get(event, [])
if not isinstance(groups, list):
continue
filtered = _strip_graphify_hooks(groups)
if filtered != groups:
hooks[event] = filtered
removed.append(event)
if not removed:
return
settings["hooks"]["PreToolUse"] = filtered
_write_settings_with_backup(settings_path, settings)
print(f" .claude/{settings_path.name} -> PreToolUse hook removed")
for event in removed:
print(f" .claude/{settings_path.name} -> {event} hook removed")
def _unsafe_purge_reason(out: Path, project_dir: Path) -> str | None:
@@ -2261,13 +2463,17 @@ def uninstall_all(project_dir: Path | None = None, purge: bool = False) -> None:
_antigravity_uninstall(pd)
# AGENTS.md covers: codex, aider, opencode, claw, droid, trae, trae-cn, hermes, copilot
_agents_uninstall(pd)
# Amp also drops a user-scope skill at ~/.config/agents/skills, which the
# AGENTS.md cleanup above does not touch.
_remove_skill_file("amp")
# The generic agents platform's user-scope skill lives at ~/.agents/skills,
# which neither the AGENTS.md cleanup nor amp's removal reaches.
_remove_skill_file("agents")
_uninstall_opencode_plugin(pd)
# `install --platform X` drops a user-scope skill (~/.codex/skills,
# ~/.config/agents/skills for amp, ~/.agents/skills, ...) that the AGENTS.md
# cleanup above does not touch, so remove every platform's.
for platform_name in _PLATFORM_CONFIG:
_remove_skill_file(platform_name)
# Kilo's global command sits outside its skill dir.
for line in _kilo_uninstall_global():
print(f" {line}")
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=pd))
# `graphify install --platform opencode` writes the plugin here (#3398).
_uninstall_opencode_plugin(_opencode_dir(project=False))
_uninstall_codex_hook(pd)
# Git hook
@@ -2313,6 +2519,11 @@ def claude_uninstall(project_dir: Path | None = None, *, project: bool = False,
_remove_skill_file("claude", project=True, project_dir=project_dir)
if remove_user_skill:
_remove_skill_file("claude", project=False)
# Without the skill, the global registration names a file that no longer
# exists, and Claude Code reads it in every session.
_remove_skill_registration(
_claude_global_registration()[0], " CLAUDE.md -> ", only_graphify_written=True
)
md_targets = [
project_dir / "CLAUDE.md",
@@ -2435,6 +2646,10 @@ def codebuddy_uninstall(project_dir: Path | None = None, *, project: bool = Fals
_remove_skill_file("codebuddy", project=True, project_dir=project_dir)
if remove_user_skill:
_remove_skill_file("codebuddy", project=False)
# Before the project-file checks below, which return early.
_remove_skill_registration(
_codebuddy_global_registration(), " CODEBUDDY.md -> ", only_graphify_written=True
)
target = project_dir / "CODEBUDDY.md"
if not target.exists():
+56 -24
View File
@@ -18,7 +18,8 @@ implementers the answer is all N, not none. Each implementer is still subject
to the single-owner guard `resolve_pascal_inherited_calls` and
`resolve_ruby_member_calls` already use: an implementer that itself declares
more than one method of the same name is ambiguous and is skipped on its own,
independently of its siblings.
independently of its siblings, unless the overloads pair up one-to-one by
signature or parameter count (C#, #4584).
The join is per method rather than per call site, so one edge per implementer
reconnects every call that reaches the interface method. Confidence is
@@ -125,6 +126,9 @@ def resolve_interface_dispatch(
mnode = node_by_id.get(method_nid)
if mnode is None or not declared_in(mnode, suffixes):
continue
# A constructor shares its type's name but implements nothing.
if (mnode.get("metadata") or {}).get("kind") == "constructor":
continue
name = method_label(mnode)
if name:
# A set, so the same method arriving on two `method` edges cannot
@@ -168,28 +172,56 @@ def resolve_interface_dispatch(
for impl_nid, impl_node in gated_impls:
impl_methods = methods_of.get(impl_nid, {})
for name, declared in interface_methods.items():
if len(declared) != 1:
continue
# Ambiguity is per implementer: one implementer overloading a
# name does not disqualify its siblings from a clean match.
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": score,
"source_file": str(impl_node.get("source_file", "")),
"source_location": impl_node.get("source_location"),
"weight": 1.0,
})
for source, target in _overload_pairs(
declared, impl_methods.get(name, set()), node_by_id
):
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": score,
"source_file": str(impl_node.get("source_file", "")),
"source_location": impl_node.get("source_location"),
"weight": 1.0,
})
all_edges.extend(new_edges)
def _overload_pairs(
declared: set[str], candidates: set[str], node_by_id: dict
) -> list[tuple[str, str]]:
"""Pair an interface's methods of one name with an implementer's.
One of each pairs up as always. Otherwise (C# overloads, #4584) each
interface method pairs with the one implementer method of the same declared
signature, else of the same parameter count among those no signature
claimed; no unique match, no edge. An implementer method takes at most one
interface method, so an overload implemented on a base class is not pinned
on a sibling of the same count.
"""
if len(declared) == 1 and len(candidates) == 1:
return [(next(iter(declared)), next(iter(candidates)))]
def _meta(nid: str) -> dict:
meta = (node_by_id.get(nid) or {}).get("metadata")
return meta if isinstance(meta, dict) else {}
pairs: dict[str, str] = {}
for key in ("signature", "arity"):
taken = set(pairs.values())
for source in sorted(declared):
want = _meta(source).get(key)
if source in pairs or want is None:
continue
hits = [c for c in candidates if c not in taken and _meta(c).get(key) == want]
if len(hits) == 1:
pairs[source] = hits[0]
# Two interface methods on one implementer method: neither is certain.
targets = list(pairs.values())
return [(s, t) for s, t in pairs.items() if targets.count(t) == 1]
+193 -28
View File
@@ -22,6 +22,7 @@ from graphify.file_slice import (
FileSlice,
bisect_slice,
expand_oversized_files,
make_full_slice,
read_slice_text,
unit_path,
)
@@ -61,6 +62,21 @@ def _get_tokenizer():
# Cached at import time. None if tiktoken is unavailable; consumers must handle.
_TOKENIZER = _get_tokenizer()
# Anything past Latin Extended (CJK, Devanagari, Cyrillic, Arabic, ...).
_NON_LATIN_RE = re.compile(r"[^\u0000-ɏ]")
def _estimate_prompt_tokens(text: str) -> int:
"""Rough token count for sizing a local model's context window.
chars/4 holds for English and code but not other scripts: on qwen2.5 a
Chinese doc came out 2.8x larger than chars/4 and a Hindi one 3.7x, so
num_ctx was too small and Ollama cut the prompt. Count non-Latin
characters as one token each, which errs on the safe side for both.
"""
non_latin = len(_NON_LATIN_RE.findall(text))
return (len(text) - non_latin) // _CHARS_PER_TOKEN + non_latin
def _resolve_ollama_base_url(default: str) -> str:
"""Resolve the Ollama base URL. Honors an explicit OLLAMA_BASE_URL first
@@ -342,6 +358,41 @@ def _resolve_max_tokens(default: int) -> int:
return default
def _openai_max_tokens_kwarg(backend: str, max_tokens: int) -> dict[str, int]:
"""Map the output cap to the OpenAI-compatible field accepted by the backend."""
# DeepSeek documents max_tokens and ignores max_completion_tokens.
key = "max_tokens" if backend == "deepseek" else "max_completion_tokens"
return {key: max_tokens}
def _provider_extra_headers(raw: object, name: str = "") -> dict[str, str] | None:
"""Validate a custom provider's providers.json ``extra_headers`` map (#3680).
Some OpenAI-compatible gateways need request headers beyond Authorization
(OpenCode Go rejects a request without ``x-opencode-session``). They are
passed to the OpenAI client as ``default_headers``, the header counterpart
of ``extra_body``. Only string-to-string entries are kept, and an
``Authorization`` entry is dropped: the API key always comes from the
provider's ``env_key``, so the config cannot swap in a different credential.
Returns None when nothing usable remains.
"""
if raw is None:
return None
if not isinstance(raw, dict):
print(f"[graphify] WARNING: provider {name!r} extra_headers is not an object; ignoring.", file=sys.stderr)
return None
headers: dict[str, str] = {}
for key, value in raw.items():
if not (isinstance(key, str) and isinstance(value, str)):
print(f"[graphify] WARNING: provider {name!r} extra_headers entry {key!r} is not a string pair; ignoring it.", file=sys.stderr)
continue
if key.strip().lower() == "authorization":
print(f"[graphify] WARNING: provider {name!r} extra_headers cannot set Authorization; ignoring it.", file=sys.stderr)
continue
headers[key] = value
return headers or None
# Model-name fragments for OpenAI-compatible "reasoning" models that reject an
# explicit temperature: the API returns 400 "Unsupported value: 'temperature'
# does not support 0 with this model. Only the default (1) value is supported."
@@ -525,9 +576,12 @@ source (a markdown or wiki link, a backticked path, a "Source:" or "Related:"
line, a module or class a design doc specifies) is a reference, not the source:
never use its path as source_file. Model the referenced file or entity as a node
attributed to the enclosing file and link to it with a `references` or `cites`
edge. Never invent, shorten or rewrite a path, and never omit source_file.
edge. Add `"metadata":{"graphify_reference_stub":true}` to every node created
solely for such a cross-document reference. Never add this marker to a node
defined by the enclosing source. Never invent, shorten or rewrite a path, and
never omit source_file.
Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
Node ID format: lowercase, word characters only (`[^\\W]` after casefolding, i.e. `[a-z0-9_]` for ASCII input but non-ASCII letters and digits are kept as-is), no dots or slashes.
Format: {stem}_{entity} where stem = full repo-relative path with the extension dropped, every segment joined with _ (e.g. src/auth/session.py -> src_auth_session); entity = symbol name (both normalised). Top-level files use just the filename stem (setup.py -> setup).
Edge direction rule — source is always the ACTOR, target is the ACTED-UPON:
@@ -792,7 +846,16 @@ def _bind_node_evidence(result: dict, text_units: "list[Path | FileSlice]", root
# No evidence. Flag only a node the model itself presented as solid
# (EXTRACTED/unset) — one it already hedged (INFERRED/AMBIGUOUS) needs no
# second flag. Idempotent: never overwrites an existing verification.
if n.get("confidence") in (None, "", "EXTRACTED") and not n.get(_VERIFICATION_FIELD):
# Matched case-insensitively, the way build._fold_confidence (#4529)
# reads it: a mis-cased enum value IS that enum value there and is
# corrected to the canonical spelling, so a node the model wrote as
# `"extracted"` reaches graph.json just as solid as `"EXTRACTED"` and
# must be evidence-checked the same. A hedged spelling in any case
# ("inferred", "ambiguous") still falls through unflagged.
_conf = n.get("confidence")
if isinstance(_conf, str):
_conf = _conf.upper()
if _conf in (None, "", "EXTRACTED") and not n.get(_VERIFICATION_FIELD):
n[_VERIFICATION_FIELD] = _UNVERIFIED_VALUE
downgraded += 1
return downgraded
@@ -1392,7 +1455,8 @@ def _backend_pkg_hint(pkg: str, extra: str) -> str:
)
def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dict:
def _ollama_request_extras(user_message: str, max_completion_tokens: int,
system_prompt: str = "") -> dict:
"""num_ctx/keep_alive for an Ollama request, sized to the prompt."""
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
# than that — the symptom is hollow 200 OK responses after the first few
@@ -1400,12 +1464,14 @@ def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dic
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
# hollow-200 symptom — just from a different direction (#798 follow-up).
# Formula: actual input tokens + output cap + system prompt headroom.
# Formula: input tokens (user message + system prompt) + output cap + margin.
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
# Auto-derive num_ctx from actual chunk size regardless — used as the
# fallback and for the mismatch check below.
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
# The system prompt is measured rather than assumed: a flat 400 was short
# of the ~760 tokens the extraction prompt really takes.
estimated_input = _estimate_prompt_tokens(user_message) + _estimate_prompt_tokens(system_prompt)
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
auto_num_ctx = max(auto_num_ctx, 8192)
if num_ctx_raw:
@@ -1432,8 +1498,6 @@ def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dic
file=sys.stderr,
)
else:
# Estimate input tokens: user_message chars / 4 (standard BPE
# heuristic) + 400 for the system prompt, then add output headroom.
num_ctx = auto_num_ctx
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
return {"options": {"num_ctx": num_ctx}, "keep_alive": keep_alive}
@@ -1522,6 +1586,7 @@ def _call_openai_compat(
deep_mode: bool = False,
images: list[_ImageRef] | None = None,
extra_body: dict | None = None,
extra_headers: dict[str, str] | None = None,
) -> dict:
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
ollama_seed = _resolve_ollama_seed() if backend == "ollama" else None
@@ -1547,14 +1612,15 @@ def _call_openai_compat(
if backend == "ollama" and not os.environ.get("GRAPHIFY_MAX_RETRIES", "").strip():
_retries = 0
client = OpenAI(api_key=api_key, base_url=base_url, timeout=_resolve_api_timeout(),
max_retries=_retries)
max_retries=_retries,
**({"default_headers": extra_headers} if extra_headers else {}))
kwargs: dict = {
"model": model,
"messages": [
{"role": "system", "content": _extraction_system(deep=deep_mode)},
{"role": "user", "content": _openai_content(user_message, images or [])},
],
"max_completion_tokens": max_completion_tokens,
**_openai_max_tokens_kwarg(backend, max_completion_tokens),
"stream": False,
}
if temperature is not None:
@@ -1583,7 +1649,8 @@ def _call_openai_compat(
# above, and replacing it here made the flag silently inert on ollama (#3988).
kwargs["extra_body"] = {
**kwargs.get("extra_body", {}),
**_ollama_request_extras(user_message, max_completion_tokens),
**_ollama_request_extras(user_message, max_completion_tokens,
kwargs["messages"][0]["content"]),
}
native = None
if backend == "ollama" and extra_body is None:
@@ -1629,6 +1696,18 @@ def _call_openai_compat(
return result
def _claude_prompt_cache_enabled() -> bool:
"""Keep prompt caching on by default; allow incompatible endpoints to opt out."""
raw = os.environ.get("GRAPHIFY_CLAUDE_PROMPT_CACHE", "").strip().lower()
if raw in ("", "1", "true", "yes", "on"):
return True
if raw in ("0", "false", "no", "off"):
return False
raise ValueError(
"GRAPHIFY_CLAUDE_PROMPT_CACHE must be 1/true/yes/on or 0/false/no/off"
)
def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False, images: list[_ImageRef] | None = None) -> dict:
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
try:
@@ -1636,6 +1715,7 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
except ImportError as exc:
raise ImportError(_backend_pkg_hint("anthropic", "anthropic")) from exc
cache_enabled = _claude_prompt_cache_enabled()
client = anthropic.Anthropic(
api_key=api_key,
base_url=BACKENDS["claude"]["base_url"],
@@ -1645,13 +1725,26 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
resp = client.messages.create(
model=model,
max_tokens=max_tokens,
system=_extraction_system(deep=deep_mode),
# The system prompt is identical on every per-file call, so mark it
# cacheable: later calls bill it as a cache read, not full input (#4835).
system=[{
"type": "text",
"text": _extraction_system(deep=deep_mode),
"cache_control": {"type": "ephemeral"},
}] if cache_enabled else _extraction_system(deep=deep_mode),
messages=[{"role": "user", "content": _anthropic_content(user_message, images or [])}],
)
raw_content = _anthropic_response_text(resp.content)
result = _parse_llm_json(raw_content or "{}")
result["input_tokens"] = (resp.usage.input_tokens or 0) if resp.usage else 0
result["output_tokens"] = (resp.usage.output_tokens or 0) if resp.usage else 0
# Anthropic reports the cached system prompt in its own cache_* fields, not
# in input_tokens; add them back so cost.json still counts the whole prompt.
usage = resp.usage
result["input_tokens"] = (
(usage.input_tokens or 0)
+ (getattr(usage, "cache_read_input_tokens", 0) or 0)
+ (getattr(usage, "cache_creation_input_tokens", 0) or 0)
) if usage else 0
result["output_tokens"] = (usage.output_tokens or 0) if usage else 0
result["model"] = model
# Normalise Anthropic's `stop_reason` to the OpenAI-compat `finish_reason`
# vocabulary so the adaptive-retry layer doesn't have to know which
@@ -2178,6 +2271,7 @@ def extract_files_direct(
deep_mode=deep_mode,
images=image_refs,
extra_body=cfg.get("extra_body"),
extra_headers=_provider_extra_headers(cfg.get("extra_headers"), backend),
)
# Verify code-typed nodes against the source the model read and downgrade the
@@ -2513,10 +2607,17 @@ def _extract_with_adaptive_retry(
}
def _split_lone_slice() -> "tuple[FileSlice, FileSlice] | None":
# When a single-unit chunk is a slice, bisect the slice so we can retry
# on a smaller range rather than give up (#1369).
if len(chunk) == 1 and isinstance(chunk[0], FileSlice) and _depth < max_depth:
return bisect_slice(chunk[0])
# When a single-unit chunk is a slice (or an eligible splittable text file
# below the char cap), bisect the slice so we can retry on a smaller
# range rather than give up (#1369, #5072).
if len(chunk) == 1 and _depth < max_depth:
unit = chunk[0]
if isinstance(unit, FileSlice):
return bisect_slice(unit)
if isinstance(unit, (Path, str)):
fs = make_full_slice(Path(unit))
if fs is not None:
return bisect_slice(fs)
return None
try:
@@ -2772,6 +2873,9 @@ def extract_corpus_parallel(
"failed_chunks": 0, # count of chunks that raised — loud failure on chunk errors
}
total = len(chunks)
# Files whose chunk raised before returning a response. The #1890
# reconciliation below must not describe them as omitted by the model (#3616).
failed_files: set[Path] = set()
def _run_one(idx: int, chunk: list[Path]) -> tuple[int, dict | None, Exception | None]:
t0 = time.time()
@@ -2799,7 +2903,39 @@ def extract_corpus_parallel(
# over session state. Force serial unless the user explicitly opts in.
if backend == "claude-cli" and os.environ.get("GRAPHIFY_CLAUDE_CLI_PARALLEL", "").strip() != "1":
max_concurrency = 1
def _checkpoint_chunk(result: dict, chunk: "list[Path | FileSlice]") -> None:
# A file split into slices is complete only once every slice has returned
# (#4943). Checkpointing each slice as it lands stamped the parent's entry
# complete after its first slice, so an interrupted run served the head of
# the file as the whole file. Its results wait here until the last slice
# succeeds, then go out in one write; a slice that fails keeps it unsaved.
slices_left: dict[Path, int] = {}
for _chunk in chunks:
for _unit in _chunk:
if isinstance(_unit, FileSlice):
slices_left[unit_path(_unit)] = slices_left.get(unit_path(_unit), 0) + 1
held_results: dict[Path, list[tuple[int, dict]]] = {}
def _checkpoint_chunk(idx: int, result: dict, chunk: "list[Path | FileSlice]") -> None:
sliced = [unit_path(u) for u in chunk if isinstance(u, FileSlice)]
for parent in sliced:
slices_left[parent] -= 1
whole = [unit_path(u) for u in chunk if not isinstance(u, FileSlice)]
if whole:
_save_checkpoint(result, whole)
for parent in dict.fromkeys(sliced):
held_results.setdefault(parent, []).append((idx, result))
if slices_left[parent] == 0:
# Chunk order, not completion order, so the entry is the same
# whichever slice returned first (#1632).
held = [r for _, r in sorted(held_results.pop(parent), key=lambda p: p[0])]
combined: dict = {
bucket: [item for r in held for item in r.get(bucket, [])]
for bucket in ("nodes", "edges", "hyperedges")
}
combined["_partial_files"] = _merged_partial_files(*held)
_save_checkpoint(combined, [parent])
def _save_checkpoint(result: dict, allowed: "list[Path]") -> None:
# Persist each chunk's semantic results to the cache as soon as it
# completes. Without this, the semantic cache is only written once, at
# the very end of the run (in __main__), so a run interrupted partway
@@ -2819,7 +2955,6 @@ def extract_corpus_parallel(
# old `.rel` attribute does not exist on FileSlice, so every sliced
# chunk leaked the FileSlice object into the allowlist and the write
# raised TypeError, silently defeating the checkpoint.)
allowed = [unit_path(item) for item in chunk]
# Deep-mode results checkpoint into their own namespace
# (cache/semantic-deep/) so a deep run never overwrites standard
# entries — and a later standard run never serves deep ones (#1894).
@@ -2853,10 +2988,11 @@ def extract_corpus_parallel(
if exc is not None:
print(f"[graphify] chunk {idx + 1}/{total} failed: {exc}", file=sys.stderr)
merged["failed_chunks"] += 1
failed_files.update(unit_path(f) for f in chunk)
continue
assert result is not None
_merge_into(merged, result)
_checkpoint_chunk(result, chunk)
_checkpoint_chunk(idx, result, chunk)
if callable(on_chunk_done):
on_chunk_done(idx, total, result)
else:
@@ -2878,15 +3014,28 @@ def extract_corpus_parallel(
file=sys.stderr,
)
merged["failed_chunks"] += 1
failed_files.update(unit_path(f) for f in chunks[idx])
continue
assert result is not None
results_by_idx[idx] = result
_checkpoint_chunk(result, chunks[idx])
_checkpoint_chunk(idx, result, chunks[idx])
if callable(on_chunk_done):
on_chunk_done(idx, total, result)
for idx in sorted(results_by_idx):
_merge_into(merged, results_by_idx[idx])
# A failed slice leaves its parent with nodes from the other slices, so the
# parent looks covered and the caller's final save would write it complete
# (#4943). Name it partial so that save stamps it and the next run retries.
failed_parents = {
unit_path(u) for chunk in chunks for u in chunk
if isinstance(u, FileSlice) and unit_path(u) in failed_files
}
if failed_parents:
merged["_partial_files"] = sorted(
set(merged.get("_partial_files", []) or []) | {str(p) for p in failed_parents}
)
# Loud failure summary — surface chunk failures at end so they're never
# buried mid-log. Exit 0 preserved for caller compatibility; the
# summary block makes the problem visible.
@@ -2991,11 +3140,25 @@ def extract_corpus_parallel(
)
merged["uncovered_files"] = [str(p) for p in uncovered]
_stamp_semantic_origin(merged)
if uncovered:
shown = ", ".join(p.name for p in uncovered[:5])
more = f" (+{len(uncovered) - 5} more)" if len(uncovered) > 5 else ""
# Split the gap by cause (#3616): a file whose chunk raised never got a
# response, so only the rest were actually omitted by the model.
unanswered = [p for p in uncovered if p in failed_files]
omitted = [p for p in uncovered if p not in failed_files]
if unanswered:
shown = ", ".join(p.name for p in unanswered[:5])
more = f" (+{len(unanswered) - 5} more)" if len(unanswered) > 5 else ""
print(
f"[graphify] WARNING: {len(uncovered)}/{len(dispatched)} dispatched file(s) "
f"[graphify] WARNING: {len(unanswered)}/{len(dispatched)} dispatched file(s) "
f"produced no nodes and are absent from the graph: {shown}{more}. Their "
"chunk failed before returning a response (see errors above); a re-run "
"will retry them.",
file=sys.stderr,
)
if omitted:
shown = ", ".join(p.name for p in omitted[:5])
more = f" (+{len(omitted) - 5} more)" if len(omitted) > 5 else ""
print(
f"[graphify] WARNING: {len(omitted)}/{len(dispatched)} dispatched file(s) "
f"produced no nodes and are absent from the graph: {shown}{more}. The model "
"returned a response but omitted them; a re-run will retry them.",
file=sys.stderr,
@@ -3205,11 +3368,13 @@ def _call_llm(
from openai import OpenAI
except ImportError as exc:
raise ImportError(_backend_pkg_hint("openai", "openai")) from exc
client = OpenAI(api_key=key, base_url=cfg["base_url"], timeout=_resolve_api_timeout(), max_retries=_resolve_max_retries())
_headers = _provider_extra_headers(cfg.get("extra_headers"), backend)
client = OpenAI(api_key=key, base_url=cfg["base_url"], timeout=_resolve_api_timeout(), max_retries=_resolve_max_retries(),
**({"default_headers": _headers} if _headers else {}))
kwargs: dict = {
"model": mdl,
"messages": [{"role": "user", "content": prompt}],
"max_completion_tokens": max_tokens,
**_openai_max_tokens_kwarg(backend, max_tokens),
# Force a single non-streamed response: some OpenAI-compatible gateways
# default to SSE streaming when `stream` is omitted, but the result here
# is always read as resp.choices[0]. Same fix as _call_openai_compat
+4 -1
View File
@@ -320,7 +320,10 @@ def _parse_pom(text: str) -> dict | None:
version = _resolve(version)
name = f"{gid}:{aid}" if gid else aid
deps: list[str] = []
for dep in root.findall(".//dependencies/dependency"):
# Only the project's own <dependencies> (and those of its profiles) are
# dependencies. <dependencyManagement> only pins versions, and a plugin's
# <dependencies> belong to the build tool.
for dep in root.findall("dependencies/dependency") + root.findall("profiles/profile/dependencies/dependency"):
da = _resolve(dep.findtext("artifactId"))
dg = _resolve(dep.findtext("groupId"))
if da:
+332 -19
View File
@@ -31,6 +31,15 @@ to the code node that defines it:
source path: ``time.sleep`` never lands on a repo's own ``sleep``, and
``Widget.render`` picks the ``render`` that ``Widget`` owns. No other
tie-breaking: an ambiguous name is a guess, and a guess is not an edge.
A bare, parenthesis-less method name is held to one more test: a word like
``redis`` is prose as often as it is a reference, so a method match survives
only when the citing section also names the class that owns it (#4609).
A bare free function name is held to the same test with its defining file in
place of the owner class: prose-like words (``token``, ``raw``) require the
citing section to cite that file or a symbol from it (#4804). Evidence is
section-scoped. Classes, snake_case, camelCase, trailing ``()``, or PascalCase
in export languages carry sufficient evidence on their own. Links to scanned
source files also mint doc->file references edges.
The match is INFERRED (0.95, a named cross-file reference).
An explicit relative cite (``./`` or ``../``) resolves against the document's
@@ -44,9 +53,13 @@ from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS
from graphify.extractors.base import (
_LANGUAGE_BUILTIN_GLOBALS,
active_scan_root as _active_scan_root,
)
MARKDOWN_MENTION_SUFFIXES = frozenset({".md", ".mdx", ".qmd", ".skill"})
@@ -62,6 +75,33 @@ def _symbol_label(node: dict[str, Any]) -> str:
return str(node.get("label", "")).strip("()").lstrip(".")
_CAMEL_CASE_RE = re.compile(r'[a-z][A-Z]')
# Languages where exported identifiers are PascalCase by convention (#4804).
_PASCAL_EXPORT_SUFFIXES = frozenset({
".go", ".cs", ".vb", ".swift", ".scala", ".pas", ".dpr", ".lpr",
".ps1", ".psm1",
})
def _is_prose_like_label(label: str) -> bool:
"""Whether a bare label looks like ordinary prose rather than a distinct code identifier.
Distinct code identifiers — snake_case (containing ``_``) or camelCase (a
lowercase letter followed by uppercase) — are exempt from the bare
free-function evidence test (#4804), while plain single-word lowercase
names (``token``, ``raw``, ``fail``, ``config``) require evidence. A
PascalCase label is exempt only in a PascalCase-export language, checked
by the caller against the target's source file.
"""
return "_" not in label and not _CAMEL_CASE_RE.search(label)
def _is_pascal_case_export_language(source_file: str) -> bool:
"""Whether *source_file*'s language exports identifiers as PascalCase."""
return os.path.splitext(_posix(source_file))[1].lower() in _PASCAL_EXPORT_SUFFIXES
def _is_file_node(node: dict[str, Any]) -> bool:
label = str(node.get("label", ""))
source_file = str(node.get("source_file", ""))
@@ -91,12 +131,101 @@ def _match_cited_file(cited: str, doc_file: str, source_files: set[str]) -> str
return None
if cited_posix in source_files:
return cited_posix
return _cited_file_suffix(cited_posix, source_files)
def _cited_file_suffix(cited_posix: str, source_files: set[str]) -> str | None:
"""The scanned file a normalized cite names by unique segment-aligned suffix."""
stripped = _RELATIVE_PREFIX_RE.sub("", cited_posix)
matches = [sf for sf in source_files
if sf == stripped or sf.endswith("/" + stripped)]
return matches[0] if len(matches) == 1 else None
def _match_cited_file_any_form(cited: str, doc_file: str,
source_files: set[str], *,
form_mismatch: bool,
scan_root: "Path | str | None" = None) -> str | None:
"""Resolve a cited file even when a partial rebuild mixes path forms.
Preserved nodes carry project-relative ``source_file`` values while a
freshly re-extracted document may carry an absolute one, so the
document-relative join in :func:`_match_cited_file` can miss a file that is
in the corpus. The suffix fallback fires only when that mixing is detected
(an absolute citing document against a corpus with relative paths) — with
uniform path forms the explicit-relative discipline above holds unchanged.
The result licenses evidence and doc->file citations, both anchored to
corpus files, so a unique corpus path that is a suffix of the joined path
is the file the document's own directory tree names.
"""
matched = _match_cited_file(cited, doc_file, source_files)
if matched is not None or not form_mismatch:
return matched
root = _posix(str(scan_root)) if scan_root is not None else None
if root is None:
active = _active_scan_root()
if active is not None:
root = _posix(str(active))
joined = _posix(os.path.normpath(
os.path.join(os.path.dirname(_posix(doc_file)), _posix(cited))))
if root is not None:
try:
rel = _posix(os.path.relpath(joined, root))
except ValueError:
return None
if rel.startswith("..") or os.path.isabs(rel):
return None
matches = [sf for sf in source_files if rel == sf or rel.endswith("/" + sf)]
return matches[0] if len(matches) == 1 else None
matches = []
doc_posix = _posix(doc_file)
for sf in source_files:
if joined == sf:
matches.append(sf)
elif joined.endswith("/" + sf):
prefix = joined[:-len(sf)]
if prefix.endswith("/") and doc_posix.startswith(prefix):
matches.append(sf)
return matches[0] if len(matches) == 1 else None
def _match_file_link(cited: str, doc_file: str,
source_files: set[str], *,
form_mismatch: bool,
scan_root: "Path | str | None" = None) -> str | None:
"""Resolve an authored Markdown link to a source file strictly against its target."""
doc_dir = os.path.dirname(_posix(doc_file))
relative = _posix(os.path.normpath(os.path.join(doc_dir, _posix(cited))))
if relative in source_files:
return relative
if not form_mismatch:
return None
root = _posix(str(scan_root)) if scan_root is not None else None
if root is None:
active = _active_scan_root()
if active is not None:
root = _posix(str(active))
if root is not None:
try:
rel = _posix(os.path.relpath(relative, root))
except ValueError:
return None
if not rel.startswith("..") and not os.path.isabs(rel) and rel in source_files:
return rel
return None
matches = []
doc_posix = _posix(doc_file)
for sf in source_files:
if relative == sf:
matches.append(sf)
elif relative.endswith("/" + sf):
prefix = relative[:-len(sf)]
if prefix.endswith("/") and doc_posix.startswith(prefix):
matches.append(sf)
return matches[0] if len(matches) == 1 else None
def _evidence(node_id: str, nodes_by_id: dict[str, dict[str, Any]],
parents: dict[str, set[str]]) -> set[str]:
"""Labels a dotted mention may qualify ``node_id`` with.
@@ -142,12 +271,16 @@ def resolve_markdown_mentions(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
*,
scan_root: "Path | str | None" = None,
) -> None:
"""Turn ``language: "markdown"`` raw calls into ``references`` edges in place."""
mentions = _markdown_raw_calls(per_file)
if not mentions:
return
root = scan_root or _active_scan_root()
code_nodes = [
n for n in all_nodes
if n.get("id") and n.get("file_type") == "code" and not _is_file_node(n)
@@ -190,34 +323,156 @@ def resolve_markdown_mentions(
candidates = narrowed
return candidates[0] if len(candidates) == 1 else None
for rc in mentions:
caller = str(rc.get("caller_nid", ""))
callee = str(rc.get("callee", "")).strip()
if not caller or not callee or caller not in node_ids:
continue
names = list(rc.get("qualifiers") or []) + [callee]
def _target(rc: dict) -> tuple[str | None, str, float]:
"""The node a mention resolves to, plus the confidence of that match."""
names = list(rc.get("qualifiers") or []) + [str(rc.get("callee", "")).strip()]
cited = rc.get("path")
if cited:
source_file = _match_cited_file(
str(cited), _posix(str(rc.get("source_file", ""))), source_files
)
if source_file is None:
continue
target = _resolve_chain(by_file[source_file], names)
confidence, score = "EXTRACTED", 1.0
return None, "EXTRACTED", 1.0
return _resolve_chain(by_file[source_file], names), "EXTRACTED", 1.0
callee = names[-1]
# Only skip a *bare* builtin-named mention (no qualifier). A dotted
# mention like `Repository.open` carries qualifier evidence that proves
# the reference, so it must not be discarded just because `open` is a
# language builtin.
if len(names) == 1 and callee in _LANGUAGE_BUILTIN_GLOBALS:
return None, "INFERRED", 0.95
qualifiers = set(names[:-1])
ns_chain = bool(rc.get("ns_qualified"))
by_name = by_label.get(callee, [])
candidates = [
c for c in by_name
if qualifiers <= _evidence(c, nodes_by_id, parents)
]
if not candidates and ns_chain:
# A PSR-4 namespace root (`App\`) maps to the scan directory and has
# no path segment, so when no candidate accounts for the whole chain,
# the leading qualifiers a candidate cannot account for are dropped
# (#4610). Only then: a qualifier that does match a candidate keeps
# discriminating (`Mailer::send()` still picks the right `send`).
def _dropped(c: str) -> bool:
evidence = _evidence(c, nodes_by_id, parents)
wanted = list(names[:-1])
while wanted and wanted[0] not in evidence:
wanted.pop(0)
return set(wanted) <= evidence
candidates = [c for c in by_name if _dropped(c)]
return (candidates[0] if len(candidates) == 1 else None), "INFERRED", 0.95
def _method_owner(node_id: str) -> str | None:
"""The class that owns *node_id*, when it is a method and not a function."""
for parent in parents.get(node_id, ()):
node = nodes_by_id.get(parent)
if node is not None and node.get("_callable_class"):
return parent
return None
def _section_chain(caller: str) -> set[str]:
"""*caller* (a heading or page) plus every heading enclosing it.
A citation recorded under a heading licenses bare mentions in that
heading's own section and every section nested inside it; a sibling
section is not covered (#4804).
"""
chain = {caller}
frontier = [caller]
while frontier:
nid = frontier.pop()
for p in parents.get(nid, ()):
if p not in chain:
chain.add(p)
frontier.append(p)
return chain
#: Targets already cited by each caller (heading or page), used as
#: section-scoped evidence in passes 2b and 2c.
cited_targets: dict[str, set[str]] = {}
# Files cited via file spans, path-qualified mentions, or links (#4804).
code_file_nodes = {
_posix(str(n.get("source_file"))): n["id"]
for n in all_nodes
if n.get("id") and n.get("file_type") == "code"
and n.get("source_file") and _is_file_node(n)
}
citable_files = set(code_file_nodes)
# Detect path mixing in partial rebuilds (absolute doc vs relative corpus).
corpus_has_relative_paths = any(not os.path.isabs(sf) for sf in citable_files)
cited_files: dict[str, set[str]] = {}
for rc in mentions:
cited = rc.get("path")
if not cited:
continue
caller = str(rc.get("evidence_owner") or rc.get("caller_nid", ""))
if not caller:
continue
doc = _posix(str(rc.get("source_file", "")))
if rc.get("file_link") and not rc.get("wikilink"):
source_file = _match_file_link(
str(cited), doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
else:
if callee in _LANGUAGE_BUILTIN_GLOBALS:
continue
qualifiers = set(names[:-1])
candidates = [
c for c in by_label.get(callee, [])
if qualifiers <= _evidence(c, nodes_by_id, parents)
]
target = candidates[0] if len(candidates) == 1 else None
confidence, score = "INFERRED", 0.95
source_file = _match_cited_file_any_form(
str(cited), doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
if source_file is not None:
cited_files.setdefault(caller, set()).add(source_file)
# Mint page --references--> file edges for links to scanned files (#4804).
for rc in mentions:
if not rc.get("file_link"):
continue
caller = str(rc.get("caller_nid", ""))
cited = str(rc.get("path") or "")
if not caller or caller not in node_ids or not cited:
continue
doc = _posix(str(rc.get("source_file", "")))
if rc.get("wikilink"):
target_file = _match_cited_file_any_form(
cited, doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
else:
target_file = _match_file_link(
cited, doc, citable_files,
form_mismatch=os.path.isabs(doc) and corpus_has_relative_paths,
scan_root=root,
)
target = code_file_nodes.get(target_file) if target_file else None
if target is None or target == caller or (caller, target) in existing:
continue
existing.add((caller, target))
all_edges.append({
"source": caller,
"target": target,
"relation": "references",
"context": rc.get("context", ""),
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
def _add(rc: dict, target: str | None, confidence: str, score: float) -> None:
caller = str(rc.get("caller_nid", ""))
if target is None or target == caller:
return
if (caller, target) in existing:
# Retain target as section-scoped citation evidence (#4609, #4804).
cited_targets.setdefault(caller, set()).add(target)
return
existing.add((caller, target))
all_edges.append({
"source": caller,
"target": target,
@@ -229,3 +484,61 @@ def resolve_markdown_mentions(
"source_location": rc.get("source_location"),
"weight": 1.0,
})
cited_targets.setdefault(caller, set()).add(target)
# Pass 1: explicit evidence resolves directly (path, dotted chain, or trailing ()).
bare: list[dict] = []
for rc in mentions:
caller = str(rc.get("caller_nid", ""))
callee = str(rc.get("callee", "")).strip()
if not caller or not callee or caller not in node_ids:
continue
names = list(rc.get("qualifiers") or []) + [callee]
span = str(rc.get("context") or "")
if rc.get("path") or len(names) > 1 or "(" in span:
_add(rc, *_target(rc))
else:
bare.append(rc)
# Pass 2a: classes and distinct identifiers (snake_case, camelCase, export PascalCase).
method_mentions: list[tuple[dict, str, str, float]] = []
function_mentions: list[tuple[dict, str, str, float]] = []
for rc in bare:
target, confidence, score = _target(rc)
if target is None:
continue
if nodes_by_id.get(target, {}).get("_callable_class"):
_add(rc, target, confidence, score)
elif _method_owner(target) is not None:
method_mentions.append((rc, target, confidence, score))
else:
label = _symbol_label(nodes_by_id[target])
if label[:1].isupper():
prose_like = not _is_pascal_case_export_language(
nodes_by_id[target].get("source_file", ""))
else:
prose_like = _is_prose_like_label(label)
if prose_like:
function_mentions.append((rc, target, confidence, score))
else:
_add(rc, target, confidence, score)
# Pass 2b: bare method mentions require the owner class to be cited (#4609).
for rc, target, confidence, score in method_mentions:
chain = _section_chain(str(rc.get("caller_nid", "")))
cited = {t for c in chain for t in cited_targets.get(c, ())}
if _method_owner(target) in cited:
_add(rc, target, confidence, score)
# Pass 2c: bare prose-like free function names require defining file or symbol evidence (#4804).
for rc, target, confidence, score in function_mentions:
target_file = _posix(str(nodes_by_id.get(target, {}).get("source_file") or ""))
if not target_file:
continue
chain = _section_chain(str(rc.get("caller_nid", "")))
cited = {t for c in chain for t in cited_targets.get(c, ())}
if target_file in {f for c in chain for f in cited_files.get(c, ())} or any(
_posix(str(nodes_by_id.get(t, {}).get("source_file") or "")) == target_file
for t in cited
):
_add(rc, target, confidence, score)
+62 -7
View File
@@ -53,6 +53,34 @@ def _out_from_env() -> str:
GRAPHIFY_OUT = _out_from_env()
def os_long_path(path: "str | Path") -> str:
r"""Return an OS path string safe for open()/stat() on Windows long paths.
On win32, paths longer than the legacy MAX_PATH (260 chars) are rejected by
the plain file APIs unless prefixed with the extended-length marker ``\\?\``
(which also requires a fully-qualified path). Without it, _md5_file /
save_manifest / count_words silently fail to hash deeply-nested files, so
their manifest entry never stabilizes and detect_incremental re-flags them
as changed on every run (#1655), and cache entries under a deep root cannot
be written at all. cache._normalize_path strips this prefix for stable
KEYS; this adds it for I/O. Non-win32 and already-prefixed paths pass
through unchanged.
"""
if sys.platform != "win32":
return str(path)
s = str(path)
if s.startswith("\\\\?\\"):
return s
try:
s = os.path.abspath(s) # \\?\ requires a fully-qualified path
except Exception:
return str(path)
if s.startswith("\\\\"):
# UNC share \\server\share -> \\?\UNC\server\share
return "\\\\?\\UNC\\" + s[2:]
return "\\\\?\\" + s
def os_replace_with_fallback(src: "str | Path", dst: "str | Path") -> None:
"""``os.replace(src, dst)``, falling back to a copy for a known set of
Windows quirks (#3508) that raise even when ``src``/``dst`` are the same
@@ -543,6 +571,35 @@ def nfc(s: str) -> str:
return unicodedata.normalize("NFC", s)
def read_graph_json(path) -> dict:
"""A graph file's data with one copy of each string its rows repeat."""
shared: dict[str, str] = {}
def share(row: dict) -> dict:
for field, value in row.items():
if type(value) is str:
row[field] = shared.setdefault(value, value)
return row
return json.loads(Path(path).read_text(encoding="utf-8"), object_hook=share)
def consumed(rows: list):
"""Each row in order, let go as it is taken, so a graph built from them never holds both."""
rows.reverse()
while rows:
yield rows.pop()
def consumed_graph_rows(data: dict) -> dict:
"""``data`` for networkx to build a graph from once, stamped as ``restore_arc_direction`` stamps it."""
for link in data["links"]:
if isinstance(link, dict):
link["_src"] = link.get("_src", link.get("source"))
link["_tgt"] = link.get("_tgt", link.get("target"))
return dict(data, nodes=consumed(data["nodes"]), links=consumed(data["links"]))
def restore_arc_direction(data: dict) -> dict:
"""Stamp each link's stored direction as ``_src``/``_tgt`` before loading.
@@ -578,16 +635,14 @@ def load_node_link_graph(path_or_data):
"""
from networkx.readwrite import json_graph
data = path_or_data
if not isinstance(data, dict):
owned = not isinstance(data, dict)
if owned:
p = Path(data)
from graphify.security import check_graph_file_size_cap # lazy: security imports paths
check_graph_file_size_cap(p)
data = json.loads(p.read_text(encoding="utf-8"))
data = read_graph_json(p)
if isinstance(data, dict) and "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
if isinstance(data, dict):
data = restore_arc_direction(data)
try:
return json_graph.node_link_graph(data, edges="links")
except TypeError: # networkx too old for the edges kwarg; default is "links"
return json_graph.node_link_graph(data)
data = consumed_graph_rows(data) if owned and isinstance(data.get("links"), list) else restore_arc_direction(data)
return json_graph.node_link_graph(data, edges="links")
+9 -1
View File
@@ -186,6 +186,14 @@ def _detect_default_branch(repo: str | None = None) -> str:
_CI_FAILURE_CONCLUSIONS = frozenset({"FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"})
# CheckStatusState has six values: REQUESTED, QUEUED, IN_PROGRESS, COMPLETED,
# WAITING and PENDING. Every one but COMPLETED means the run has not finished,
# so it carries no conclusion yet and nothing else in the rollup speaks for it.
# Matching only IN_PROGRESS/QUEUED left WAITING (a job held by a deployment
# protection rule), REQUESTED and PENDING runs invisible — NONE on their own,
# and masked as SUCCESS by any sibling check that had already passed.
_CI_PENDING_STATUSES = frozenset({"REQUESTED", "QUEUED", "IN_PROGRESS", "WAITING", "PENDING"})
def _parse_ci(rollup: list) -> str:
if not rollup:
@@ -198,7 +206,7 @@ def _parse_ci(rollup: list) -> str:
if conclusions & (_CI_FAILURE_CONCLUSIONS | {"ERROR"}):
return "FAILURE"
statuses = {r.get("status") for r in rollup}
if "IN_PROGRESS" in statuses or "QUEUED" in statuses or conclusions & {"PENDING", "EXPECTED"}:
if statuses & _CI_PENDING_STATUSES or conclusions & {"PENDING", "EXPECTED"}:
return "PENDING"
if "SUCCESS" in conclusions:
return "SUCCESS"
Loaded 100 of 479 files, more files were not shown because too many files have changed in this diff. Show more