Compare commits

...
42 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
58 changed files with 5864 additions and 255 deletions

No files matched your search

+16
View File
@@ -79,6 +79,11 @@ 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
@@ -122,6 +127,17 @@ carry `INFERRED` confidence. Bare calls to package-level functions remain `EXTRA
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.
+33 -6
View File
@@ -2,6 +2,33 @@
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).
@@ -19,12 +46,12 @@ Full release notes with details on each version: [GitHub Releases](https://githu
- 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 (#5020, 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 (#5020, 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 (#5020, 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 (#5020, 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, 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 (#5019, thanks @neumannpeter1231-lang).
- 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).
+17 -13
View File
@@ -318,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
+72 -3
View File
@@ -723,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.
@@ -743,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"
@@ -1622,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
@@ -2476,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
@@ -2504,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
@@ -2516,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)),
)
@@ -3097,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
@@ -3242,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
+93 -1
View File
@@ -38,7 +38,7 @@ except Exception:
_EXTRACTOR_VERSION = "unknown"
# Bump when AST cache-key semantics change independently of the package version.
_AST_CACHE_SCHEMA = 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 the interface's implicit implementers (#4934), so cached Solidity, Python, Kotlin and Go extractions re-run; prior (36): C++ extraction changes: a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling so it no longer loses to a same-normalized function, and a salted alias keeps its own `contains` edge (#4951); a member call `x.m()` binds by the receiver's type, now typed from parameters and class fields and not just locals, with untyped receivers kept bound in-file (#3215, #4946); an out-of-line/split-header definition attaches to the unique owner whose class file is in its include set via a `_cpp_qualified` identity marker, instead of file-containing or cross-binding to an unrelated same-named function (#4916, #4920); and a local callable value (a lambda or `std::function` local) 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 (#4917, #4921), so cached C++ extractions re-run; prior (35): A Rust module-qualified call like `crate::b::helper()` resolves to the function it names via qualifier-verified cross-file resolution, kept inside the caller's crate and out of local names (#2135, #4944); a Rust call written inside an expression macro's arguments (`println!`, `vec!`, ...) is linked, with a parsed call winning the dedupe (#4945); and cache keys keep their written case (file I/O through os_long_path, cache identity via normpath not normcase, anLine truncated
_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
@@ -1849,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("."),
+116 -3
View File
@@ -458,11 +458,28 @@ def _handle_unverified_semantic_shrink(
partial_semantic_files,
failed_ast_sources,
semantic_files,
cached_semantic_files=None,
sem_cache_mode=None,
sem_prompt=None,
cache_root=None,
):
"""Shared handling for the #3203 unverified-semantic-shrink guard on both the
raw and clustered write paths (they differ only in where the flag is read
from — ``merged`` vs ``G.graph``). Always prints the actionable notice.
The same under-produced source also has to be kept out of the semantic
cache (#5083): the cache is unversioned and content-hash keyed, so a
degraded chunk would otherwise be replayed as authoritative on every later
run, the shrink guard would keep refusing the write, and no LLM call would
ever be made again. ``save_semantic_cache`` cannot see graph.json (and must
not: it has no business reading the graph), so the entry is stamped
``partial`` here, after the guard has measured the shrink.
``cached_semantic_files`` identifies which shrinking sources were REPLAYED
from the cache this run (as opposed to freshly extracted), so the message
can call out the poisoned-entry replay instead of repeating the
``--allow-partial`` advice — which would commit the degraded replay and
drop the prior nodes.
Returns None when there is no shrink, else ``(incomplete, manifest_files,
cleared_semantic)`` — the latter two are None unless the guard armed
(``not cli_allow_partial``), so the caller mirrors the original inline logic.
@@ -485,16 +502,83 @@ def _handle_unverified_semantic_shrink(
)
stamped = {f for _flist in manifest_files.values() for f in _flist}
cleared_semantic = {str(p) for p in semantic_files} - stamped
def _path_key(value) -> str:
p = Path(value)
if not p.is_absolute():
p = Path(target) / p
try:
return os.path.normcase(str(p.resolve()))
except (OSError, RuntimeError):
return os.path.normcase(os.path.abspath(str(p)))
cached_keys = {_path_key(p) for p in (cached_semantic_files or [])}
cached_sources = sorted(
sf for sf in unverified_shrink if _path_key(sf) in cached_keys
)
fresh_sources = sorted(
sf for sf in unverified_shrink if _path_key(sf) not in cached_keys
)
marked: list[Path] = []
try:
from graphify.cache import mark_semantic_cache_partial as _mark_partial
marked = _mark_partial(
sorted(unverified_shrink),
root=Path(target),
mode=sem_cache_mode,
prompt=sem_prompt,
cache_root=cache_root,
)
except Exception as exc: # noqa: BLE001 — cache marking is best-effort
print(
f"[graphify extract] warning: could not mark degraded semantic "
f"cache entries: {exc}",
file=sys.stderr,
)
details = ", ".join(
f"'{sf}' ({prior} -> {fresh} nodes)"
for sf, (prior, fresh) in sorted(unverified_shrink.items())
)
print(
f"[graphify extract] semantic extraction is incomplete: unverified semantic "
f"shrink detected for {details}. The shrink guard stays armed for this write; "
"pass --allow-partial to overwrite a larger existing graph anyway.",
f"shrink detected for {details}.",
file=sys.stderr,
)
if cached_sources:
cached_details = ", ".join(
f"'{sf}' ({unverified_shrink[sf][0]} -> {unverified_shrink[sf][1]} nodes)"
for sf in cached_sources
)
replay_effect = (
"--allow-partial was passed, so the degraded replay is being written "
"over the existing graph and the prior nodes are dropped."
if cli_allow_partial
else "Do NOT pass --allow-partial here: it would write the degraded "
"replay over the larger existing graph and drop the prior nodes."
)
print(
f"[graphify extract] {cached_details} was replayed from the semantic "
"cache, not freshly extracted, so re-running with the same cache would "
"replay it again. " + replay_effect + " Re-run to re-extract the "
"marked source(s).",
file=sys.stderr,
)
if marked:
print(
"[graphify extract] marked "
f"{len(marked)} semantic cache entr{'y' if len(marked) == 1 else 'ies'} "
f"partial for re-extraction on the next run: "
f"{', '.join(str(p) for p in marked)}",
file=sys.stderr,
)
if fresh_sources and not cli_allow_partial:
print(
"[graphify extract] The shrink guard stays armed for this write; "
"pass --allow-partial to overwrite a larger existing graph anyway.",
file=sys.stderr,
)
return incomplete, manifest_files, cleared_semantic
@@ -4834,7 +4918,8 @@ def dispatch_command(cmd: str) -> None:
# graphify-out/ dir into a project that asked for external output.
# `root` stays the scanned project so source_file/ids relativize
# against it; conflating the two basenamed every node (#1941).
ast_kwargs: dict = {"cache_root": out_root, "root": target}
# One extract() per process here, so free its parse memo when done.
ast_kwargs: dict = {"cache_root": out_root, "root": target, "release_parse_memo": True}
if cli_max_workers is not None:
ast_kwargs["max_workers"] = cli_max_workers
# #2437/#2438 (the `graphify update` twin of watch's #2406 fix): an
@@ -4980,10 +5065,13 @@ def dispatch_command(cmd: str) -> None:
_ctx_edges.append(_ctx_edge)
except Exception:
_ctx_nodes, _ctx_edges = [], []
# Only the context lists are needed; free the full parse.
_ctx_graph = None
if _ctx_nodes:
ast_kwargs["resolution_context_nodes"] = _ctx_nodes
if _ctx_edges:
ast_kwargs["resolution_context_edges"] = _ctx_edges
del _ctx_nodes, _ctx_edges
print(f"[graphify extract] AST extraction on {len(code_files)} code files...")
try:
ast_result = _ast_extract(code_files, **ast_kwargs)
@@ -4998,6 +5086,9 @@ def dispatch_command(cmd: str) -> None:
sys.exit(1)
ast_result = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
_extraction_incomplete = True # the whole AST pass was lost
# Only extract() reads the resolution context; free it before the
# semantic pass and graph build.
del ast_kwargs
stages.mark("AST extract")
# Semantic extraction on docs/papers/images. Check cache first.
@@ -5018,6 +5109,11 @@ def dispatch_command(cmd: str) -> None:
_partial_semantic_files: set[str] = set()
sem_cache_hits = 0
sem_cache_misses = 0
# Files served from the semantic cache this run (absolute paths), used
# by the #3203 shrink handler to tell a poisoned cached replay from a
# fresh under-production (#5083).
_cached_semantic_paths: list[str] = []
uncached_paths: list[str] = []
# Deep mode uses its own namespace (cache/semantic-deep/) so deep and
# standard results for the same content never shadow each other (#1894).
sem_cache_mode = "deep" if deep_mode else None
@@ -5042,6 +5138,10 @@ def dispatch_command(cmd: str) -> None:
)
sem_cache_hits = len(semantic_files) - len(uncached_paths)
sem_cache_misses = len(uncached_paths)
_uncached_set = set(uncached_paths)
_cached_semantic_paths = [
p for p in sem_paths_str if p not in _uncached_set
]
sem_result["nodes"].extend(cached_nodes)
sem_result["edges"].extend(cached_edges)
sem_result["hyperedges"].extend(cached_hyperedges)
@@ -5439,6 +5539,10 @@ def dispatch_command(cmd: str) -> None:
partial_semantic_files=_partial_semantic_files,
failed_ast_sources=_failed_ast_sources,
semantic_files=semantic_files,
cached_semantic_files=_cached_semantic_paths,
sem_cache_mode=sem_cache_mode,
sem_prompt=sem_prompt,
cache_root=out_root,
)
if _shrink is not None and _shrink[0]:
_extraction_incomplete = True
@@ -5596,6 +5700,10 @@ def dispatch_command(cmd: str) -> None:
partial_semantic_files=_partial_semantic_files,
failed_ast_sources=_failed_ast_sources,
semantic_files=semantic_files,
cached_semantic_files=_cached_semantic_paths,
sem_cache_mode=sem_cache_mode,
sem_prompt=sem_prompt,
cache_root=out_root,
)
if _shrink is not None and _shrink[0]:
_extraction_incomplete = True
@@ -5614,6 +5722,11 @@ def dispatch_command(cmd: str) -> None:
else:
G = _build([merged], dedup=not no_dedup, dedup_llm_backend=dedup_backend, root=target)
stages.mark("build")
# G holds its own copy of every node and edge now. Drop the raw
# extraction lists so cluster/analyze/export can reuse that memory.
ast_result = sem_result = pg_result = cargo_result = fresh = {}
cached_nodes = cached_edges = cached_hyperedges = []
merged = {"input_tokens": merged["input_tokens"], "output_tokens": merged["output_tokens"]}
if G.number_of_nodes() == 0:
print(
"[graphify extract] graph is empty — extraction produced no nodes. "
+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:
+11 -3
View File
@@ -3057,12 +3057,20 @@ 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(
+19 -3
View File
@@ -308,6 +308,9 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
# 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():
@@ -334,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)
@@ -361,7 +367,7 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
]
folded: dict[str, str] = {}
missing = _lost_saved_semantic_nodes(
existing_nodes, new_node_list, set(), folded, dedup_remap=dedup_remap,
existing_nodes, new_node_list, replaced_sources, folded, dedup_remap=dedup_remap,
)
if missing:
import sys as _sys
@@ -395,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()}
@@ -468,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", {}):
@@ -490,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:
+470 -5
View File
@@ -147,6 +147,7 @@ from graphify.extractors.resolution import ( # noqa: E402,F401
_package_entry_candidates,
_parse_js_tree,
_parse_python_tree,
_parse_python_tree_cached,
_pascal_class_stem_cache,
_pascal_project_root,
_pascal_resolve_class,
@@ -5030,6 +5031,9 @@ def _merge_csharp_partial_class_nodes(
cn = rc.get("caller_nid")
if cn in remap:
rc["caller_nid"] = remap[cn]
eo = rc.get("evidence_owner")
if eo in remap:
rc["evidence_owner"] = remap[eo]
def _drop_shadowed_csharp_partial_bases(all_nodes: list[dict], all_edges: list[dict]) -> None:
@@ -6159,15 +6163,16 @@ def _resolve_cpp_member_calls(
The shared cross-file pass drops every ``is_member_call`` because a bare method
name (``bar``) collides across the corpus and inflates god-nodes (#543/#1219).
The C++ extractor records each member call's receiver and a per-file
``var -> ClassName`` table (``cpp_type_table``) built from local declarations.
The C++ extractor records lexical receiver bindings, access chains and
class-scoped field types. Older scoped-call records also use a per-file
``var -> ClassName`` table (``cpp_type_table``).
This pass types the receiver, then emits an edge ONLY when that type resolves
to exactly ONE definition (the god-node guard).
Receiver typing, by precision tier:
* ``Foo::bar()`` — the scope ``Foo`` names the type explicitly -> EXTRACTED.
* ``this->bar()`` — the receiver is the caller's own enclosing class -> EXTRACTED.
* ``f.bar()`` / ``f->bar()`` — ``f`` typed via the file's local table -> INFERRED.
* ``f.bar()`` / ``f->bar()`` and field chains — declared receiver types -> INFERRED.
A receiver whose type can't be inferred locally is SKIPPED (no guess): a false
call edge is worse than a missing one. The ``_merge_decl_def_classes`` pass has
already folded each header/impl class pair into one node, so a paired class is a
@@ -6231,6 +6236,99 @@ def _resolve_cpp_member_calls(
if n.get("source_file") and label.endswith("()") and "::" in label:
qualified_method_nids.setdefault(label, []).append(n["id"])
# Receiver chains use literal, case-sensitive identities, including namespaces.
qualified_types: dict[str, list[str]] = {}
simple_types: dict[str, list[str]] = {}
exact_methods: dict[tuple[str, str], set[str]] = {}
for n in all_nodes:
identity = n.get("_cpp_qualified")
if identity and "_cpp_fields" in n and n.get("id") in contained and _is_type_like_definition(n):
qualified_types.setdefault(identity, []).append(n["id"])
simple_types.setdefault(identity.rsplit("::", 1)[-1], []).append(n["id"])
for rel in ("defines", "method"):
grouped: dict[tuple[str, str], set[str]] = {}
for e in all_edges:
target_node = node_by_id.get(e.get("target", ""), {})
label = target_node.get("label", "")
if e.get("relation") == rel and label.endswith("()"):
name = label.removesuffix("()").lstrip(".").rsplit("::", 1)[-1]
grouped.setdefault((e["source"], name), set()).add(e["target"])
exact_methods.update(grouped)
def chain_type(name: str, scope: str, operator: str) -> str | None:
name = re.sub(r"\b(const|volatile)\b", "", name).strip()
identifier = r"(?:::)?[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*"
if operator == "->":
smart = re.fullmatch(rf"std::(?:unique_ptr|shared_ptr)\s*<\s*({identifier})\s*>", name)
if smart:
name = smart[1]
elif name.endswith("*"):
name = name[:-1].strip()
else:
return None
elif operator != ".":
return None
if not re.fullmatch(identifier, name):
return None
absolute = name.startswith("::")
name = name.removeprefix("::")
if not absolute:
while scope:
candidates = qualified_types.get(f"{scope}::{name}", [])
if candidates:
return candidates[0] if len(candidates) == 1 else None
scope = scope.rsplit("::", 1)[0] if "::" in scope else ""
candidates = qualified_types.get(name, [])
if not candidates and not absolute and "::" not in name:
candidates = simple_types.get(name, [])
return candidates[0] if len(candidates) == 1 else None
def resolve_chain(rc: dict) -> str | None:
chain = rc["cpp_receiver_chain"]
if not chain:
return None
root_name = chain[0][0]
owner = enclosing_type.get(rc["caller_nid"], "")
owner_node = node_by_id.get(owner, {})
scope = rc.get("cpp_receiver_scope", owner_node.get("_cpp_qualified", ""))
if root_name == "this":
name = owner_node.get("_cpp_qualified", "") + "*"
elif "cpp_receiver_type" in rc:
name = rc["cpp_receiver_type"]
else:
name = owner_node.get("_cpp_fields", {}).get(root_name, "")
type_nid = ""
for index, (member, operator) in enumerate(chain):
if index:
owner_node = node_by_id.get(type_nid, {})
name = owner_node.get("_cpp_fields", {}).get(member, "")
scope = owner_node.get("_cpp_qualified", "")
type_nid = chain_type(name, scope, operator)
if type_nid is None:
return None
return type_nid
def chain_park_name(rc: dict) -> str | None:
"""The bare receiver-type name of a SINGLE-element C++ chain, so a call
onto a typed local whose class is declared in no local file can still be
PARKED for the cross-repo merge instead of dropped (#3152). A multi-hop
chain is not a single parkable name, and `this`/field roots are in-repo."""
chain = rc["cpp_receiver_chain"]
if len(chain) != 1 or "cpp_receiver_type" not in rc:
return None
name = re.sub(r"\b(const|volatile)\b", "", rc["cpp_receiver_type"]).strip()
identifier = r"(?:::)?[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*"
if chain[0][1] == "->":
smart = re.fullmatch(rf"std::(?:unique_ptr|shared_ptr)\s*<\s*({identifier})\s*>", name)
if smart:
name = smart[1]
elif name.endswith("*"):
name = name[:-1].strip()
else:
return None
name = name.removeprefix("::")
return name if re.fullmatch(r"[A-Za-z_]\w*", name) else None
all_raw_calls: list[dict] = []
for result in per_file:
all_raw_calls.extend(result.get("raw_calls", []))
@@ -6252,7 +6350,22 @@ def _resolve_cpp_member_calls(
continue
# Determine the receiver's type and the resulting confidence.
qualified_fallback_label: str | None = None
if receiver == "this":
if "cpp_receiver_chain" in rc:
type_nid = resolve_chain(rc)
if type_nid is None:
# A single-element chain whose receiver type is known but declared
# in no local file is a cross-repo candidate: park it by type name
# for the merge to finish, as the non-chain receiver path does
# below — otherwise a typed local calling into another repo is
# silently dropped (#3152 regression from the chain resolver).
park_name = chain_park_name(rc)
if park_name is not None and not type_def_nids.get(_key(park_name)):
_park_unresolved_member_call(
node_by_id.get(caller), callee, park_name, "cpp", rc,
)
continue
type_qualified = receiver == "this" and len(rc["cpp_receiver_chain"]) == 1
elif receiver == "this":
# this->bar(): receiver is the caller's own enclosing class.
type_nid = enclosing_type.get(caller)
if not type_nid:
@@ -6305,7 +6418,11 @@ def _resolve_cpp_member_calls(
continue
type_nid = type_defs[0]
type_qualified = False
method_nid = method_index.get((type_nid, _key(callee)))
if "cpp_receiver_chain" in rc:
methods = exact_methods.get((type_nid, callee), set())
method_nid = next(iter(methods)) if len(methods) == 1 else None
else:
method_nid = method_index.get((type_nid, _key(callee)))
if method_nid is None and qualified_fallback_label is not None:
candidates = qualified_method_nids.get(qualified_fallback_label, [])
if len(candidates) == 1:
@@ -6328,6 +6445,32 @@ def _resolve_cpp_member_calls(
})
# C# predefined/BCL type names that are never declared in the scanned corpus.
# A receiver of one of these types can still be the target of an extension method
# (`this string`), so the extractor now stamps the type name (#4828) — but the
# type is not a cross-repo candidate, so a failed instance lookup must not park it
# as one (#3152).
# Member names a BCL type owns. A receiver whose type is *not* declared in the
# corpus could be a BCL type, and if it is, an instance method of that name beats
# any extension. Without a BCL symbol table the graph cannot prove the negative,
# so these names are never bound through an out-of-corpus receiver (#4828). A
# generic (`this T`) or `this object` declaration is still subject to this rule.
_CSHARP_BCL_MEMBER_NAMES = frozenset({
"Add", "Any", "Cast", "Clear", "Compare", "CompareTo", "Concat", "Contains",
"CopyTo", "Count", "Dispose", "Equals", "First", "ForEach", "Format",
"GetEnumerator", "GetHashCode", "GetType", "GetValue", "IndexOf", "Insert",
"Join", "Keys", "Last", "Length", "Parse", "Remove", "Replace", "Select",
"Split", "Substring", "ToArray", "ToDictionary", "ToLower", "ToList",
"ToString", "ToUpper", "Trim", "TryParse", "Values", "Where",
})
_CSHARP_WELL_KNOWN_TYPES = frozenset({
"bool", "byte", "char", "decimal", "double", "dynamic", "float", "int",
"long", "nint", "nuint", "object", "sbyte", "short", "string", "uint",
"ulong", "ushort", "void",
})
def _csharp_overload_index(nodes: list[dict], edges: list[dict]) -> dict:
"""Method nodes by id and their owning type, for C# methods with an arity."""
node_by_id = {n.get("id"): n for n in nodes}
@@ -6535,8 +6678,15 @@ def _resolve_csharp_member_calls(
``_resolve_type_name_nid`` collapses "absent", "ambiguous" and "scoping was
decisive" into one ``None``, and only the first is a cross-repo candidate,
so re-check the bare-name index instead of trusting the ``None``.
A well-known BCL name is NOT a cross-repo candidate: ``string``/``int``
receivers are typed now that extension methods need their declared type
(#4828), and parking every ``x.ToString()`` would stamp a useless
``unresolved_calls`` payload on most caller nodes in a .NET corpus.
"""
if type_name and not type_def_nids.get(_key(type_name)):
if str(type_name).lower() in _CSHARP_WELL_KNOWN_TYPES:
return
_park_unresolved_member_call(
caller_node, rc.get("callee"), type_name, "csharp", rc,
)
@@ -6706,6 +6856,301 @@ def _resolve_csharp_member_calls(
})
def _resolve_csharp_extension_calls(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Bind C# extension-method calls (``recv.Ext()``) to their declaration (#4828).
An extension invocation is static dispatch: the receiver is the first
argument of a method declared on a *static class*, not a member of the
receiver's type. ``_resolve_csharp_member_calls`` therefore cannot see it —
it looks the name up on the receiver's type and its base chain, and an
extension lives on a sibling type — so a widely used helper had no callers
in the graph and looked dead.
The declaration side now records ``extended_type`` (plus arity and a
type-parameter marker) on the extension node; this pass joins call sites to
it. Every rule is a C# resolution rule, and anything unprovable is dropped:
* the receiver's declared type must be in the corpus and its base chain
fully resolved — an out-of-corpus base may declare an *instance* member
of that name, which always wins over an extension;
* the receiver type must declare no instance member of that name;
* the declaring static class's namespace must be visible at the call site,
walking the enclosing namespace declarations outward (a file-level
``using`` belongs to the compilation unit, so an inner-namespace
extension wins);
* the extended type must be the receiver's type or one of its resolved
base types or interfaces;
* the declaration must accept the call's argument count, using the same
``arity``/``min_arity`` facts #4584 already records (the receiver is one
parameter short of the call);
* more than one surviving declaration is ambiguous and binds nothing.
An open generic (``this T``) or ``this object`` declaration applies to any
receiver, but only when no exact/base match exists — C# prefers the
non-generic candidate.
A receiver whose type the corpus never declares (``string``, ``int``, a
third-party type) cannot have its instance members enumerated, so the
instance-wins rule is replaced by two conservative proofs: the member name
is not one a BCL type owns (``ToString``, ``GetValue``, …), and no regular
method anywhere in the corpus has that name. Such an edge is INFERRED 0.75,
one tier below a receiver whose declaration table typed it.
A chained receiver (``v.ToString().Mask()``) has no type at all: typing it
needs the inner call's return type, which for a BCL call the corpus does not
know. The same two proofs apply, with no type-compatibility filter — only a
name that is unique enough to survive them binds (``v.ToString().Mask()``
does; anything named like an ordinary member does not). A capitalized
untyped receiver is a type name (``Convert.ToInt32(x)``), never a value an
extension can apply to, so it is skipped.
"""
def _key(label: str) -> str:
# Case and `_` are part of a C# name (#4415); drop only the `.M()` decoration.
return re.sub(r"\W+", "", str(label))
node_by_id: dict[str, dict] = {n.get("id"): n for n in all_nodes}
contained = {e.get("target") for e in all_edges if e.get("relation") == "contains"}
type_def_nids: dict[str, list[str]] = {}
for nid in contained:
n = node_by_id.get(nid)
if (
n is not None
and _is_cs_file(n.get("source_file"))
and _is_type_like_definition(n)
):
type_def_nids.setdefault(_key(n.get("label", "")), []).append(nid)
resolver = CsharpNameResolver(all_nodes, all_edges)
# Extension declarations, by the name a call site spells.
ext_by_name: dict[str, list[dict]] = {}
method_owner: dict[str, str] = {}
method_index: dict[tuple[str, str], list[str]] = {}
for e in all_edges:
if e.get("relation") != "method":
continue
owner, method_nid = e.get("source"), e.get("target")
mnode = node_by_id.get(method_nid)
if mnode is None or not _is_cs_file(mnode.get("source_file")):
continue
method_owner.setdefault(method_nid, owner)
method_index.setdefault((owner, _key(mnode.get("label", ""))), []).append(method_nid)
meta = mnode.get("metadata") or {}
arity = meta.get("arity")
if not meta.get("extension") or not isinstance(arity, int):
continue
low = meta.get("min_arity")
ext_by_name.setdefault(_key(mnode.get("label", "")), []).append({
"method": method_nid,
"extended": str(meta.get("extended_type") or ""),
"ext_arity": meta.get("extended_type_arity") or 0,
"is_type_param": bool(meta.get("extended_is_type_param")),
"arity": arity,
"low": low if isinstance(low, int) else arity,
"variadic": bool(meta.get("variadic")),
"namespace": str(meta.get("namespace") or ""),
})
if not ext_by_name:
return
# `ext_by_name` covers only extension declarations; this is every *other*
# C# method name, used to prove a name is not an ordinary member (#4828).
ext_method_ids = {d["method"] for decls in ext_by_name.values() for d in decls}
regular_method_names = {
key
for (_owner, key), mids in method_index.items()
for mid in mids
if mid not in ext_method_ids
}
# Supertype graph. A target with no source_file is a placeholder for a type
# the corpus never declares: the chain through it is UNRESOLVED.
supers: dict[str, set[str]] = {}
for e in all_edges:
if e.get("relation") not in ("inherits", "implements"):
continue
if not _is_cs_file(e.get("source_file")):
continue
src, tgt = e.get("source"), e.get("target")
if isinstance(src, str) and isinstance(tgt, str):
supers.setdefault(src, set()).add(tgt)
closure_cache: dict[str, tuple[set[str], bool]] = {}
def _closure(nid: str) -> tuple[set[str], bool]:
cached = closure_cache.get(nid)
if cached is not None:
return cached
out: set[str] = set()
unresolved = False
stack = [nid]
while stack:
cur = stack.pop()
if cur in out:
continue
out.add(cur)
for sup in supers.get(cur, ()):
snode = node_by_id.get(sup)
if snode is None or not snode.get("source_file"):
unresolved = True
continue
stack.append(sup)
closure_cache[nid] = (out, unresolved)
return out, unresolved
def _resolve_type_nid(type_name: str | None, caller_node: dict | None,
src_file: str) -> tuple[str | None, bool]:
"""(definition nid, decisive). ``(None, True)`` means ambiguous or
scoping-known-and-unresolvable; ``(None, False)`` means declared nowhere
in this corpus — the out-of-corpus rung."""
if not type_name:
return None, False
if caller_node is not None:
resolved, decisive = resolver.resolve_type_name(
type_name, caller_node, src_file
)
if resolved:
return resolved, True
if decisive:
return None, True
hits = type_def_nids.get(_key(type_name), [])
if len(hits) == 1:
return hits[0], True
return None, bool(hits)
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
for result in per_file:
for rc in result.get("raw_calls") or []:
if rc.get("lang") != "csharp" or not rc.get("is_member_call"):
continue
caller = rc.get("caller_nid")
callee = rc.get("callee")
argc = rc.get("arity")
receiver = rc.get("receiver")
chain = rc.get("receiver_chain") or []
if not caller or not callee or not isinstance(argc, int):
continue
if receiver == "base":
continue # base.M() is nominal dispatch, never an extension
src_file = str(rc.get("source_file") or "")
caller_node = node_by_id.get(caller)
if caller_node is None:
continue
recv_name = rc.get("receiver_type")
if not recv_name and chain:
if len(chain) > 1:
# `x.F.M()` needs F's declared type, not x's: fail closed
# rather than bind the extension to the root's type.
continue
recv_name = chain[0]
if not recv_name and receiver == "this":
owner = method_owner.get(caller)
owner_node = node_by_id.get(owner) if owner else None
recv_name = (owner_node or {}).get("label")
candidates = ext_by_name.get(_key(callee))
if not candidates:
continue
closure: set[str] = set()
if not recv_name:
# A capitalized untyped receiver is a type named in source
# (`Convert.ToInt32(x)`), not a value an extension applies to.
if receiver and not rc.get("receiver_type") and str(receiver)[:1].isupper():
continue
roc = True
else:
recv_nid, decisive = _resolve_type_nid(recv_name, caller_node, src_file)
if recv_nid is None and decisive:
continue # the receiver's own type is ambiguous here
roc = recv_nid is None # receiver type declared nowhere in the corpus
if not roc:
closure, unresolved = _closure(recv_nid)
if unresolved:
# An out-of-corpus base may declare this name as an instance
# member, which beats any extension. Not provable: no edge.
continue
if any(method_index.get((owner, _key(callee))) for owner in closure):
continue # an instance member (or an override) wins
else:
# Instance members of an undeclared type cannot be enumerated;
# refuse a name a BCL type owns, and a name any regular method
# in the corpus already spells.
if callee in _CSHARP_BCL_MEMBER_NAMES:
continue
if _key(callee) in regular_method_names:
continue
for visible in resolver.visible_namespaces(caller_node, src_file):
at_level = [d for d in candidates if d["namespace"] in visible]
if at_level:
candidates = at_level
break
else:
continue
if not recv_name:
# No type to be compatible with: the guarded name rules above are
# the whole proof, and a tie stays unbound.
applicable = candidates
else:
exact = [
d for d in candidates
if not d["is_type_param"] and _key(d["extended"]) == _key(recv_name)
]
inherited = []
if not roc:
inherited = [
d for d in candidates
if not d["is_type_param"]
and _key(d["extended"]) in {
_key((node_by_id.get(c) or {}).get("label", "")) for c in closure
}
]
applicable = exact or inherited
if not applicable:
applicable = [
d for d in candidates
if d["is_type_param"] or d["extended"].lower() in ("object", "dynamic")
]
if not applicable:
continue
fits = [
d for d in applicable
if d["low"] <= argc and (argc <= d["arity"] - 1 or d["variadic"])
]
if len(fits) != 1:
continue # no declaration accepts this call shape, or ambiguous
method_nid = fits[0]["method"]
if method_nid == caller or (caller, method_nid) in existing_pairs:
continue
existing_pairs.add((caller, method_nid))
all_edges.append({
"source": caller,
"target": method_nid,
"relation": "calls",
"context": "call",
"confidence": "INFERRED",
# 0.85 when the extractor's declaration table typed the receiver;
# 0.75 when the receiver's type is out of corpus (or absent) and
# the binding rests on the BCL/regular-name guards — the discrete
# INFERRED rubric in references/extraction-spec.md.
"confidence_score": 0.75 if roc else 0.85,
"source_file": src_file,
"source_location": rc.get("source_location"),
"weight": 1.0,
})
def _bind_member_field_tables(
per_file: list[dict],
all_nodes: list[dict],
@@ -8743,6 +9188,12 @@ register_language_resolver(
register_language_resolver(
LanguageResolver("csharp_member_calls", frozenset({".cs"}), _resolve_csharp_member_calls)
)
# C# extension-method calls (#4828): `recv.Ext()` where Ext is a `this`-parameter
# method on a static class. Runs after the nominal pass so an instance member has
# already won, and adds only the calls that pass could not bind.
register_language_resolver(
LanguageResolver("csharp_extension_calls", frozenset({".cs"}), _resolve_csharp_extension_calls)
)
register_language_resolver(
LanguageResolver("java_member_calls", frozenset({".java"}), _resolve_java_member_calls)
)
@@ -10527,6 +10978,7 @@ def extract(
max_workers: int | None = None,
resolution_context_nodes: list[dict] | None = None,
resolution_context_edges: list[dict] | None = None,
release_parse_memo: bool = False,
) -> dict:
"""Extract AST nodes and edges from a list of code files.
@@ -10566,6 +11018,9 @@ def extract(
Read-only, same contract as
resolution_context_nodes: they widen the resolvers' view but only
fresh results are appended to the returned nodes/edges.
release_parse_memo: clear the Python parse memo once both resolution
passes are done. One-shot callers (`graphify extract`) set it to
cut peak RAM; long-lived callers keep the memo for the next run.
"""
paths = [Path(p) for p in paths]
if resolution_context_nodes:
@@ -11283,6 +11738,10 @@ def extract(
_new = _remapped(rc.get("caller_nid"), rc.get("source_file"))
if _new is not None:
rc["caller_nid"] = _new
if rc.get("evidence_owner"):
_new_eo = _remapped(rc.get("evidence_owner"), rc.get("source_file"))
if _new_eo is not None:
rc["evidence_owner"] = _new_eo
# swift_extensions[].nid is the same kind of id carrier as caller_nid
# above (cache.py remaps both), consumed by _merge_swift_extensions far
# below. Left stale it matches no node, so whether the extension merge
@@ -11364,6 +11823,9 @@ def extract(
cn = rc.get("caller_nid")
if cn in sym_remap:
rc["caller_nid"] = sym_remap[cn]
eo = rc.get("evidence_owner")
if eo in sym_remap:
rc["evidence_owner"] = sym_remap[eo]
# Same for swift_extensions[].nid (see the id_remap pass above).
for result in per_file:
for ext in result.get("swift_extensions", []) or []:
@@ -11569,6 +12031,9 @@ def extract(
except Exception as exc:
import logging
logging.getLogger(__name__).warning("Cross-file import resolution failed, skipping: %s", exc)
if release_parse_memo:
# Both Python resolution passes are done; the memo pins every tree.
_parse_python_tree_cached.cache_clear()
# An incremental build re-extracts only the changed files, so the rewire also
# needs the unchanged ones as candidates, or it resolves less than a full build.
_fresh_ids = {n.get("id") for n in all_nodes}
+28
View File
@@ -422,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, []):
+145 -30
View File
@@ -207,10 +207,22 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
variadic = extension = False
# A primary constructor's parameter list is an unnamed child of its type
# declaration, so the caller hands it over; the type's own type parameters
# are not the constructor's.
# are not the constructor's (#5054).
primary = params is not None
if params is None:
params = node.child_by_field_name("parameters")
# The method's own type parameters, so `this T` can be told apart from a
# method on a real class that happens to be named T (#4828).
type_param_nodes = [
p for c in node.children if c.type == "type_parameter_list"
for p in c.children if p.type in ("type_parameter", "identifier")
]
type_param_names = {
"".join(_read_text(p, source).split()) for p in type_param_nodes
}
extended_type: str | None = None
extended_arity = 0
extended_is_type_param = False
children = params.children if params is not None else []
for i, c in enumerate(children):
if c.type == "parameter":
@@ -223,6 +235,23 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
arity += 1
if "this" in mods and arity == 1:
extension = True
# The extended type is the join key an extension call site
# needs; record it here, where the declaration is still at
# hand, instead of re-reading the parameter text downstream
# (#4828). `_read_csharp_type_name` already strips the
# namespace qualifier and the generic arguments, so this is
# the same simple name a receiver is stamped with.
ext_info = _read_csharp_type_name(type_node, source)
if ext_info and ext_info[0]:
extended_type = ext_info[0]
extended_arity = sum(
1 for ch in (type_node.children if type_node is not None else [])
if ch.type == "type_argument_list"
for a in ch.children if a.is_named
)
extended_is_type_param = bool(
extended_type and extended_type in type_param_names
)
if not any(x.type == "=" for x in c.children):
required += 1
elif c.type == "params":
@@ -230,10 +259,9 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
parts.append("params " + ("".join(_read_text(type_node, source).split()) if type_node is not None else ""))
arity += 1
variadic = True
type_params = 0 if primary else sum(
1 for c in node.children if c.type == "type_parameter_list"
for _p in c.children if _p.type in ("type_parameter", "identifier")
)
# A primary constructor contributes no type parameters of its own (#5054);
# otherwise count the method's own type parameters (#4828).
type_params = 0 if primary else len(type_param_nodes)
signature = ",".join(parts)
if type_params:
signature = f"`{type_params}:{signature}"
@@ -244,6 +272,16 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
meta["min_arity"] = min_arity
if variadic:
meta["variadic"] = True
if extension:
# Call-side facts: a member-call resolver can index declarations by
# `extended_type` and bind `recv.M(args)` against `[min_arity, arity]`
# (#4828). Persisted on the node so a merged/sharded build keeps them.
meta["extension"] = True
if extended_type:
meta["extended_type"] = extended_type
meta["extended_type_arity"] = extended_arity
if extended_is_type_param:
meta["extended_is_type_param"] = True
return signature, meta
@@ -3287,9 +3325,66 @@ def _cpp_qualified_name(node, name: str, source: bytes) -> str:
return "::".join([*reversed(parents), name])
def _cpp_local_binding_ranges(body, source: bytes) -> dict[str, list[tuple[int, int]]]:
def _cpp_declared_receiver_type(node, declarator, source: bytes) -> str:
"""Keep qualification and pointer shape; unsupported declarations stay unknown."""
type_node = node.child_by_field_name("type")
if type_node is None or type_node.type not in {
"type_identifier", "qualified_identifier", "template_type",
}:
return ""
name = _read_text(type_node, source)
while declarator is not None and declarator.type not in {"identifier", "field_identifier"}:
if declarator.type == "pointer_declarator":
name += "*"
elif declarator.type not in {"reference_declarator", "init_declarator"}:
return ""
inner = declarator.child_by_field_name("declarator")
if inner is None and declarator.type == "reference_declarator":
inner = next((c for c in declarator.named_children if c.type != "type_qualifier"), None)
declarator = inner
return name if declarator is not None else ""
def _cpp_receiver_chain(node, source: bytes) -> list[list[str]]:
"""Pairs of receiver/member names and their following access operators."""
members, operators = [], []
while node is not None:
if node.type == "parenthesized_expression" and len(node.named_children) == 1:
node = node.named_children[0]
elif node.type == "field_expression":
field = node.child_by_field_name("field")
operator = node.child_by_field_name("operator")
if field is None or field.type != "field_identifier" or operator is None:
return []
members.append(_read_text(field, source))
operators.append(_read_text(operator, source))
node = node.child_by_field_name("argument")
elif node.type in {"identifier", "this"}:
members.append(_read_text(node, source))
return [list(pair) for pair in zip(reversed(members[1:]), reversed(operators))]
else:
return []
return []
def _cpp_class_fields(node, source: bytes) -> dict[str, str]:
fields: dict[str, str] = {}
body = node.child_by_field_name("body")
if body is not None:
for field in body.named_children:
if field.type != "field_declaration":
continue
for declarator in field.children_by_field_name("declarator"):
name = _cpp_declarator_name(declarator, source)
if name:
value = _cpp_declared_receiver_type(field, declarator, source)
fields[name] = value if fields.get(name, value) == value else ""
return fields
def _cpp_local_binding_ranges(body, source: bytes) -> dict[str, list[tuple[int, int, str, str]]]:
"""Lexical lifetimes of named C++ locals/parameters, not corpus callees."""
ranges: dict[str, list[tuple[int, int]]] = {}
ranges: dict[str, list[tuple[int, int, str, str]]] = {}
scopes = {"compound_statement", "for_statement", "for_range_loop", "if_statement",
"switch_statement", "catch_clause", "function_definition", "lambda_expression"}
stack = [body]
@@ -3302,15 +3397,22 @@ def _cpp_local_binding_ranges(body, source: bytes) -> dict[str, list[tuple[int,
node = stack.pop()
if node.type in {"class_specifier", "struct_specifier", "function_definition"}:
continue
if node.type in {"declaration", "parameter_declaration", "optional_parameter_declaration"}:
if node.type in {"declaration", "parameter_declaration", "optional_parameter_declaration",
"lambda_capture_initializer"}:
scope = node.parent
while scope is not None and scope.type not in scopes:
scope = scope.parent
if scope is not None:
for declarator in node.children_by_field_name("declarator"):
declarators = node.children_by_field_name(
"left" if node.type == "lambda_capture_initializer" else "declarator")
for declarator in declarators:
name = _cpp_declarator_name(declarator, source)
if name:
ranges.setdefault(name, []).append((declarator.start_byte, scope.end_byte))
ranges.setdefault(name, []).append((
declarator.start_byte, scope.end_byte,
_cpp_declared_receiver_type(node, declarator, source),
_cpp_qualified_name(node, "", source).rstrip(":"),
))
stack.extend(node.named_children)
return ranges
@@ -3406,15 +3508,18 @@ def _swift_local_var_types(body_node, source: bytes, table: dict[str, str],
def _csharp_receiver_type_name(type_node, source: bytes) -> str | None:
"""Resolve a C# declared type to a receiver-typable class name, or None.
A genuine C# class name is Pascal-cased; predefined primitives
(int/bool/string) and ``dynamic`` never own a resolvable method definition
here, and ``var`` (``implicit_type``) carries no name at all.
Predefined primitives (``int``/``bool``/``string``) and ``dynamic`` own no
definition *inside this corpus*, so an instance lookup on them never binds.
They are still returned: an extension method (``this string``) dispatches on
exactly that type name, and dropping the name made every such call
untypeable before it reached the extension pass (#4828). ``var``
(``implicit_type``) still carries no name at all.
"""
info = _read_csharp_type_name(type_node, source)
if not info:
return None
name = info[0]
return name if name and name[:1].isupper() else None
return name or None
_CSHARP_LOOP_SEQUENCES = frozenset({
@@ -4245,6 +4350,8 @@ def _require_imports_js(node, source: bytes, importer_nid: str, stem: str, edges
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
"_require_target_file": str(resolved_path),
"_require_imported_name": sym,
})
return found
@@ -6996,6 +7103,9 @@ def _extract_generic(
cpp_qualified_names[class_nid] = (
qualified if cpp_qualified_names.get(class_nid, qualified) == qualified else ""
)
if node.child_by_field_name("body") is not None:
class_node = next(n for n in nodes if n["id"] == class_nid)
class_node["_cpp_fields"] = _cpp_class_fields(node, source)
# A nested class/object/trait is contained by its ENCLOSING type, not
# the file (#2040). parent_class_nid is threaded down the walk for
# every language and is always a real class-like node (never a
@@ -10212,28 +10322,29 @@ def _extract_generic(
obj.child_by_field_name("name"), source)
elif config.ts_module == "tree_sitter_cpp":
# C++: function field, then field_expression/qualified_identifier
cpp_chain = []
cpp_binding = None
func_node = node.child_by_field_name(config.call_function_field) if config.call_function_field else None
if func_node:
if func_node.type == "identifier":
callee_name = _read_text(func_node, source)
if any(start <= node.start_byte < end for start, end in
if any(start <= node.start_byte < end for start, end, *_ in
cpp_local_bindings.get(caller_nid, {}).get(callee_name, ())):
callee_name = None
elif func_node.type == "field_expression":
# `f.bar()` / `f->bar()` / `this->bar()`: receiver is the
# `argument` (object) field, callee is the `field` (#1547).
# Capture a simple-identifier (or `this`) receiver so the
# cross-file pass can resolve it through the file's type
# table; chained receivers (`a.b.method()`) are left to bail.
# Preserve the full chain for class-scoped cross-file lookup.
is_member_call = True
name = func_node.child_by_field_name("field")
if name:
callee_name = _read_text(name, source)
obj = func_node.child_by_field_name("argument")
if obj is not None and obj.type == "identifier":
member_receiver = _read_text(obj, source)
elif obj is not None and obj.type == "this":
member_receiver = "this"
cpp_chain = _cpp_receiver_chain(func_node, source)
if cpp_chain:
member_receiver = cpp_chain[0][0]
bindings = [b for b in cpp_local_bindings.get(caller_nid, {}).get(
member_receiver, ()) if b[0] <= node.start_byte < b[1]]
cpp_binding = max(bindings, key=lambda b: b[0]) if bindings else None
elif func_node.type == "qualified_identifier":
# `Foo::bar()`: the scope (`Foo`) is the receiver type named
# explicitly in source (EXTRACTED), the name is the callee.
@@ -10499,16 +10610,15 @@ def _extract_generic(
# name must not pick whichever `m` this file declares: through
# `Base* b`, `b->draw()` bound to the file's `Derived::draw`.
# Deferring sends it to _resolve_cpp_member_calls, which types x
# from the file's local/parameter/field table and bails when it
# can't. An untyped receiver and `this->m()` keep the in-file
# binding they had.
# from lexical bindings and class fields. Chains must defer even
# when their root has no known type; bare-name matching is unsafe.
_cpp_member_defer = (
config.ts_module == "tree_sitter_cpp"
and is_member_call
and not is_scoped_call
and member_receiver is not None
and member_receiver != "this"
and member_receiver in type_table
and func_node is not None and func_node.type == "field_expression"
and (len(cpp_chain) != 1 or member_receiver in type_table
or (cpp_binding is not None and bool(cpp_binding[2])))
)
if _python_defer or _java_defer or _csharp_defer or _js_member_defer or _cpp_member_defer or (_builtin_member_call and not php_builtin_self_call) or _lua_member_defer or is_scoped_call or (
is_member_call
@@ -10724,6 +10834,11 @@ def _extract_generic(
# suffix sets, so a source_file suffix alone can't separate them.
if config.ts_module == "tree_sitter_cpp":
rc_entry["lang"] = "cpp"
if func_node is not None and func_node.type == "field_expression":
rc_entry["cpp_receiver_chain"] = cpp_chain
if cpp_binding is not None:
rc_entry["cpp_receiver_type"] = cpp_binding[2]
rc_entry["cpp_receiver_scope"] = cpp_binding[3]
# PHP: separate a scoped class call (`Helper::m()`, source-
# qualified) from an instance member call (`$g->m()`), whose
# receiver is a variable the resolver must type through the
@@ -11111,7 +11226,7 @@ def _extract_generic(
# every function body so the cross-file member-call pass can type a receiver
# (#1547). File-scoped (not per-body): a later body's `Foo f;` doesn't clobber
# an earlier binding (`var not in table`), keeping resolution conservative.
cpp_local_bindings: dict[str, dict[str, list[tuple[int, int]]]] = {}
cpp_local_bindings: dict[str, dict[str, list[tuple[int, int, str, str]]]] = {}
if config.ts_module == "tree_sitter_cpp":
# Each function's table first: a local shadows a parameter there. The
# file table is shared by every function, so a name typed differently in
+167 -45
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
@@ -309,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``.
@@ -353,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
@@ -386,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:
@@ -403,15 +425,22 @@ 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 m:
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:
# ``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)]
@@ -420,9 +449,10 @@ def _code_span_mention(span: str) -> "tuple[str | None, list[str]] | None":
# that is only a namespace root (``App\``) is dropped: it names no symbol.
m = _MD_NS_MENTION_RE.match(text)
if m:
body = text[:-2] if text.endswith("()") else text
is_call = text.endswith("()")
body = text[:-2] if is_call else text
parts = re.split(r"::|\\", body)
if _MD_NS_NON_SYMBOL_RE.match(parts[-1]):
if not is_call and body.endswith("::" + parts[-1]) and _MD_NS_NON_SYMBOL_RE.match(parts[-1]):
return None
return None, parts
return None
@@ -452,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
@@ -465,9 +497,12 @@ 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 (``` ... ``` or ~~~ ... ~~~, closed by a run of the
same character at least as long, per CommonMark) are skipped during
@@ -506,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(),
@@ -550,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
@@ -606,22 +698,25 @@ def extract_markdown(path: Path) -> dict:
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.
@@ -644,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)
+27
View File
@@ -1213,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":
@@ -1281,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}
@@ -1634,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.
+20 -3
View File
@@ -32,9 +32,11 @@ 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({
@@ -248,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)
+47 -6
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,
)
@@ -364,6 +365,34 @@ def _openai_max_tokens_kwarg(backend: str, max_tokens: int) -> dict[str, int]:
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."
@@ -1557,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
@@ -1582,7 +1612,8 @@ 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": [
@@ -2240,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
@@ -2575,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:
@@ -3329,7 +3368,9 @@ 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}],
+260 -26
View File
@@ -33,9 +33,13 @@ to the code node that defines it:
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 document also names the class that owns it (#4609).
The trailing ``()``, a dotted form, or a class/function label carries enough
evidence on its own.
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
@@ -49,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"})
@@ -67,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", ""))
@@ -96,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.
@@ -147,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)
@@ -244,19 +372,105 @@ def resolve_markdown_mentions(
return parent
return None
#: Targets already cited by each document, used as evidence in pass 2b.
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:
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
doc = _posix(str(rc.get("source_file", "")))
if (caller, target) in existing:
# The edge is already in the graph, but this document still CITES that
# target, so it stays on record as owner evidence for a later method
# mention in the same document (#4609 review finding).
cited_targets.setdefault(doc, set()).add(target)
# Retain target as section-scoped citation evidence (#4609, #4804).
cited_targets.setdefault(caller, set()).add(target)
return
existing.add((caller, target))
all_edges.append({
@@ -270,12 +484,9 @@ def resolve_markdown_mentions(
"source_location": rc.get("source_location"),
"weight": 1.0,
})
cited_targets.setdefault(doc, set()).add(target)
cited_targets.setdefault(caller, set()).add(target)
# Pass 1: explicit evidence resolves on its own — a cited path, a dotted
# qualifier chain, or a trailing (). Record those targets per document.
# Pass 2 handles the bare, parenthesis-less, single-name spans, where the
# word alone (`redis`, `data`, `message`) is indistinguishable from prose.
# Pass 1: explicit evidence resolves directly (path, dotted chain, or trailing ()).
bare: list[dict] = []
for rc in mentions:
caller = str(rc.get("caller_nid", ""))
@@ -289,22 +500,45 @@ def resolve_markdown_mentions(
else:
bare.append(rc)
# Pass 2a: bare mentions that do not name a method. A class or free function
# label is specific enough to keep matching, and the class a later method
# mention needs must be on record before pass 2b runs.
# 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 not None and _method_owner(target) is not None:
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 2b: a bare method name (#4609) is only evidence when the same
# document already cites the class that owns it. `redis` the server does not
# link to `Cache.redis` unless the document names `Cache`;
# `successWithWarnings` survives because `HandlerResult` is cited next to it.
for rc, target, confidence, score in method_mentions:
doc = _posix(str(rc.get("source_file", "")))
if _method_owner(target) in cited_targets.get(doc, ()):
# 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)
+137 -1
View File
@@ -351,6 +351,87 @@ _SOURCE_MATCH_BONUS = 0.5
_RATIONALE_MATCH_BONUS = 0.75
_ATTRIBUTE_MATCH_BONUS = 0.75
# A label may carry a leading qualifier that the query never repeats: a SQL
# function is `public.sweep_widget_state()`, a namespaced symbol is
# `fmt.Println`. The full-query tier below only fires on equal/prefix, so the
# qualifier alone defeats it and the per-token tiers take over — where an
# unrelated node whose *whole* label is one of the query's tokens outranks the
# intended one (#5080). Keep the bonus below the exact tier (the query is not
# the label) but well above the per-token exact tier it has to beat, and scale
# it by how small the qualifier is so `public.f()` (one token) is trusted more
# than `a.b.c.d.f()`.
_QUALIFIED_MATCH_BONUS = 500.0
_QUALIFIED_MAX_TOKENS = 4
# Separators that start a new segment of a qualified name.
_QUALIFIER_SEPARATORS = r"\.{1,}|::|/|\\|:|@"
# `sweep_widget_state()` and `sweep widget state` are the same name; strip these
# before comparing. `_search_tokens` already drops them from the inside.
_NAME_EDGES = "()[]{}"
_CAMEL_WORD_RE = re.compile(r"[A-Z]+(?![a-z])|[A-Z][a-z0-9]*|[a-z0-9]+")
# Only a separator or a lower->upper transition below the first character can
# leave a qualifier behind; plain `snake_case_name` cannot, so reject it early.
_QUALIFIER_MAYBE_RE = re.compile(r"[.::/\\:@]|[a-z0-9][A-Z]")
# File-extension segments (`.py`, `.md`) are not qualifiers: the tail of
# `lib/foo/bar.py` is `bar`, not `py`. Numbers are not names either (`3.14`).
_FILE_SUFFIX_RE = re.compile(r"^(?:py|pyi|js|jsx|ts|tsx|mjs|cjs|go|rs|java|kt|kts|c|h|cc|cpp|hpp|cs|rb|php|swift|scala|lua|sh|bash|sql|md|rst|txt|ya?ml|toml|json|ini|cfg|html?|css|scss|vue|svelte|ex|exs|erl|hs|ml|clj|dart|proto|graphql)$")
def _is_name_segment(segment: str) -> bool:
"""True if `segment` names something rather than being an extension or a number."""
return bool(segment) and not segment.isdigit() and not _FILE_SUFFIX_RE.match(segment)
def _qualified_tail(norm_label: str) -> tuple[int, str] | None:
"""Split a label into `(qualifier_token_count, tail_key)`, or `None` if unqualified.
`public.sweep_widget_state()` -> `(1, "sweep widget state")`: the tail is the
part a query would actually name. Segments are split on punctuation, so
`fmt.Println` -> `(1, "println")` and `App\\Http\\handle` -> `(2, "handle")`.
The CamelCase fallback below only fires on a cased label (an inner lower->upper
transition); the scorer's callers pass the already-lowercased `norm_label`, so
in practice only the separator path runs — the fallback is defensive.
"""
label = (norm_label or "").strip()
# Cheap reject first: without a separator and without an inner capital there
# is nothing to split. This is the common case on a whole-graph pass, and it
# keeps the regex work off every plain identifier.
if not _QUALIFIER_MAYBE_RE.search(label):
return None
parts = [p for p in re.split(_QUALIFIER_SEPARATORS, label) if p]
# Drop trailing non-name segments (`lib/foo/bar.py` -> `lib`, `foo`, `bar`).
while parts and not _is_name_segment(parts[-1]):
parts.pop()
if not parts:
return None
tail = parts[-1]
if len(parts) > 1:
head_tokens = len(_search_tokens(" ".join(parts[:-1])))
if head_tokens:
return head_tokens, _name_key(tail)
# No separator: only a CamelCase qualifier can still leave one. Require at
# least two words and an inner capital, so all-lower snake_case names are
# left alone (they are already matched as one token run).
words = _CAMEL_WORD_RE.findall(tail)
if len(words) < 2 or not any(w[:1].isupper() for w in words[1:]):
return None
head_tokens = len(_search_tokens(" ".join(words[:-1])))
if not head_tokens:
return None
return head_tokens, _name_key(words[-1])
def _name_key(text: str) -> str:
"""Token-joined form of an already-normalized name, for comparing two names.
`norm_label` has been lowercased and had its diacritics stripped already, so
splitting on non-alphanumerics is all `_search_tokens` would add here — and
skipping the per-call Unicode normalization matters, this runs on the whole
graph.
"""
stripped = str(text or "").strip(_NAME_EDGES + " ").lower()
return " ".join(re.findall(r"[^\W_]+", stripped))
def _flatten_attr_text(val, parts: list[str]) -> None:
if isinstance(val, dict):
@@ -712,6 +793,17 @@ def _score_query(
or label_tokens.startswith(joined)
):
score += _PREFIX_MATCH_BONUS * 10 * joined_w
else:
# Qualified name: the label is `<qualifier>.<rest>` (or a
# CamelCase variant) and the query names the rest. Ranking
# below the exact tier — the label is not what was typed — but
# above what the per-token tiers can add up to for a node whose
# whole label is one query token (#5080).
qualified = _qualified_tail(norm_label)
if qualified is not None and qualified[0] <= _QUALIFIED_MAX_TOKENS:
qualifier_tokens, tail_key = qualified
if tail_key and tail_key == joined:
score += _QUALIFIED_MATCH_BONUS * joined_w / qualifier_tokens
# Term coverage (#1602): scale the per-term exact/prefix tiers by the
# squared fraction of query terms the node's LABEL matches, so a lone
# generic word that happens to equal a short label (query term "home"
@@ -2256,6 +2348,11 @@ def _resolve_path_endpoint(
symbols of one file were split by graph order behind a score-tie warning,
and `path::symbol` cannot separate them — only the node id can.
A name made of words the graph doesn't know is a miss, not the top of a
weak ranking (#5079): `explain` already answers "No node matching" for it,
and routing from the closest-sounding label instead prints a path through
a symbol nobody asked about.
Returns ``(node_id, scored, None)``, where ``scored`` is empty unless the
score fallback picked the node; ``(None, [], message)`` when ambiguous; and
``(None, [], None)`` when nothing matches.
@@ -2285,12 +2382,51 @@ def _resolve_path_endpoint(
no_member = _no_member_match_message(G, query)
if no_member:
return None, [], no_member
scored = _score_nodes(G, [t.lower() for t in query.split()])
terms = [t.lower() for t in query.split()]
scored = _score_nodes(G, terms)
if not scored:
return None, [], None
if not _query_uses_known_words(G, terms):
return None, [], None
return _pick_scored_endpoint(G, scored, query), scored, None
def _query_uses_known_words(G: nx.Graph, terms: list[str]) -> bool:
"""Whether every word of the query occurs in some node's name.
Scoring ranks by token overlap, so a made-up name still finds candidates:
`zzqqxx_no_such_symbol_9137` matches `no_such_symbol_helper()` on `no`,
`symbol` and `helper`, and the route through that symbol prints as if it
were the one asked for (#5079). The scored fallback is only honest when
the query is at least partly in the graph's vocabulary, so each token has
to occur somewhere — then the query shares a word with what it routes
through (`Rejection judge` -> `Rejection Summary`, its tokens once said
whole). A token that appears nowhere (`zzqqxx`, `9137`) means the name the
caller asked for isn't in the graph, which is what `explain` reports too.
Looser than `explain`'s resolution on purpose: there any substring hit is
a "near miss" worth refusing with suggestions, but `path` answers with a
route rather than a name, and a caller still typing (`draft-generator` for
`draft-generator.ts`) needs the score fallback's ranking.
One pass per token, each stopping at the first node that carries it; the
vocabulary is `_search_tokens` pieces of labels and ids, the same split the
scorer uses.
"""
tokens = list(dict.fromkeys(tok for t in terms for tok in _search_tokens(t)))
if not tokens:
return False
# A query is usually rejected on its first unknown word (~a fifth of a score
# pass on a 60k-node graph), and nothing is memoised on a shared graph.
for token in tokens:
for nid, d in G.nodes(data=True):
if token in _search_tokens(nid) or token in _search_tokens(d.get("label") or ""):
break
else:
return False
return True
def _path_search_graph(G: nx.Graph, undirected: bool) -> nx.Graph:
"""The sorted, materialized graph `_shortest_path_text` searches.
@@ -1,6 +1,6 @@
# graphify reference: extraction subagent prompt (compact)
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
@@ -1,6 +1,6 @@
# graphify reference: extraction subagent prompt (compact)
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
@@ -1,6 +1,6 @@
# graphify reference: extraction subagent prompt (compact)
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
+1 -1
View File
@@ -49,7 +49,7 @@ DEFAULT_MAX_CHILDREN = 200
def _common_root(paths: List[str]) -> str:
if not paths:
return ""
parts = [Path(p).parts for p in paths if p]
parts = [Path(p).parent.parts for p in paths if p]
if not parts:
return ""
common = parts[0]
+7 -2
View File
@@ -45,7 +45,9 @@ def validate_extraction(data: dict) -> list[str]:
)
else:
node_ids.add(node["id"])
if "file_type" in node and node["file_type"] not in VALID_FILE_TYPES:
if "file_type" in node and (
not isinstance(node["file_type"], str) or node["file_type"] not in VALID_FILE_TYPES
):
errors.append(
f"Node {i} (id={node.get('id', '?')!r}) has invalid file_type "
f"'{node['file_type']}' - must be one of {sorted(VALID_FILE_TYPES)}"
@@ -65,7 +67,10 @@ def validate_extraction(data: dict) -> list[str]:
for field in REQUIRED_EDGE_FIELDS:
if field not in edge:
errors.append(f"Edge {i} missing required field '{field}'")
if "confidence" in edge and edge["confidence"] not in VALID_CONFIDENCES:
if "confidence" in edge and (
not isinstance(edge["confidence"], str)
or edge["confidence"] not in VALID_CONFIDENCES
):
errors.append(
f"Edge {i} has invalid confidence '{edge['confidence']}' "
f"- must be one of {sorted(VALID_CONFIDENCES)}"
+135 -11
View File
@@ -487,6 +487,7 @@ from graphify.detect import (
IMAGE_EXTENSIONS,
_load_graphifyignore,
_is_ignored,
ignored_predicate,
)
from graphify.rcfile import (
RC_FILENAME,
@@ -931,10 +932,24 @@ def _reconcile_markdown_links(
and not _is_file_node(target)
)
def _is_code_file_citation(edge: dict) -> bool:
"""A page -> source-file link citation minted by markdown resolution (#4804)."""
if edge.get("relation") != "references" or edge.get("target_file"):
return False
target = nodes_by_id.get(edge.get("target"))
source = nodes_by_id.get(edge.get("source"))
return (
target is not None
and target.get("file_type") == "code"
and _is_file_node(target)
and source is not None
and source.get("file_type") == "document"
)
def _keep_edge(edge: dict) -> bool:
if not (_is_ast_tier(edge) and edge.get("relation") == "references"):
return True
if _is_code_span_mention(edge):
if _is_code_span_mention(edge) or _is_code_file_citation(edge):
return True
owner = source_paths.normalize(edge.get("source_file"))
if owner not in parsed_sources:
@@ -3581,7 +3596,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
try:
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from watchdog.events import FileSystemEventHandler
from watchdog.events import FileCreatedEvent, FileSystemEventHandler
except ImportError as e:
raise ImportError("watchdog not installed. Run: pip install watchdog") from e
@@ -3596,22 +3611,59 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
# without this short-circuit a busy volume can saturate a CPU core
# discarding events one extension at a time. (gh-928)
watch_root_for_ignore = watch_path.resolve()
ignore_gitignore = _read_build_gitignore(watch_path / _GRAPHIFY_OUT)
ignore_patterns = _load_graphifyignore(
watch_root_for_ignore,
gitignore=_read_build_gitignore(watch_path / _GRAPHIFY_OUT),
gitignore=ignore_gitignore,
)
ignored = ignored_predicate(watch_root_for_ignore, gitignore=ignore_gitignore)
# Observer and dispatch threads need the same root-specific snapshot.
root_config_path = watch_root_for_ignore / RC_FILENAME
override_snapshot: dict[str, str] = activate_language_overrides(watch_root_for_ignore)
config_changed = False
# Only Linux prunes the recursive watch tree. macOS and Windows keep the
# recursive schedule, so their handler must not require a `watched` entry.
manual = sys.platform.startswith("linux")
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
nonlocal last_trigger, pending, override_snapshot, config_changed
if event.is_directory or _is_read_only_event(event):
nonlocal ignore_patterns, ignored
if event.is_directory:
if not manual or _is_read_only_event(event):
return
path = Path(os.fsdecode(event.src_path)).resolve()
if path.parent not in watched:
return
if event.event_type == "created":
add_tree(path, emit_existing=True)
elif event.event_type == "deleted":
remove_tree(path)
elif event.event_type == "moved":
remove_tree(path)
dest = Path(os.fsdecode(event.dest_path)).resolve()
if under_root(dest):
add_tree(dest, emit_existing=True)
return
if _is_read_only_event(event):
return
path = Path(os.fsdecode(event.src_path))
if manual and (
path.parent not in watched or not path.parent.exists()
):
return
if path.name in {".graphifyignore", ".gitignore"}:
ignore_patterns = _load_graphifyignore(
watch_root_for_ignore, gitignore=ignore_gitignore
)
ignored = ignored_predicate(
watch_root_for_ignore, gitignore=ignore_gitignore
)
if manual:
remove_tree(watch_root_for_ignore)
add_tree(watch_root_for_ignore, emit_existing=False)
return
# Atomic replacement reports the new root config in dest_path.
dest_raw = getattr(event, "dest_path", None)
dest_path = Path(os.fsdecode(dest_raw)) if dest_raw else None
@@ -3644,13 +3696,85 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
changed.add(path)
handler = Handler()
# Use polling observer on macOS — FSEvents can miss rapid saves in some editors
observer = PollingObserver() if sys.platform == "darwin" else Observer()
# Ask the kernel only for events the handler treats as changes. Without
# this filter the recursive setup walk floods the inotify queue with
# IN_OPEN/IN_CLOSE_NOWRITE, overflows it around 4,000 directories, and
# watchdog 7 then re-walks the tree forever (#5033).
if _observer_accepts_event_filter(observer):
observer = (
Observer()
if manual
else (PollingObserver() if sys.platform == "darwin" else Observer())
)
watched: dict[Path, object] = {}
warned_no_filter = False
def under_root(path: Path) -> bool:
try:
path.resolve().relative_to(watch_root_for_ignore)
return True
except (OSError, ValueError):
return False
def schedule_one(path: Path) -> None:
nonlocal warned_no_filter
path = path.resolve()
if path in watched or not under_root(path):
return
if path != watch_root_for_ignore and ignored(path):
return
if path == watch_root_for_ignore / _GRAPHIFY_OUT:
return
kwargs = {"recursive": False}
if _observer_accepts_event_filter(observer):
kwargs["event_filter"] = _watch_event_filter()
elif not warned_no_filter:
warned_no_filter = True
logger.warning(
"watchdog does not declare event_filter; read-only inotify "
"events may overflow the queue and lose changes (#5033)"
)
try:
watched[path] = observer.schedule(handler, str(path), **kwargs)
except OSError as exc:
if exc.errno == errno.ENOSPC:
logger.warning(
"inotify watch limit reached while watching %s; "
"changes below it will be missed", path
)
return
raise
def remove_tree(path: Path) -> None:
path = path.resolve()
prefix = str(path) + os.sep
for key in [p for p in watched if str(p) == str(path) or str(p).startswith(prefix)]:
watch = watched.pop(key)
try:
observer.unschedule(watch)
except Exception:
pass
def add_tree(path: Path, *, emit_existing: bool) -> None:
path = path.resolve()
stack = [path]
while stack:
current = stack.pop()
if not under_root(current):
continue
if current != watch_root_for_ignore and ignored(current):
continue
if current == watch_root_for_ignore / _GRAPHIFY_OUT:
continue
schedule_one(current)
try:
entries = list(os.scandir(current))
except OSError:
continue
for entry in entries:
if entry.is_dir(follow_symlinks=False):
stack.append(Path(entry.path))
elif emit_existing and entry.is_file(follow_symlinks=False):
handler.on_any_event(FileCreatedEvent(entry.path))
if manual:
add_tree(watch_root_for_ignore, emit_existing=False)
elif _observer_accepts_event_filter(observer):
observer.schedule(
handler,
str(watch_root_for_ignore),
+21 -6
View File
@@ -383,16 +383,22 @@ def to_wiki(
_slug_limit = stem_filename_budget(out, reserve=_SLUG_SUFFIX_RESERVE)
def _unique_slug(base: str) -> str:
# Fold case in the collision check: two labels differing only by case
# (e.g. "Parser" vs "parser") resolve to one path on case-insensitive
# Fold with casefold(), the SAME rule the orphan sweep below indexes
# produced filenames with - not lower(). Two labels differing only by
# case (e.g. "Parser" vs "parser") resolve to one path on case-insensitive
# filesystems (macOS/APFS, Windows/NTFS), so they must dedup against each
# other while still emitting the original-case filename.
# other while still emitting the original-case filename. lower() is not
# enough for Unicode: "Straße".lower() != "STRASSE".lower(), yet both
# casefold to "strasse", so both slugs were allocated and the sweep's
# folded map kept one and unlinked the other current article (#5087).
# Same fold on both sides keeps every produced name distinct here, so a
# name the sweep sees is always one it produced.
slug = base
n = 2
while slug.lower() in used_slugs:
while slug.casefold() in used_slugs:
slug = f"{base}_{n}"
n += 1
used_slugs.add(slug.lower())
used_slugs.add(slug.casefold())
return slug
# First pass: assign every article its slug before rendering any body, so the
@@ -458,8 +464,17 @@ def to_wiki(
# check then saw `"groups.md" not in {"Groups.md"}`, unlinked the file this run
# had just written, and left `index.md` pointing at `Groups.md` with nothing
# behind it (#4508).
produced_by_fold = {name.casefold(): name for name in produced}
#
# _unique_slug dedups on casefold(), so this map is one-to-one. sorted()
# keeps the survivor deterministic (not set-iteration order) if it ever is not.
produced_by_fold = {name.casefold(): name for name in sorted(produced)}
for old_article in out.glob("*.md"):
# Never delete a file this run produced. The fold map is one-to-one only
# because _unique_slug dedups on casefold(); this exact-name check keeps
# that promise even if a future slug rule drifts from the fold rule again
# (#5087: two current Unicode labels, only one fold key, one article lost).
if old_article.name in produced:
continue
wanted = produced_by_fold.get(old_article.name.casefold())
if wanted is None:
old_article.unlink()
+3 -3
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.9.104"
version = "0.9.105"
description = "AI coding assistant skill (Claude Code, CodeBuddy, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Devin CLI, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = "Apache-2.0"
@@ -74,7 +74,7 @@ Issues = "https://github.com/Graphify-Labs/graphify/issues"
mcp = ["mcp>=1,<3", "starlette>=1.3.1,<2", "anyio>=4.14.2"]
neo4j = ["neo4j"]
falkordb = ["falkordb"]
pdf = ["pypdf>=6.19.0", "markdownify"]
pdf = ["pypdf>=6.21.4", "markdownify"]
watch = ["watchdog"]
svg = ["matplotlib", "pillow>=13.0.0; python_version >= '3.11'", "pillow>=12.3.0; python_version < '3.11'", "numpy>=2.0; python_version >= '3.13'"]
leiden = [
@@ -142,7 +142,7 @@ vbnet = ["tree-sitter-vb-dotnet==0.3.0"]
r = ["tree-sitter-language-pack==0.11.0"]
erlang = ["tree-sitter-language-pack==0.11.0"]
solidity = ["tree-sitter-solidity==1.2.13"]
all = ["mcp>=1,<3", "starlette>=1.3.1,<2", "anyio>=4.14.2", "neo4j", "falkordb", "pypdf>=6.19.0", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "graspologic-native>=1.3.1,<2; python_version >= '3.13'", "python-docx", "openpyxl", "psycopg[binary]", "faster-whisper; python_version >= '3.11'", "av>=11,<19; python_version >= '3.11'", "yt-dlp>=2026.7.4", "matplotlib", "pillow>=13.0.0; python_version >= '3.11'", "pillow>=12.3.0; python_version < '3.11'", "numpy>=2.0; python_version >= '3.13'", "openai", "tiktoken", "boto3", "anthropic", "tree-sitter-sql", "jieba; python_version < '3.12'", "jieba-py>=0.46.12,<1; python_version >= '3.12'", "tree-sitter-dm>=0.25,<0.26", "tree-sitter-hcl", "tree-sitter-pascal", "tree-sitter-ocaml", "tree-sitter-commonlisp", "robotframework>=4.0", "tree-sitter-vb-dotnet==0.3.0", "tree-sitter-language-pack==0.11.0", "tree-sitter-solidity==1.2.13"]
all = ["mcp>=1,<3", "starlette>=1.3.1,<2", "anyio>=4.14.2", "neo4j", "falkordb", "pypdf>=6.21.4", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "graspologic-native>=1.3.1,<2; python_version >= '3.13'", "python-docx", "openpyxl", "psycopg[binary]", "faster-whisper; python_version >= '3.11'", "av>=11,<19; python_version >= '3.11'", "yt-dlp>=2026.7.4", "matplotlib", "pillow>=13.0.0; python_version >= '3.11'", "pillow>=12.3.0; python_version < '3.11'", "numpy>=2.0; python_version >= '3.13'", "openai", "tiktoken", "boto3", "anthropic", "tree-sitter-sql", "jieba; python_version < '3.12'", "jieba-py>=0.46.12,<1; python_version >= '3.12'", "tree-sitter-dm>=0.25,<0.26", "tree-sitter-hcl", "tree-sitter-pascal", "tree-sitter-ocaml", "tree-sitter-commonlisp", "robotframework>=4.0", "tree-sitter-vb-dotnet==0.3.0", "tree-sitter-language-pack==0.11.0", "tree-sitter-solidity==1.2.13"]
[project.scripts]
graphify = "graphify.__main__:main"
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,90 @@
"""Splittable documents below character cap can bisect after output truncation (#5072)."""
from pathlib import Path
from unittest.mock import patch
import pytest
import graphify.llm as llm
from graphify.file_slice import (
FileSlice,
is_splittable_text,
read_slice_text,
unit_source_text,
)
@pytest.mark.parametrize("ext", [".md", ".txt", ".rst"])
def test_splittable_document_under_cap_bisects_on_truncation(tmp_path, ext):
"""When a splittable document below _FILE_CHAR_CAP truncates (finish_reason='length'),
adaptive retry should promote the raw Path unit to a full-range FileSlice and bisect it,
completing without being marked partial (#5072).
"""
path = tmp_path / f"dense{ext}"
content = "# Title\n\n" + "".join(f"Paragraph {i} with some content.\n\n" for i in range(40))
path.write_text(content, encoding="utf-8")
text = unit_source_text(path)
assert len(text) < llm._FILE_CHAR_CAP
raw = llm.expand_oversized_files([path], llm._FILE_CHAR_CAP)
assert raw == [path], "File below cap must initially stay a raw Path"
calls = []
def mock_extract(chunk, **kwargs):
calls.append(chunk)
chunk_text = "".join(
read_slice_text(u) if isinstance(u, FileSlice) else unit_source_text(u)
for u in chunk
)
if len(chunk_text) > 700:
return {
"nodes": [{"id": f"node_{len(calls)}", "label": "n", "source_file": str(path)}],
"edges": [],
"hyperedges": [],
"finish_reason": "length",
}
return {
"nodes": [{"id": f"leaf_{len(calls)}", "label": "leaf", "source_file": str(path)}],
"edges": [],
"hyperedges": [],
"finish_reason": "stop",
}
with patch.object(llm, "extract_files_direct", side_effect=mock_extract):
result = llm._extract_with_adaptive_retry(
raw, "kimi", "offline", "offline", path.parent, max_depth=3
)
is_partial = bool(result.get("partial") or result.get("_partial_files"))
assert not is_partial, "Splittable document under cap should bisect and recover from truncation"
assert result["finish_reason"] == "stop"
assert len(calls) >= 3, f"Expected at least 1 root truncated call + bisected slice calls, got {len(calls)}"
for subcall in calls[1:]:
assert isinstance(subcall[0], FileSlice), "Bisected unit must be a FileSlice"
def test_code_file_under_cap_does_not_bisect_on_truncation(tmp_path):
"""Code files must never be sliced or bisected; they remain whole and partial on truncation."""
path = tmp_path / "dense.py"
path.write_text("x = 1\n" * 100, encoding="utf-8")
raw = [path]
calls = []
def mock_extract(chunk, **kwargs):
calls.append(chunk)
return {
"nodes": [{"id": "code_node", "label": "n", "source_file": str(path)}],
"edges": [],
"hyperedges": [],
"finish_reason": "length",
}
with patch.object(llm, "extract_files_direct", side_effect=mock_extract):
result = llm._extract_with_adaptive_retry(
raw, "kimi", "offline", "offline", path.parent, max_depth=3
)
is_partial = bool(result.get("partial") or result.get("_partial_files"))
assert is_partial, "Code file must stay partial when truncated"
assert len(calls) == 1, "Code file must not be bisected"
+17
View File
@@ -59,3 +59,20 @@ def test_class_level_caller_still_works():
g.add_edge("caller", "svc", relation="references")
hits = {h.node_id for h in affected_nodes(g, "svc", depth=2)}
assert "caller" in hits
def test_file_affected_reaches_nested_method_callers():
g = nx.DiGraph()
for nid, label in [
("file_p", "processor.py"),
("proc", "Processor"), ("proc_call", ".call()"),
("runner", "Runner"), ("runner_run", ".run()"),
]:
g.add_node(nid, label=label)
g.add_edge("file_p", "proc", relation="contains")
g.add_edge("proc", "proc_call", relation="method")
g.add_edge("runner", "runner_run", relation="method")
g.add_edge("runner_run", "proc_call", relation="calls")
hits = {h.node_id for h in affected_nodes(g, "file_p", depth=2)}
assert "runner_run" in hits, "caller of method inside class must be reachable from file"
+161 -7
View File
@@ -1,11 +1,13 @@
"""Incremental --update: hyperedge preservation (#1574) and root-less prune (#1571).
"""Incremental --update: hyperedge preservation (#1574, #5081) and root-less prune (#1571).
build_merge backs `graphify --update`. Two regressions covered here:
build_merge backs `graphify --update`. The regressions covered here:
- #1574: it read only nodes+edges from the existing graph.json, never hyperedges,
so every incremental update collapsed the graph's hyperedge set down to just the
re-extracted files'. Now existing hyperedges are carried forward, with
re-extracted files' replaced (by source_file) and deleted files' pruned.
- #1574 / #5081: it read only nodes+edges from the existing graph.json, never
hyperedges, so every incremental update collapsed the graph's hyperedge set
down to just the re-extracted files'. Now existing hyperedges are carried
forward, with re-extracted files' replaced (by source_file) and deleted files'
pruned. The loader also folds the nested ``graph.hyperedges`` slot (#2485),
which node_link_data-only writers emit instead of the top-level key.
- #1571: when a caller omits `root` (the skill's --update runbook does), absolute
prune_sources never relativized to match the stored relative source_file keys, so
deleted files' nodes survived as ghosts. build_merge now infers a fallback root.
@@ -18,7 +20,8 @@ from pathlib import Path
import pytest
from graphify.build import build_merge, _infer_merge_root
from graphify.build import build_merge, merge_raw_extraction, _infer_merge_root
from graphify.export import to_json
def _write_graph(graph_path: Path, nodes, edges, hyperedges) -> None:
@@ -140,6 +143,157 @@ def test_update_still_drops_a_hyperedge_the_new_chunk_re_emits(tmp_path):
assert labels == ["cross-file flow v2", "flow A v2"]
def _seed_full_graph(tmp_path, *, nested_only=False):
"""The #5081 shape: three files, one hyperedge each, plus a cross-file one."""
root = tmp_path / "corpus"
root.mkdir()
graph_path = root / "graphify-out" / "graph.json"
graph_path.parent.mkdir(parents=True)
nodes = [
{"id": f"{f[0]}1", "label": f, "file_type": "document", "source_file": f}
for f in ("a.md", "b.md", "c.md")
]
hyperedges = [
{"id": f"he_{f[0]}", "label": f"flow {f}", "source_file": f, "nodes": [f"{f[0]}1"]}
for f in ("a.md", "b.md", "c.md")
]
hyperedges.append(
{"id": "he_global", "label": "cross-file flow", "nodes": ["a1", "b1", "c1"]}
)
data = {"nodes": nodes, "edges": [], "hyperedges": hyperedges}
if nested_only:
# node_link_data-only writer: hyperedges live in graph attrs only (#2485).
data.pop("hyperedges")
data["graph"] = {"hyperedges": hyperedges}
graph_path.write_text(json.dumps(data), encoding="utf-8")
return root, graph_path
def _update_after_editing_b(graph_path, root):
"""Re-extract b.md semantically, delete c.md — the reporter's --update step."""
new_chunk = {
"nodes": [{"id": "b1", "label": "b.md", "file_type": "document", "source_file": "b.md"}],
"edges": [],
"hyperedges": [
{"id": "he_b_v2", "label": "flow b v2", "source_file": "b.md", "nodes": ["b1"]}
],
}
return build_merge(
[new_chunk],
graph_path,
prune_sources=[str(root / "c.md")],
root=root,
dedup=False,
)
def test_update_keeps_unchanged_hyperedges_in_written_graph_json(tmp_path):
"""#5081 end to end, and the control arm for the nested-slot fix.
A full build wrote one hyperedge per unchanged file plus a cross-file one.
Re-extracting b.md and deleting c.md must leave a.md's, the cross-file
one, and b.md's fresh version — and write them to BOTH persistence slots.
The top-level shape already passes on v8 since #1574; this pins it (and the
dual-slot write) so the reported flow cannot regress.
"""
root, graph_path = _seed_full_graph(tmp_path)
G = _update_after_editing_b(graph_path, root)
assert to_json(G, {}, str(graph_path), force=True) is True
data = json.loads(graph_path.read_text(encoding="utf-8"))
ids = {h["id"] for h in data["hyperedges"]}
assert ids == {"he_a", "he_b_v2", "he_global"}
assert data["graph"]["hyperedges"] == data["hyperedges"]
def test_deleted_file_member_is_pruned_from_surviving_hyperedges(tmp_path):
"""#5081: a deleted file's node must not stay named by a hyperedge that
survives. The cross-file one keeps its live members; one left with no live
member is dropped."""
root, graph_path = _seed_full_graph(tmp_path)
data = json.loads(graph_path.read_text(encoding="utf-8"))
data["hyperedges"].append({"id": "he_c_only", "label": "only c", "nodes": ["c1"]})
graph_path.write_text(json.dumps(data), encoding="utf-8")
G = _update_after_editing_b(graph_path, root) # deletes c.md
hes = {h["id"]: h for h in G.graph["hyperedges"]}
assert sorted(hes["he_global"]["nodes"]) == ["a1", "b1"]
assert "he_c_only" not in hes
def test_update_reads_nested_only_hyperedge_slot(tmp_path):
"""A graph.json written by a node_link_data-only writer stores its hyperedges
solely under ``graph.hyperedges``. The incremental loader must fold that slot
the way build_from_json does (#2485), or --update loses the whole set."""
root, graph_path = _seed_full_graph(tmp_path, nested_only=True)
G = _update_after_editing_b(graph_path, root)
ids = _he_ids(G)
assert {"he_a", "he_global", "he_b_v2"} <= ids
assert "he_b" not in ids
assert "he_c" not in ids
def test_update_falls_back_to_nested_when_top_level_slot_is_malformed(tmp_path):
"""A null top-level value must not mask a readable nested list, and the
loader must not raise on it either."""
root, graph_path = _seed_full_graph(tmp_path, nested_only=True)
data = json.loads(graph_path.read_text(encoding="utf-8"))
data["hyperedges"] = None
graph_path.write_text(json.dumps(data), encoding="utf-8")
G = _update_after_editing_b(graph_path, root)
ids = _he_ids(G)
assert {"he_a", "he_global", "he_b_v2"} <= ids
assert "he_b" not in ids
assert "he_c" not in ids
def test_update_prefers_top_level_slot_over_stale_nested_copy(tmp_path):
"""Both slots present: the canonical top-level key wins, so a stale nested
copy cannot resurrect hyperedges the graph already replaced."""
root = tmp_path / "corpus"
root.mkdir()
graph_path = tmp_path / "graph.json"
nodes = [
{"id": "a1", "label": "a1", "file_type": "document", "source_file": "a.md"},
{"id": "b1", "label": "b1", "file_type": "document", "source_file": "b.md"},
]
data = {
"nodes": nodes,
"edges": [],
"hyperedges": [{"id": "he_top", "source_file": "a.md", "nodes": ["a1"]}],
"graph": {"hyperedges": [{"id": "he_stale", "source_file": "a.md", "nodes": ["a1"]}]},
}
graph_path.write_text(json.dumps(data), encoding="utf-8")
new_chunk = {
"nodes": [{"id": "b1", "label": "b1", "file_type": "document", "source_file": "b.md"}],
"edges": [],
}
G = build_merge([new_chunk], graph_path, dedup=False, root=root)
ids = _he_ids(G)
assert "he_top" in ids
assert "he_stale" not in ids
def test_raw_merge_reads_nested_only_hyperedge_slot(tmp_path):
"""The --no-cluster incremental path shares the loader, so it must keep a
nested-only graph's hyperedges too."""
root, graph_path = _seed_full_graph(tmp_path, nested_only=True)
new = {
"nodes": [{"id": "b1", "label": "b.md", "file_type": "document", "source_file": "b.md"}],
"edges": [],
"hyperedges": [
{"id": "he_b_v2", "label": "flow b v2", "source_file": "b.md", "nodes": ["b1"]}
],
}
merged = merge_raw_extraction(
new, graph_path, prune_sources=[str(root / "c.md")], root=root
)
ids = {h["id"] for h in merged["hyperedges"]}
assert {"he_a", "he_global", "he_b_v2"} <= ids
assert "he_b" not in ids
assert "he_c" not in ids
# ── #1571: root-less prune (absolute deleted paths vs relative node keys) ──────
def test_prune_without_root_removes_ghost_nodes_via_grandparent_fallback(tmp_path):
+72
View File
@@ -1,4 +1,5 @@
"""Tests for graphify/cache.py."""
import json
import os
import pytest
from pathlib import Path
@@ -2073,3 +2074,74 @@ def test_scope_semantic_result_unscoped_is_a_no_op():
assert (dropped_files, dropped_items) == (set(), 0)
assert [n["id"] for n in result["nodes"]] == ["n"]
# -- #5083: mark a degraded entry partial so the next run self-heals ----------
def test_mark_semantic_cache_partial_forces_next_run_miss(tmp_path):
"""A degraded entry stays on disk for inspection but stops being served."""
from graphify.cache import load_cached, mark_semantic_cache_partial, save_semantic_cache
_reset_stat_index()
doc = tmp_path / "doc.md"
doc.write_text("# Doc\n")
save_semantic_cache([{"id": "doc", "source_file": "doc.md"}], [], root=tmp_path)
assert load_cached(doc, root=tmp_path, kind="semantic") is not None
marked = mark_semantic_cache_partial(["doc.md"], root=tmp_path)
assert len(marked) == 1
assert marked[0].exists()
assert load_cached(doc, root=tmp_path, kind="semantic") is None
assert load_cached(doc, root=tmp_path, kind="semantic", allow_partial=True)[
"partial"
] is True
# A complete re-extraction overwrites the same content-hash key cleanly.
save_semantic_cache([{"id": "doc", "source_file": "doc.md"}], [], root=tmp_path)
assert load_cached(doc, root=tmp_path, kind="semantic") is not None
def test_mark_semantic_cache_partial_marks_the_flat_entry_it_would_serve(tmp_path):
"""A pre-fingerprint flat entry must be marked, not shadowed by a new one."""
from graphify.cache import (
cache_dir,
file_hash,
load_cached,
mark_semantic_cache_partial,
)
_reset_stat_index()
doc = tmp_path / "doc.md"
doc.write_text("# Doc\n")
flat = cache_dir(tmp_path, "semantic") / f"{file_hash(doc, tmp_path)}.json"
flat.write_text(
json.dumps({"nodes": [{"id": "doc", "source_file": "doc.md"}]}),
encoding="utf-8",
)
prompt = "a prompt"
# The fingerprinted namespace misses, so the read path falls back to flat.
assert load_cached(doc, root=tmp_path, kind="semantic", prompt=prompt) is not None
marked = mark_semantic_cache_partial(["doc.md"], root=tmp_path, prompt=prompt)
assert marked == [flat]
assert load_cached(doc, root=tmp_path, kind="semantic", prompt=prompt) is None
def test_mark_semantic_cache_partial_skips_missing_and_already_partial(tmp_path):
from graphify.cache import load_cached, mark_semantic_cache_partial, save_semantic_cache
_reset_stat_index()
doc = tmp_path / "doc.md"
doc.write_text("# Doc\n")
save_semantic_cache(
[{"id": "doc", "source_file": "doc.md"}],
[],
root=tmp_path,
partial_source_files=[doc],
)
# Already partial -> nothing new to mark; a missing source is skipped.
assert mark_semantic_cache_partial(["doc.md"], root=tmp_path) == []
assert mark_semantic_cache_partial(["absent.md"], root=tmp_path) == []
assert load_cached(doc, root=tmp_path, kind="semantic") is None
+167
View File
@@ -0,0 +1,167 @@
"""Declared C++ receiver chains resolve without guessing by method name."""
import json
import pytest
from graphify.extract import extract
HEADER = """
#include <memory>
namespace app {
struct Direct { void Execute() {} };
struct Smart { void Execute() {} };
struct ValueClient { Direct actions; };
struct SmartClient { std::unique_ptr<Smart> actions; };
struct SharedClient { std::shared_ptr<Smart> actions; };
struct RawClient { Smart* actions; };
struct Outer { SmartClient client; };
}
"""
def _extract(tmp_path, source, header=HEADER, reverse=False):
paths = [tmp_path / "types.hpp", tmp_path / "use.cpp"]
paths[0].write_text(header, encoding="utf-8")
paths[1].write_text('#include "types.hpp"\n' + source, encoding="utf-8")
result = extract(paths[::-1] if reverse else paths, root=tmp_path,
cache_root=tmp_path / "cache", parallel=False)
return paths, result
def _calls(result, caller="Run()"):
nodes = {n["id"]: n for n in result["nodes"]}
owners = {e["target"]: nodes[e["source"]].get("_cpp_qualified")
for e in result["edges"] if e["relation"] in {"method", "defines"}}
return [(owners.get(e["target"]), nodes[e["target"]]["label"], e["confidence"])
for e in result["edges"] if e["relation"] == "calls"
and nodes[e["source"]]["label"] == caller]
@pytest.mark.parametrize("reverse", [False, True])
@pytest.mark.parametrize("parameter,expression,owner", [
("app::Direct& x", "x.Execute()", "app::Direct"),
("std::unique_ptr<app::Smart>& x", "x->Execute()", "app::Smart"),
("app::ValueClient& x", "x.actions.Execute()", "app::Direct"),
("app::SmartClient& x", "x.actions->Execute()", "app::Smart"),
("app::SharedClient* x", "x->actions->Execute()", "app::Smart"),
("app::RawClient& x", "(x).actions->Execute()", "app::Smart"),
("app::Outer& x", "x.client.actions->Execute()", "app::Smart"),
("app::SmartClient& x", "([&] { x.actions->Execute(); })()", "app::Smart"),
])
def test_split_header_chains(tmp_path, parameter, expression, owner, reverse):
paths, result = _extract(tmp_path, f"void Run({parameter}) {{ {expression}; }}", reverse=reverse)
assert _calls(result) == [(owner, ".Execute()", "INFERRED")]
cached = extract(paths, root=tmp_path, cache_root=tmp_path / "cache", parallel=False)
assert _calls(cached) == _calls(result)
def test_scope_and_same_named_fields(tmp_path):
_, result = _extract(tmp_path, """
void Run(app::SmartClient& x) {
{ app::ValueClient x; x.actions.Execute(); }
([&](app::ValueClient& x) { x.actions.Execute(); })(*(app::ValueClient*)nullptr);
x.actions->Execute();
}
void Other(app::ValueClient& x) { x.actions.Execute(); }
""")
assert set(_calls(result)) == {("app::Direct", ".Execute()", "INFERRED"),
("app::Smart", ".Execute()", "INFERRED")}
assert _calls(result, "Other()") == [("app::Direct", ".Execute()", "INFERRED")]
@pytest.mark.parametrize("body", [
"{ auto x = unknown(); x.actions->Execute(); }",
"([&](auto& x) { x.actions->Execute(); })(unknown());",
"([x = unknown()] { x.actions->Execute(); })();",
"{ std::vector<app::SmartClient> x; x.actions->Execute(); }",
"{ UnresolvedAlias x; x.actions->Execute(); }",
"x.missing->Execute();",
"x.actions.Execute();", # dot accesses the wrapper, not its pointee
])
def test_unsupported_or_shadowed_receivers_do_not_guess(tmp_path, body):
_, result = _extract(tmp_path, f"void Run(app::SmartClient& x) {{ {body} }}")
assert _calls(result) == []
def test_namespace_ambiguity_does_not_pick_a_same_named_class(tmp_path):
header = HEADER + "\nnamespace other { struct SmartClient { app::Direct actions; }; }"
_, result = _extract(tmp_path, "void Run(SmartClient& x) { x.actions->Execute(); }", header)
assert _calls(result) == []
@pytest.mark.parametrize("body", [
"([&](app::ValueClient& x) { x.actions.Execute(); })(*(app::ValueClient*)nullptr);",
"{ app::ValueClient x; x.actions.Execute(); }",
])
def test_inner_binding_is_the_only_target(tmp_path, body):
_, result = _extract(tmp_path, f"void Run(app::SmartClient& x) {{ {body} }}")
assert _calls(result) == [("app::Direct", ".Execute()", "INFERRED")]
@pytest.mark.parametrize("expression", ["unknown().actions->Execute()", "x.missing->Execute()",
"x.actions->execute()", "x.actions.Execute()"])
def test_same_file_and_case_collisions_do_not_guess(tmp_path, expression):
_, result = _extract(tmp_path, HEADER + f"\nvoid Run(app::SmartClient& x) {{ {expression}; }}", "")
assert _calls(result) == []
def test_lowercase_smart_pointer_type_uses_the_declared_receiver(tmp_path):
_, result = _extract(tmp_path, """
struct action { void Execute() {} };
void Run(std::unique_ptr<action>& x) { x->Execute(); }
""", "")
assert _calls(result) == [("action", ".Execute()", "INFERRED")]
@pytest.mark.parametrize("expression", ["this->client.actions->Execute()", "client.actions->Execute()"])
def test_explicit_this_chain_and_implicit_field(tmp_path, expression):
header = HEADER + "\nstruct Holder { app::SmartClient client; void Run(); };"
_, result = _extract(tmp_path, f"void Holder::Run() {{ {expression}; }}", header)
assert _calls(result, "Holder::Run()") == [("app::Smart", ".Execute()", "INFERRED")]
def test_forward_declaration_is_not_a_competing_definition(tmp_path):
paths, _ = _extract(tmp_path, "void Run(app::SmartClient& x) { x.actions->Execute(); }")
forward = tmp_path / "forward.hpp"
forward.write_text("namespace app { struct Smart; }", encoding="utf-8")
result = extract([forward, *paths], root=tmp_path, cache_root=tmp_path / "cache", parallel=False)
assert _calls(result) == [("app::Smart", ".Execute()", "INFERRED")]
@pytest.mark.parametrize("wrapper", ["std::weak_ptr<app::Smart>", "CustomPtr<app::Smart>",
"std::unique_ptr<app::Smart[]>",
"std::unique_ptr<app::Smart, CustomDeleter>"])
def test_unsupported_pointer_wrappers_do_not_unwrap(tmp_path, wrapper):
_, result = _extract(tmp_path, f"void Run({wrapper}& x) {{ x->Execute(); }}")
assert _calls(result) == []
def test_prior_ast_cache_is_not_reused(tmp_path, monkeypatch):
import graphify.cache as cache
current = cache._AST_CACHE_SCHEMA
assert current > 40
with monkeypatch.context() as old:
old.setattr(cache, "_AST_CACHE_SCHEMA", 40)
paths, _ = _extract(tmp_path, "void Run(app::SmartClient& x) { x.actions->Execute(); }")
# Strip the new metadata as if these entries predated chain support.
for path in (tmp_path / "cache").rglob("*.json"):
text = path.read_text(encoding="utf-8")
path.write_text(text.replace('"_cpp_fields"', '"old_fields"')
.replace('"cpp_receiver_chain"', '"old_chain"'), encoding="utf-8")
fresh = extract(paths, root=tmp_path, cache_root=tmp_path / "cache", parallel=False)
assert _calls(fresh) == [("app::Smart", ".Execute()", "INFERRED")]
def test_incremental_caller_uses_persisted_header_fields(tmp_path):
paths, result = _extract(tmp_path, "void Run(app::SmartClient& x) { x.actions->Execute(); }")
result = json.loads(json.dumps(result))
paths[1].write_text(paths[1].read_text(encoding="utf-8") + "\n// caller edit\n", encoding="utf-8")
fresh = extract([paths[1]], root=tmp_path, cache_root=tmp_path / "cache", parallel=False,
resolution_context_nodes=[n for n in result["nodes"] if n.get("source_file") != "use.cpp"],
resolution_context_edges=[e for e in result["edges"] if e.get("source_file") != "use.cpp"])
combined = {"nodes": result["nodes"] + fresh["nodes"], "edges": [
e for e in result["edges"] if e.get("relation") in {"method", "defines"}
] + fresh["edges"]}
assert _calls(combined) == [("app::Smart", ".Execute()", "INFERRED")]
assert not any(n.get("source_file") == "types.hpp" for n in fresh["nodes"])
+295
View File
@@ -0,0 +1,295 @@
"""Decision record: A/B comparison of candidate C# extension binders (#4828).
The production pass is chosen by measuring candidates against fixtures whose
ground truth is decidable from the C# spec. This module keeps the comparison
executable: it is what tells a future change that removing the scope check, the
unresolved-base poison, or the deny-list costs a false edge.
Candidates are applied to the graph as the *nominal* pipeline builds it
(``production_extension=False`` in the harness), so the numbers stay comparable
no matter which stage of the production fix has landed. The production behaviour
itself is covered by ``test_csharp_extension_resolution.py``.
Fixtures: ``expect`` must bind, ``forbid``/``forbid_pairs`` must not, ``optional``
is unknowable without a BCL symbol table and is never scored.
"""
from __future__ import annotations
import pytest
from tests.csharp_extension_harness import (
FIXTURES,
STRATEGY_IDS,
STRATEGIES,
expected_pairs,
line_of,
strategy_bindings,
)
FIXTURE_IDS = list(FIXTURES)
# Strategies that claim "no false edge anywhere". The others are deliberately
# imprecise (that is the property being measured) and are scored by the matrix.
PRECISE_STRATEGIES = [
"S3_typed_assignable",
"S5_roc_guarded",
"S7_all_rungs",
"S9_signature_parse",
]
# Per strategy, the fixtures it must get fully right. Everything else may
# under-bind (scored by the matrix) but may still not over-bind.
STRATEGY_RECALL: dict[str, set[str]] = {
"S1_typed_exact": {"domain_cross_file", "same_file", "arity", "type_param_vs_class"},
"S2_typed_exact_scope": {"domain_cross_file", "same_file", "arity", "type_param_vs_class"},
"S3_typed_assignable": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
},
"S4_roc_naive": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
"primitive_and_thirdparty", "generic_wildcard",
},
"S5_roc_guarded": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
"primitive_and_thirdparty", "generic_wildcard",
},
"S6_reporter_patch": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"instance_wins", "primitive_and_thirdparty", "generic_wildcard",
"issue_repro",
},
"S7_all_rungs": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
"primitive_and_thirdparty", "generic_wildcard", "issue_repro",
},
"S9_signature_parse": {
"domain_cross_file", "same_file", "arity", "base_and_interface",
"inner_scope_wins", "instance_wins",
},
}
# --------------------------------------------------------------------------- #
# fixture sanity
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_fixture_markers_are_unambiguous(name):
fixture = FIXTURES[name]
bodies = "\n".join(fixture.files.values())
import re as _re
markers = _re.findall(r"//\s*[A-Z]\d+", bodies)
for marker in set(markers):
assert markers.count(marker) == 1, (name, marker, markers.count(marker))
def source_of(marker):
hits = [b for b in fixture.files.values() if marker in b]
assert len(hits) == 1, (name, marker, len(hits))
return hits[0]
for call_marker, (t_file, t_marker) in fixture.expect.items():
assert line_of(source_of(call_marker), call_marker)
assert line_of(fixture.files[t_file], t_marker)
assert call_marker not in fixture.forbid, (name, call_marker)
for call_marker in fixture.forbid:
assert line_of(source_of(call_marker), call_marker)
for call_marker, (t_file, t_marker) in fixture.forbid_pairs.items():
assert line_of(source_of(call_marker), call_marker)
assert line_of(fixture.files[t_file], t_marker)
assert fixture.expect.get(call_marker) != (t_file, t_marker)
for call_marker in fixture.optional:
assert line_of(source_of(call_marker), call_marker)
# --------------------------------------------------------------------------- #
# per-candidate sweep
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("strategy_id", PRECISE_STRATEGIES)
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_precise_strategy_emits_no_forbidden_edge(name, strategy_id):
result = strategy_bindings(name, strategy_id)
assert result["violations"] == set(), f"{strategy_id} on {name}"
@pytest.mark.parametrize("strategy_id", STRATEGY_IDS)
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_strategy_to_upholds_the_ground_truth(name, strategy_id):
if strategy_id == "S0_baseline":
assert strategy_bindings(name, strategy_id)["added"] == []
return
required = STRATEGY_RECALL.get(strategy_id, set())
if name not in required:
pytest.skip("under-binding is scored by the matrix test")
result = strategy_bindings(name, strategy_id)
assert expected_pairs(name) <= result["bindings"], (
f"{strategy_id} on {name}: missing "
f"{sorted(expected_pairs(name) - result['bindings'])}"
)
# --------------------------------------------------------------------------- #
# the matrix
# --------------------------------------------------------------------------- #
def _score(strategy_id: str) -> dict:
expected_total = 0
correct = 0
wrong: list = []
for name in FIXTURE_IDS:
fixture = FIXTURES[name]
expected = expected_pairs(name)
expected_total += len(expected)
result = strategy_bindings(name, strategy_id)
correct += len(expected & result["bindings"])
for binding in result["bindings"] - expected:
if binding[0] in fixture.optional:
continue
wrong.append((name, *binding))
for edge in result["phantoms"]:
wrong.append((name, "phantom", str(edge.get("target"))))
return {
"expected": expected_total,
"correct": correct,
"wrong": wrong,
"recall": correct / expected_total if expected_total else 0.0,
"precision": correct / (correct + len(wrong)) if (correct + len(wrong)) else 1.0,
}
def test_strategy_matrix(capsys):
scores = {sid: _score(sid) for sid in STRATEGY_IDS}
lines = [
f"{'strategy':26} {'hits':>5} {'expected':>9} {'wrong':>6} "
f"{'recall':>7} {'precision':>10}"
]
for sid in STRATEGY_IDS:
s = scores[sid]
lines.append(
f"{sid:26} {s['correct']:5d} {s['expected']:9d} {len(s['wrong']):6d} "
f"{s['recall']:7.3f} {s['precision']:10.3f}"
)
with capsys.disabled():
print("\n" + "\n".join(lines))
# Baseline proves the fixtures are not already passing: it can satisfy only
# the ordinary static/instance calls, never an extension call.
assert scores["S0_baseline"]["wrong"] == []
assert scores["S0_baseline"]["correct"] < scores["S3_typed_assignable"]["correct"]
# Each added rung is weakly better on recall.
assert scores["S2_typed_exact_scope"]["recall"] >= scores["S1_typed_exact"]["recall"]
assert scores["S3_typed_assignable"]["recall"] >= scores["S2_typed_exact_scope"]["recall"]
assert scores["S5_roc_guarded"]["recall"] >= scores["S3_typed_assignable"]["recall"]
assert scores["S7_all_rungs"]["recall"] >= scores["S5_roc_guarded"]["recall"]
# The provable-only rung has no false edge anywhere in the corpus.
for sid in PRECISE_STRATEGIES:
assert scores[sid]["wrong"] == [], sid
# Relaxing a rule costs precision: each of these is a documented trade.
assert scores["S1_typed_exact"]["wrong"], "no-scope must bind an unimported extension"
assert scores["S2_typed_exact_scope"]["wrong"], "no-poison must bind through an unknown base"
assert scores["S4_roc_naive"]["wrong"], "no-deny-list must bind a BCL instance member"
assert scores["S6_reporter_patch"]["wrong"], "reporter patch must bind out of scope / through a base"
assert scores["S4_roc_naive"]["recall"] > scores["S5_roc_guarded"]["recall"]
assert scores["S5_roc_guarded"]["recall"] > scores["S3_typed_assignable"]["recall"]
# --------------------------------------------------------------------------- #
# explicit discriminators: each proves the flag it names is what changed
# --------------------------------------------------------------------------- #
def _has(name: str, strategy_id: str, call_marker: str, target: tuple[str, str]) -> bool:
return (call_marker, target) in strategy_bindings(name, strategy_id)["bindings"]
def test_scope_flag_is_what_excludes_an_unimported_extension():
target = ("Other.cs", "// D1")
assert _has("out_of_scope", "S1_typed_exact", "// E1", target)
for sid in ("S2_typed_exact_scope", "S3_typed_assignable",
"S5_roc_guarded", "S7_all_rungs"):
assert not _has("out_of_scope", sid, "// E1", target), sid
def test_scope_level_is_what_picks_the_inner_extension():
inner = ("Inner.cs", "// D2")
outer = ("Outer.cs", "// D1")
assert not _has("inner_scope_wins", "S1_typed_exact", "// E1", inner)
assert _has("inner_scope_wins", "S3_typed_assignable", "// E1", inner)
assert not _has("inner_scope_wins", "S3_typed_assignable", "// E1", outer)
def test_assignability_is_what_reaches_base_and_interface_extensions():
base = ("Domain.cs", "// D1")
iface = ("Domain.cs", "// D2")
assert not _has("base_and_interface", "S2_typed_exact_scope", "// E1", base)
assert not _has("base_and_interface", "S2_typed_exact_scope", "// E2", iface)
assert _has("base_and_interface", "S3_typed_assignable", "// E1", base)
assert _has("base_and_interface", "S3_typed_assignable", "// E2", iface)
def test_poison_flag_is_what_refuses_an_unknown_base():
target = ("W.cs", "// D1")
assert _has("unresolved_base_poison", "S2_typed_exact_scope", "// E1", target)
assert not _has("unresolved_base_poison", "S3_typed_assignable", "// E1", target)
def test_out_of_corpus_rung_is_what_reaches_string_and_thirdparty():
targets = {
"// E1": ("Ext.cs", "// D1"),
"// E2": ("Ext.cs", "// D2"),
"// E3": ("Ext.cs", "// D3"),
}
for marker, target in targets.items():
assert not _has("primitive_and_thirdparty", "S3_typed_assignable", marker, target), marker
assert _has("primitive_and_thirdparty", "S5_roc_guarded", marker, target), marker
def test_deny_list_is_what_prevents_a_bcl_false_positive():
"""`PropertyInfo.GetValue(obj)`: the 2-arg extension fits the arity, so only
the deny-list stands between the naive rung and a false edge."""
target = ("E.cs", "// D2")
assert _has("bcl_name_cost", "S4_roc_naive", "// E1", target)
assert not _has("bcl_name_cost", "S5_roc_guarded", "// E1", target)
def test_untyped_rung_is_what_reaches_a_chained_receiver():
target = ("Ext.cs", "// D1")
assert not _has("issue_repro", "S5_roc_guarded", "// E2", target)
assert _has("issue_repro", "S7_all_rungs", "// E2", target)
# ... while the typed (primitive) receiver needs no untyped rung at all.
assert _has("issue_repro", "S5_roc_guarded", "// E1", target)
def test_metadata_beats_signature_parsing_on_this_T():
"""Both `this T` declarations look identical in the signature text."""
concrete = ("T.cs", "// D1")
assert _has("type_param_vs_class", "S3_typed_assignable", "// E1", concrete)
assert not _has("type_param_vs_class", "S9_signature_parse", "// E1", concrete)
# The generic `this T` is the wildcard rung, reachable only with the
# `extended_is_type_param` fact that the signature text cannot carry.
wildcard = ("Gen.cs", "// D1")
assert _has("generic_wildcard", "S5_roc_guarded", "// E1", wildcard)
assert not _has("generic_wildcard", "S9_signature_parse", "// E1", wildcard)
def test_control_bare_name_reintroduces_the_god_node_edge():
"""The anti-pattern is real on this corpus, which is why it is rejected."""
control = strategy_bindings("god_node_control", "S8_bare_name_control")
assert ("// F1", ("Cache.cs", "// D1")) in control["bindings"]
for sid in STRATEGY_IDS:
if sid == "S8_bare_name_control":
continue
assert not _has("god_node_control", sid, "// F1", ("Cache.cs", "// D1")), sid
+211
View File
@@ -0,0 +1,211 @@
"""C# extension-method declaration facts and primitive receiver typing (#4828).
The member-call resolvers can only bind a call to an extension method if the
declaration carries the join key: which type the `this` parameter extends. These
tests pin that the extractor records it (and keeps recording it in a way the
resolver can consume), and that a primitive receiver type is stamped so
`this string` can ever match.
"""
from __future__ import annotations
import os
import tempfile
from pathlib import Path
from graphify.extract import extract, extract_csharp
def _extract(tmp_path, files: dict[str, str]):
for name, body in files.items():
path = tmp_path / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body)
old = os.getcwd()
try:
os.chdir(tmp_path)
result = extract([Path(n) for n in files], cache_root=Path(tempfile.mkdtemp()))
per_file = {n: extract_csharp(Path(n)) for n in files}
finally:
os.chdir(old)
return result, per_file
def _line_of(text: str, marker: str) -> str:
hits = [i for i, line in enumerate(text.splitlines(), start=1) if marker in line]
assert len(hits) == 1, (marker, hits)
return f"L{hits[0]}"
def _meta_by_line(result, source_file: str, text: str, marker: str) -> dict:
line = _line_of(text, marker)
hits = [
n for n in result["nodes"]
if n.get("source_file") == source_file and n.get("source_location") == line
]
assert len(hits) == 1, (source_file, line, [n.get("label") for n in hits])
return hits[0].get("metadata") or {}
def _call(per_file, callee: str, source_file: str, line: str) -> dict:
hits = [
rc for rc in per_file[source_file].get("raw_calls", [])
if rc.get("callee") == callee and rc.get("source_location") == line
]
assert len(hits) == 1, (callee, source_file, line, hits)
return hits[0]
def test_this_parameter_records_the_extended_type(tmp_path):
ext = (
"namespace Ext {\n"
" public static class StringExtensions {\n"
" public static string Mask(this string s, char m = '*') { return s; } // D1\n"
" }\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"Ext.cs": ext})
meta = _meta_by_line(result, "Ext.cs", ext, "// D1")
assert meta["extension"] is True
assert meta["extended_type"] == "string"
assert meta["extended_type_arity"] == 0
assert "extended_is_type_param" not in meta
# Parameter arity keeps its #4584 meaning; the extension call is one short.
assert meta["arity"] == 2
assert meta["min_arity"] == 0
def test_generic_extended_type_keeps_name_and_arity(tmp_path):
src = (
"namespace App {\n"
" public class Box<T> { }\n"
" public static class BoxExt {\n"
" public static void Fill(this Box<int> b) { } // D1\n"
" }\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"Box.cs": src})
meta = _meta_by_line(result, "Box.cs", src, "// D1")
assert meta["extended_type"] == "Box"
assert meta["extended_type_arity"] == 1
def test_qualified_this_parameter_keeps_only_the_simple_name(tmp_path):
src = (
"namespace App {\n"
" public class Widget { }\n"
" public static class WExt {\n"
" public static void Paint(this App.Widget w) { } // D1\n"
" }\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"W.cs": src})
meta = _meta_by_line(result, "W.cs", src, "// D1")
assert meta["extended_type"] == "Widget"
def test_open_generic_extension_is_marked_as_a_type_parameter(tmp_path):
src = (
"public class T { }\n"
"public static class TExt {\n"
" public static void Go(this T t) { } // D1\n"
"}\n"
"public static class GenExt {\n"
" public static void Go<T>(this T t) { } // D2\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"Gen.cs": src})
concrete = _meta_by_line(result, "Gen.cs", src, "// D1")
generic = _meta_by_line(result, "Gen.cs", src, "// D2")
# Both carry the same name, so only this flag can tell them apart.
assert concrete["extended_type"] == "T"
assert "extended_is_type_param" not in concrete
assert generic["extended_type"] == "T"
assert generic["extended_is_type_param"] is True
def test_object_extension_is_recorded_as_the_wildcard_type(tmp_path):
src = (
"public static class ObjExt {\n"
" public static object GetValue(this object o) { return o; } // D1\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"O.cs": src})
meta = _meta_by_line(result, "O.cs", src, "// D1")
assert meta["extended_type"] == "object"
assert "extended_is_type_param" not in meta
def test_ordinary_method_has_no_extension_facts(tmp_path):
src = "public class C {\n public void M(int a) { } // D1\n}\n"
result, _per_file = _extract(tmp_path, {"C.cs": src})
meta = _meta_by_line(result, "C.cs", src, "// D1")
assert "extension" not in meta
assert "extended_type" not in meta
def test_primitive_receiver_types_are_stamped(tmp_path):
ext = (
"namespace Ext {\n"
" public static class Exts {\n"
" public static string Mask(this string s) { return s; }\n"
" }\n"
"}\n"
)
svc = (
"using Ext;\n"
"public class Svc {\n"
" public string A(string s) { return s.Mask(); } // E1\n"
" public string B(long v) { return v.ToString(); } // E2\n"
"}\n"
)
_result, per_file = _extract(tmp_path, {"Ext.cs": ext, "Svc.cs": svc})
mask = _call(per_file, "Mask", "Svc.cs", _line_of(svc, "// E1"))
assert mask["receiver"] == "s"
assert mask["receiver_type"] == "string"
tostring = _call(per_file, "ToString", "Svc.cs", _line_of(svc, "// E2"))
assert tostring["receiver_type"] == "long"
def test_primitive_receiver_is_not_parked_as_cross_repo(tmp_path):
ext = (
"namespace Ext {\n"
" public static class Exts {\n"
" public static string Mask(this string s) { return s; }\n"
" }\n"
"}\n"
)
svc = (
"using Ext;\n"
"public class Svc {\n"
" public string A(string s) { return s.Mask(); }\n"
"}\n"
)
result, per_file = _extract(tmp_path, {"Ext.cs": ext, "Svc.cs": svc})
caller_nid = per_file["Svc.cs"]["raw_calls"][0]["caller_nid"]
caller = next(n for n in result["nodes"] if n["id"] == caller_nid)
assert "unresolved_calls" not in (caller.get("metadata") or {}), (
"a `string` receiver has no cross-repo declaration to wait for"
)
def test_chained_receiver_is_still_untyped(tmp_path):
"""The remaining gap, pinned so a future chained-receiver fix is deliberate."""
ext = (
"namespace Ext {\n"
" public static class Exts {\n"
" public static string Mask(this string s) { return s; }\n"
" }\n"
"}\n"
)
svc = (
"using Ext;\n"
"public class Svc {\n"
" public string B(long v) { return v.ToString().Mask(); } // E1\n"
"}\n"
)
_result, per_file = _extract(tmp_path, {"Ext.cs": ext, "Svc.cs": svc})
chained = _call(per_file, "Mask", "Svc.cs", _line_of(svc, "// E1"))
assert chained.get("receiver") is None
assert chained.get("receiver_type") is None
assert chained.get("receiver_chain") is None
assert chained.get("receiver_call") is None
+163
View File
@@ -0,0 +1,163 @@
"""Production behaviour for C# extension-call binding (#4828).
Ground truth lives in ``tests/csharp_extension_harness.py``: ``expect`` edges must
exist in the real pipeline output, ``forbid`` edges must not. ``STAGE_FIXTURES``
names the fixtures the pass is required to satisfy *at this stage* of the fix;
the forbidden-edge tests run against every fixture from the first stage, so a
later stage can only add recall, never a false edge.
"""
from __future__ import annotations
import pytest
from tests.csharp_extension_harness import (
FIXTURES,
expected_pairs,
graph_bindings,
)
FIXTURE_IDS = list(FIXTURES)
# Stage 1: in-corpus receivers, scope, assignability, poison, arity.
# Stage 2: out-of-corpus receivers guarded by the BCL/regular-name rules.
# Stage 3: untyped/chained receivers.
STAGE_FIXTURES = {
"domain_cross_file",
"same_file",
"arity",
"type_param_vs_class",
"base_and_interface",
"inner_scope_wins",
"instance_wins",
# stage 2: out-of-corpus receivers (primitives, third-party types, `this T`)
"primitive_and_thirdparty",
"generic_wildcard",
# stage 3: untyped/chained receivers
"issue_repro",
}
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_production_never_emits_a_forbidden_edge(name):
result = graph_bindings(name)
assert result["violations"] == set(), sorted(result["violations"])
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_production_invents_no_call_site(name):
assert graph_bindings(name)["phantoms"] == []
@pytest.mark.parametrize("name", sorted(STAGE_FIXTURES))
def test_production_binds_the_decidable_extension_calls(name):
result = graph_bindings(name)
missing = expected_pairs(name) - result["bindings"]
assert not missing, f"{name}: missing {sorted(missing)}"
def test_extension_edge_is_inferred_at_the_call_site():
from tests.csharp_extension_harness import corpus
data = corpus("domain_cross_file")
by_id = {n["id"]: n for n in data["nodes"]}
paint_calls = [
e for e in data["edges"]
if e.get("relation") == "calls"
and by_id.get(e.get("target"), {}).get("label") == ".Paint()"
]
assert len(paint_calls) == 2
assert {e["source_location"] for e in paint_calls} == {"L5", "L6"}
for edge in paint_calls:
assert edge["confidence"] == "INFERRED"
assert edge["confidence_score"] == 0.85
assert edge["context"] == "call"
def test_instance_member_wins_over_a_same_named_extension():
"""`Cache.GetValue()` is nominal; the extension of the same name must not win."""
result = graph_bindings("instance_wins")
assert ("// E1", ("Cache.cs", "// D1")) in result["bindings"]
assert ("// E1", ("Cache.cs", "// D2")) not in result["bindings"]
def test_static_form_is_never_rebound_to_the_extension():
"""`Conv.ToInt32(x)` names its type in source and is bound by the nominal pass."""
result = graph_bindings("static_class_receiver")
assert ("// B1", ("E.cs", "// D1")) in result["bindings"]
assert ("// B1", ("E.cs", "// D2")) not in result["bindings"]
def test_ambiguity_binds_nothing():
result = graph_bindings("ambiguous_same_scope")
assert not any(marker == "// E1" for marker, _target in result["bindings"])
def test_out_of_scope_extension_binds_nothing():
result = graph_bindings("out_of_scope")
assert not any(marker == "// E1" for marker, _target in result["bindings"])
def test_unresolved_base_poisons_the_lookup():
result = graph_bindings("unresolved_base_poison")
assert not any(marker == "// E1" for marker, _target in result["bindings"])
def test_out_of_corpus_receiver_binds_through_the_guarded_rung():
"""`string.Mask()`, `int.Twice()` and a third-party receiver all bind."""
result = graph_bindings("primitive_and_thirdparty")
for marker, target in (
("// E1", ("Ext.cs", "// D1")),
("// E2", ("Ext.cs", "// D2")),
("// E3", ("Ext.cs", "// D3")),
):
assert (marker, target) in result["bindings"], marker
def test_out_of_corpus_extension_edge_is_scored_lower():
from tests.csharp_extension_harness import corpus
data = corpus("primitive_and_thirdparty")
by_id = {n["id"]: n for n in data["nodes"]}
scores = {
by_id[e["target"]]["label"]: e["confidence_score"]
for e in data["edges"]
if e.get("relation") == "calls"
and by_id.get(e["target"], {}).get("metadata", {}).get("extension")
}
assert scores[".Mask()"] == 0.75
assert scores[".Twice()"] == 0.75
def test_bcl_member_name_on_an_undeclared_type_is_not_bound():
"""`PropertyInfo.GetValue(obj)` is an instance call; the corpus cannot prove
otherwise, so the deny-list refuses the same-named extension."""
result = graph_bindings("bcl_name_cost")
assert not any(marker == "// E1" for marker, _target in result["bindings"])
def test_open_generic_extension_applies_only_as_a_wildcard():
result = graph_bindings("generic_wildcard")
assert ("// E1", ("Gen.cs", "// D1")) in result["bindings"]
# The concrete class T keeps winning over the generic `this T` declaration.
concrete = graph_bindings("type_param_vs_class")
assert ("// E1", ("T.cs", "// D1")) in concrete["bindings"]
assert ("// E1", ("T.cs", "// D2")) not in concrete["bindings"]
def test_chained_receiver_binds_when_the_name_is_unique():
"""The issue's `v.ToString().Mask()` line: no receiver type to check, so the
guarded untyped rung is the only possible proof."""
result = graph_bindings("issue_repro")
assert ("// E1", ("Ext.cs", "// D1")) in result["bindings"]
assert ("// E2", ("Ext.cs", "// D1")) in result["bindings"]
def test_untyped_rung_refuses_a_name_a_regular_method_uses():
result = graph_bindings("untyped_regular_name")
assert not any(marker == "// F1" for marker, _target in result["bindings"])
def test_untyped_rung_refuses_a_capitalized_type_receiver():
"""`Conv.ToInt32(x)` names a type; the extension must not be considered."""
result = graph_bindings("static_class_receiver")
assert ("// B1", ("E.cs", "// D2")) not in result["bindings"]
+109
View File
@@ -0,0 +1,109 @@
"""`graphify extract` frees its whole-graph intermediates without changing output.
The Python parse memo pinned every tree-sitter tree (and its node wrappers)
after AST extraction, and to_json kept copies of the old and new graphs alive
through the write. Releasing them early must not change a byte of graph.json.
"""
from __future__ import annotations
import json
import shutil
import networkx as nx
import pytest
import graphify.__main__ as mainmod
import graphify.export as export_mod
from graphify.export import to_json
# to_json output for _graph() below, as written before the memory changes.
EXPECTED_GRAPH_JSON = (
'{"directed":false,"multigraph":false,"graph":{"hyperedges":[{"id":"h1","nodes":["a","b","c"],'
'"relation":"group"}],"schema_version":1},"nodes":[{"id":"a","label":"A","community":0,'
'"file_type":"code","norm_label":"a","source_file":"a.py"},{"id":"b","label":"B","community":0,'
'"file_type":"code","norm_label":"b","source_file":"b.py"},{"id":"c","label":"C","community":1,'
'"file_type":"document","norm_label":"c","source_file":"c.md"}],"links":[{"source":"b",'
'"target":"a","relation":"calls","confidence":"EXTRACTED","confidence_score":1.0},'
'{"source":"b","target":"c","relation":"references","confidence":"INFERRED",'
'"confidence_score":0.55}],"hyperedges":[{"id":"h1","nodes":["a","b","c"],"relation":"group"}],'
'"built_at_commit":"abc"}'
)
def _graph(*, hyperedges: bool = True) -> nx.Graph:
G = nx.Graph()
# `id` stored inline on one node: canonicalization must still put it first.
G.add_node("b", label="B", file_type="code", source_file="b.py", id="b")
G.add_node("a", label="A", file_type="code", source_file="a.py")
G.add_node("c", label="C", file_type="document", source_file="c.md")
G.add_edge("a", "b", relation="calls", confidence="EXTRACTED", _src="b", _tgt="a")
G.add_edge("b", "c", relation="references", confidence="INFERRED")
if hyperedges:
G.graph["hyperedges"] = [{"id": "h1", "nodes": ["a", "b", "c"], "relation": "group"}]
return G
def test_to_json_bytes_unchanged_on_forced_and_guarded_writes(tmp_path, monkeypatch):
monkeypatch.setattr(export_mod, "_graphify_version", lambda: None)
communities = {0: ["a", "b"], 1: ["c"]}
forced = tmp_path / "forced.json"
assert to_json(_graph(), communities, str(forced), force=True, built_at_commit="abc")
assert forced.read_text(encoding="utf-8") == EXPECTED_GRAPH_JSON
# The guarded write parses the existing file and frees it before exporting.
guarded = tmp_path / "guarded.json"
shutil.copy(forced, guarded)
assert to_json(_graph(), communities, str(guarded), force=False, built_at_commit="abc")
assert guarded.read_bytes() == forced.read_bytes()
def test_to_json_hyperedge_wipe_warning_still_reads_previous_graph(tmp_path, capsys):
out = tmp_path / "graph.json"
to_json(_graph(), {0: ["a", "b", "c"]}, str(out), force=True, built_at_commit="abc")
assert to_json(_graph(hyperedges=False), {0: ["a", "b", "c"]}, str(out),
force=True, built_at_commit="abc")
assert "already holds 1 hyperedge(s)" in capsys.readouterr().err
assert json.loads(out.read_text(encoding="utf-8"))["hyperedges"] == []
def test_extract_cli_releases_python_parse_memo(tmp_path, monkeypatch):
pytest.importorskip("tree_sitter_python")
from graphify.extractors.resolution import _parse_python_tree_cached
corpus = tmp_path / "corpus"
corpus.mkdir()
(corpus / "a.py").write_text("def helper():\n return 1\n", encoding="utf-8")
(corpus / "b.py").write_text(
"from a import helper\n\ndef run():\n return helper()\n", encoding="utf-8"
)
out_dir = tmp_path / "out"
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
mainmod.sys, "argv",
["graphify", "extract", str(corpus), "--code-only", "--out", str(out_dir)],
)
_parse_python_tree_cached.cache_clear()
try:
mainmod.main()
except SystemExit as exc:
assert exc.code in (None, 0), f"unexpected exit code {exc.code}"
assert (out_dir / "graphify-out" / "graph.json").exists()
# Both resolution passes parse a.py and b.py through the memo; it must be
# empty once the command is done with it (it held 2 trees before).
assert _parse_python_tree_cached.cache_info().currsize == 0
@pytest.mark.parametrize("release", [False, True])
def test_extract_parse_memo_release_is_opt_in(tmp_path, release):
pytest.importorskip("tree_sitter_python")
from graphify.extract import extract
from graphify.extractors.resolution import _parse_python_tree_cached
(tmp_path / "a.py").write_text("def helper():\n return 1\n", encoding="utf-8")
(tmp_path / "b.py").write_text("from a import helper\n", encoding="utf-8")
_parse_python_tree_cached.cache_clear()
extract([tmp_path / "a.py", tmp_path / "b.py"], cache_root=tmp_path / "out",
root=tmp_path, release_parse_memo=release)
# Long-lived callers (watch, MCP) keep the memo warm for their next run.
assert _parse_python_tree_cached.cache_info().currsize == (0 if release else 2)
+19
View File
@@ -10,6 +10,7 @@ from graphify.file_slice import (
bisect_slice,
expand_oversized_files,
is_splittable_text,
make_full_slice,
read_slice_text,
slice_boundaries,
unit_path,
@@ -163,3 +164,21 @@ def test_bisect_slice_splits_at_newline(tmp_path):
def test_bisect_slice_returns_none_for_tiny(tmp_path):
f = _write(tmp_path / "a.md", "ab")
assert bisect_slice(FileSlice(f, 0, 1, 0, 1)) is None
def test_make_full_slice(tmp_path):
f_md = _write(tmp_path / "doc.md", "# Hello\n\nWorld\n")
fs = make_full_slice(f_md)
assert fs is not None
assert fs.path == f_md
assert fs.start == 0
assert fs.end == len(f_md.read_text(encoding="utf-8"))
assert fs.index == 0
assert fs.total == 1
f_py = _write(tmp_path / "code.py", "x = 1\n")
assert make_full_slice(f_py) is None
f_none = tmp_path / "nonexistent.md"
assert make_full_slice(f_none) is None
+52
View File
@@ -66,6 +66,58 @@ def test_same_size_rewrite_in_one_tick_is_requeued(corpus):
assert queued[0].endswith("f1.md")
def test_a_row_stamped_just_before_the_mtime_still_hashes(corpus):
"""`seen` from time.time() can land a few hundred ns BEFORE the mtime (#5036).
Both clocks describe the same write, so the old `seen - mtime < 0 -> trust
stat` shortcut skipped the hash on a row that could still hide a rewrite.
The delta is only meaningful as a magnitude: anything inside the tick is
unprovable in either direction.
"""
import json
src, manifest = corpus
det.save_manifest(det.detect(src)["files"], manifest, root=src, kind="semantic")
rows = json.loads(Path(manifest).read_text(encoding="utf-8"))
for row in rows.values():
row["seen"] = row["mtime"] - 0.000001 # ~1 us before the stamp
Path(manifest).write_text(json.dumps(rows), encoding="utf-8")
target = src / "f1.md"
stat_before = target.stat()
target.write_text("# Doc 2\n\nA substantially longer body than before.\n", encoding="utf-8")
os.utime(target, ns=(stat_before.st_atime_ns, stat_before.st_mtime_ns))
assert target.stat().st_mtime_ns == stat_before.st_mtime_ns
queued = _queued(det.detect_incremental(src, manifest, kind="semantic"))
assert len(queued) == 1 and queued[0].endswith("f1.md")
def test_a_row_stamped_well_before_the_mtime_keeps_the_fastpath(corpus, monkeypatch):
"""Control for the fix: a window-old row is from an earlier run, not a tick."""
import json
src, manifest = corpus
det.save_manifest(det.detect(src)["files"], manifest, root=src, kind="semantic")
rows = json.loads(Path(manifest).read_text(encoding="utf-8"))
for row in rows.values():
row["seen"] = row["mtime"] - 3600 # an hour before; a later write moved mtime
Path(manifest).write_text(json.dumps(rows), encoding="utf-8")
calls = {"n": 0}
real = det._md5_file
def counting(p):
calls["n"] += 1
return real(p)
monkeypatch.setattr(det, "_md5_file", counting)
result = det.detect_incremental(src, manifest, kind="semantic")
assert _queued(result) == []
assert calls["n"] == 0, "a row from an earlier run must not be re-hashed"
def test_a_settled_corpus_costs_no_content_hashes(corpus, monkeypatch):
"""The fastpath must survive: an untouched corpus does zero MD5 work."""
src, manifest = corpus
+50
View File
@@ -0,0 +1,50 @@
"""#5034: a constructor reached through a destructured require of a CommonJS
barrel must resolve to the class in the module the barrel re-exports.
`const { SourceCode } = require('./index')` where `index.js` does
`const SourceCode = require('./source'); module.exports = { SourceCode }`
used to leave the call's reference on the barrel, which defines nothing, so
the `calls` edge disappeared even though the direct-require case resolved.
"""
from __future__ import annotations
from pathlib import Path
from graphify.extract import extract
def test_constructor_call_resolves_through_destructured_barrel_require(tmp_path):
files = {
"source.js": "class SourceCode {}\nmodule.exports = SourceCode;\n",
"index.js": (
"const SourceCode = require('./source');\n"
"module.exports = { SourceCode };\n"
),
"consumer.js": (
"const { SourceCode } = require('./index');\n"
"function create() { return new SourceCode(); }\n"
),
}
for name, body in files.items():
(tmp_path / name).write_text(body, encoding="utf-8")
graph = extract(
[tmp_path / name for name in files],
cache_root=tmp_path / "cache",
root=tmp_path,
parallel=False,
)
nodes = {node["id"]: node for node in graph["nodes"]}
calls = [
(
nodes[edge["source"]]["label"],
nodes[edge["target"]]["label"],
Path(nodes[edge["target"]]["source_file"]).name,
)
for edge in graph["edges"]
if edge["relation"] == "calls"
and edge["source"] in nodes
and edge["target"] in nodes
]
assert ("create()", "SourceCode", "source.js") in calls, calls
+118
View File
@@ -1122,6 +1122,124 @@ def test_call_openai_compat_extra_body_wins_over_moonshot_default(monkeypatch):
assert captured["extra_body"] == {"thinking": {"type": "enabled"}}
# ---------------------------------------------------------------------------
# Custom-provider extra_headers (#3680): gateways such as OpenCode Go reject a
# request without their own header (x-opencode-session). providers.json passes
# them to the OpenAI client as default_headers, at extraction and at _call_llm.
# ---------------------------------------------------------------------------
def _install_header_capturing_openai(monkeypatch):
"""Record the OpenAI client's constructor kwargs (where default_headers go)."""
import sys
import types
clients: list[dict] = []
class _FakeOpenAI:
def __init__(self, *_, **kwargs):
clients.append(kwargs)
self.chat = self
self.completions = self
def create(self, **_kwargs):
return _fake_openai_response(
'{"nodes":[{"id":"x"}],"edges":[],"hyperedges":[]}',
finish_reason="stop",
completion_tokens=100,
)
fake_module = types.ModuleType("openai")
setattr(fake_module, "OpenAI", _FakeOpenAI)
setattr(fake_module, "APIStatusError", _FakeAPIStatusError)
monkeypatch.setitem(sys.modules, "openai", fake_module)
return clients
def _register_header_provider(monkeypatch, extra_headers):
monkeypatch.setattr(llm, "_get_backend_api_key", lambda _backend: "go-key")
monkeypatch.setitem(
llm.BACKENDS,
"opencode-go",
{
"base_url": "https://opencode.ai/zen/go/v1",
"default_model": "deepseek-v4-flash",
"env_key": "OPENCODE_API_KEY",
"pricing": {"input": 0.0, "output": 0.0},
"temperature": 0,
"extra_headers": extra_headers,
},
)
def test_call_openai_compat_passes_extra_headers_as_default_headers(monkeypatch):
clients = _install_header_capturing_openai(monkeypatch)
llm._call_openai_compat(
"https://opencode.ai/zen/go/v1", "go-key", "deepseek-v4-flash",
"u", temperature=0, max_completion_tokens=8192, backend="opencode-go",
extra_headers={"x-opencode-session": "s-1"},
)
assert clients[-1]["default_headers"] == {"x-opencode-session": "s-1"}
def test_call_openai_compat_without_extra_headers_sets_no_default_headers(monkeypatch):
clients = _install_header_capturing_openai(monkeypatch)
llm._call_openai_compat(
"https://api.moonshot.ai/v1", "tk", "kimi-k2",
"u", temperature=0, max_completion_tokens=8192, backend="kimi",
)
assert "default_headers" not in clients[-1]
def test_extraction_forwards_provider_extra_headers(monkeypatch, tmp_path):
clients = _install_header_capturing_openai(monkeypatch)
_register_header_provider(monkeypatch, {"x-opencode-session": "s-1", "User-Agent": "my-agent/1.0"})
doc = tmp_path / "a.md"
doc.write_text("# A\n", encoding="utf-8")
llm.extract_files_direct([doc], backend="opencode-go", root=tmp_path)
assert clients[-1]["default_headers"] == {"x-opencode-session": "s-1", "User-Agent": "my-agent/1.0"}
def test_call_llm_forwards_provider_extra_headers(monkeypatch):
clients = _install_header_capturing_openai(monkeypatch)
_register_header_provider(monkeypatch, {"x-opencode-session": "s-1"})
llm._call_llm("label this", backend="opencode-go")
assert clients[-1]["default_headers"] == {"x-opencode-session": "s-1"}
def test_provider_extra_headers_cannot_override_authorization(monkeypatch, capsys):
"""The key always comes from env_key; a providers.json header must not swap it."""
clients = _install_header_capturing_openai(monkeypatch)
_register_header_provider(
monkeypatch,
{"Authorization": "Bearer other", "x-opencode-session": "s-1", "x-bad": 7},
)
llm._call_llm("label this", backend="opencode-go")
assert clients[-1]["default_headers"] == {"x-opencode-session": "s-1"}
err = capsys.readouterr().err
assert "cannot set Authorization" in err and "'x-bad'" in err
@pytest.mark.parametrize("raw", [None, {}, "x-opencode-session: s-1", {"Authorization": "Bearer x"}])
def test_provider_extra_headers_unusable_values_send_no_default_headers(monkeypatch, raw):
clients = _install_header_capturing_openai(monkeypatch)
_register_header_provider(monkeypatch, raw)
llm._call_llm("label this", backend="opencode-go")
assert "default_headers" not in clients[-1]
# ---------------------------------------------------------------------------
# GRAPHIFY_DISABLE_THINKING: opt-in disable-thinking for reasoning models like
# deepseek-v4-flash. Off by default — disabling thinking trades a rare reasoning
+578 -6
View File
@@ -10,12 +10,33 @@ from __future__ import annotations
import json
import os
import subprocess
import sys
import textwrap
from pathlib import Path
from graphify.extract import extract
from graphify.extractors.markdown import _code_span_mention, extract_markdown
from graphify.markdown_resolution import _match_cited_file
def _run_isolated(script: str, *args: str) -> subprocess.CompletedProcess:
"""Run *script* in a fresh interpreter so in-process global state cannot leak in.
``_rebuild_code`` touches module-level globals: the cache stat index
(#3989) and the active scan root. In the full suite a prior test's root
can be served to a later rebuild, dropping resolver-minted markdown
reference edges. A subprocess starts from a clean slate, matching the
isolated run the test sees when executed on its own.
"""
repo_root = Path(__file__).resolve().parent.parent
return subprocess.run(
[sys.executable, "-c", textwrap.dedent(script), *args],
cwd=str(repo_root),
capture_output=True,
text=True,
)
_WIDGET_PY = '''\
class Widget:
def render(self):
@@ -97,13 +118,23 @@ def test_code_span_mentions_are_classified():
None, ["App", "Services", "Mailer"])
assert _code_span_mention("Mailer::send") == (None, ["Mailer", "send"])
assert _code_span_mention("Mailer::send()") == (None, ["Mailer", "send"])
assert _code_span_mention("App\\Services\\DB") == (None, ["App", "Services", "DB"])
assert _code_span_mention("App\\API") == (None, ["App", "API"])
assert _code_span_mention("Http::GET()") == (None, ["Http", "GET"])
# `Foo::CONST` and `Foo::class` have no node to land on, and a bare
# namespace root (`App\`) names no symbol at all.
for span in ("Foo::CONST", "Foo::class", "App\\", "C:\\Users\\me"):
assert _code_span_mention(span) is None, span
# Files, commands, expressions and prose are not symbol mentions.
for span in ("setup.py", "README.md", "notes.txt", "git revert", "x = 1", "a-b",
"--flag", "", "src/widget.py"):
# A source-file span classifies with an empty symbol chain, so resolution
# can record it as file evidence (#4804).
assert _code_span_mention("setup.py") == ("setup.py", [])
assert _code_span_mention("src/widget.py") == ("src/widget.py", [])
# A *document* span is not evidence (only code files are), so it is not a
# mention at all.
assert _code_span_mention("README.md") is None
assert _code_span_mention("docs/notes.mdx") is None
# Commands, expressions and prose are not symbol mentions.
for span in ("git revert", "x = 1", "a-b", "--flag", ""):
assert _code_span_mention(span) is None, span
@@ -358,11 +389,39 @@ def test_bare_method_with_parentheses_still_resolves(tmp_path):
assert (notes["id"], method["id"]) in _references(r)
def test_bare_function_mention_still_resolves_without_its_owner(tmp_path):
"""The extra owner test is scoped to methods; a free function label stays evidence (#4609)."""
def test_bare_lowercase_word_does_not_link_to_an_unrelated_function(tmp_path):
"""`token` the query parameter is prose, not a reference to token() in an unrelated JS file (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) {\n return name;\n}\n",
"docs/feed.md": "# Quote feed\n\nThe client sends the API key as the `token` query parameter.\n",
})
feed = _node(r, "Quote feed")
assert {t for (s, t) in _references(r) if s == feed["id"]} == set()
def test_bare_function_mention_survives_when_the_document_cites_another_symbol_from_its_file(tmp_path):
"""`token` next to `palette()` from the same file is a real reference (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"docs/feed.md": "# Quote feed\n\nWalks through charts, mentions `palette()` and then `token`.\n",
})
feed = _node(r, "Quote feed")
token = _node(r, "token()", "charts.js")
palette = _node(r, "palette()", "charts.js")
assert (feed["id"], token["id"]) in _references(r)
assert (feed["id"], palette["id"]) in _references(r)
def test_bare_function_with_parentheses_still_resolves(tmp_path):
"""A trailing () is explicit evidence, so defining file does not need another symbol cited (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "def deploy():\n pass\n",
"notes.md": "# Notes\n\nRun `deploy` after the tests.\n",
"notes.md": "# Notes\n\nRun `deploy()` after the tests.\n",
})
notes = _node(r, "Notes")
@@ -370,6 +429,33 @@ def test_bare_function_mention_still_resolves_without_its_owner(tmp_path):
assert (notes["id"], deploy["id"]) in _references(r)
def test_bare_function_survives_when_a_class_in_its_file_is_cited(tmp_path):
"""`deploy` next to `Deployer` in the same file is a real reference (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "class Deployer:\n pass\n\ndef deploy():\n pass\n",
"notes.md": "# Notes\n\nUse `Deployer` then run `deploy`.\n",
})
notes = _node(r, "Notes")
deploy = _node(r, "deploy()", "deploy.py")
assert (notes["id"], deploy["id"]) in _references(r)
def test_function_evidence_cited_in_another_document_does_not_count(tmp_path):
"""The file-symbol evidence is per document: one doc's mention cannot license another's (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"a.md": "# A\n\nUses `palette()`.\n",
"b.md": "# B\n\nSends `token`.\n",
})
b = _node(r, "B")
assert {t for (s, t) in _references(r) if s == b["id"]} == set()
def test_owner_cited_in_another_document_does_not_count(tmp_path):
"""The owner evidence is per document: one doc's mention cannot license another's (#4609)."""
r = _extract(tmp_path, {
@@ -442,3 +528,489 @@ def test_dotted_mention_resolves_when_method_name_is_a_builtin(tmp_path):
# The builtin-named `.open()` must resolve just like `.connect()`.
assert repo_open["id"] in cited
assert repo_connect["id"] in cited
def test_bare_function_survives_when_file_is_cited(tmp_path):
"""Naming the defining file (span or link) licenses a bare function (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/span.md": "# Span\n\n- `web/charts.js` — uses `token` to read styles.\n",
"docs/link.md": "# Link\n\nSee [charts](../web/charts.js). Uses `token`.\n",
})
token = _node(r, "token()", "charts.js")
span_node = _node(r, "Span")
link_node = _node(r, "Link")
refs = _references(r)
assert (span_node["id"], token["id"]) in refs
assert (link_node["id"], token["id"]) in refs
def test_two_bare_functions_from_one_file_with_no_other_citation_yield_no_edge(tmp_path):
"""Two bare prose-like names cannot circularly license each other without evidence (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"notes.md": "# Notes\n\nCalls `palette` then `token`.\n",
})
notes = _node(r, "Notes")
assert {t for (s, t) in _references(r) if s == notes["id"]} == set()
def test_bare_function_resolves_when_class_is_cited_after_it_in_document(tmp_path):
"""Pass 2a/2c ordering ensures license is document-scoped, not reading-order dependent (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "class Deployer:\n pass\n\ndef deploy():\n pass\n",
"notes.md": "# Notes\n\nRun `deploy` first. Then use `Deployer`.\n",
})
notes = _node(r, "Notes")
deploy = _node(r, "deploy()", "deploy.py")
deployer = _node(r, "Deployer", "deploy.py")
refs = _references(r)
assert (notes["id"], deploy["id"]) in refs
assert (notes["id"], deployer["id"]) in refs
def test_bare_function_survives_with_path_qualified_evidence(tmp_path):
"""A path-qualified class citation licenses a bare function from that file (#4804)."""
r = _extract(tmp_path, {
"deploy.py": "class Deployer:\n pass\n\ndef deploy():\n pass\n",
"notes.md": "# Notes\n\nSee `deploy.py::Deployer`. Then run `deploy`.\n",
})
notes = _node(r, "Notes")
deploy = _node(r, "deploy()", "deploy.py")
assert (notes["id"], deploy["id"]) in _references(r)
def test_target_with_no_source_file_is_safely_skipped():
"""A callable target without a source_file sentinel is skipped without error (#4804)."""
from graphify.markdown_resolution import resolve_markdown_mentions
per_file = [{"raw_calls": [
{"caller_nid": "doc_notes", "callee": "sourceless", "language": "markdown",
"context": "sourceless", "source_file": "notes.md", "source_location": "L1"},
]}]
nodes = [
{"id": "doc_notes", "label": "Notes", "file_type": "document", "source_file": "notes.md"},
{"id": "code_sourceless", "label": "sourceless()", "file_type": "code",
"_callable": True, "source_file": ""},
]
edges: list[dict] = []
resolve_markdown_mentions(per_file, nodes, edges)
assert not [e for e in edges if e.get("relation") == "references"]
def test_nested_class_resolves_standalone(tmp_path):
"""A nested class is a class, not a method; it resolves without outer class cited (#4804)."""
r = _extract(tmp_path, {
"tree.py": "class Outer:\n class Inner:\n pass\n",
"notes.md": "# Notes\n\nUse `Inner`.\n",
})
notes = _node(r, "Notes")
inner = _node(r, "Inner", "tree.py")
assert (notes["id"], inner["id"]) in _references(r)
def test_bare_function_with_snake_case_or_camel_case_resolves_without_file_citation(tmp_path):
"""Distinct code identifiers (snake_case or camelCase) resolve standalone (#4804)."""
r = _extract(tmp_path, {
"build.py": (
"def deduplicate_by_label():\n pass\n\n"
"def buildFromJson():\n pass\n"
),
"notes.md": (
"# Notes\n\n"
"Calls `deduplicate_by_label` and `buildFromJson`.\n"
),
})
notes = _node(r, "Notes")
dedup = _node(r, "deduplicate_by_label()", "build.py")
build_json = _node(r, "buildFromJson()", "build.py")
refs = _references(r)
assert (notes["id"], dedup["id"]) in refs
assert (notes["id"], build_json["id"]) in refs
def test_bare_function_mention_survives_when_symbol_itself_cited_with_parentheses(tmp_path):
"""An explicit () mention under h1 licenses a bare mention under h2 (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function palette() { return 'dark'; }\n",
"docs/guide.md": (
"# Overview\n\n"
"Call `palette()` to configure theme.\n\n"
"## Details\n\n"
"Reads `palette` for current colors.\n"
),
})
overview = _node(r, "Overview")
details = _node(r, "Details")
palette = _node(r, "palette()", "charts.js")
refs = _references(r)
assert (overview["id"], palette["id"]) in refs
assert (details["id"], palette["id"]) in refs
def test_link_to_scanned_source_file_is_a_reference_and_licenses_bare_mentions(tmp_path):
"""A link to a scanned source file is a doc->file edge AND licenses a bare mention (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": "# Guide\n\nSee [charts](../web/charts.js). Sends `token`.\n",
})
guide = _node(r, "Guide")
token = _node(r, "token()", "charts.js")
charts_file = _node(r, "charts.js", "charts.js")
page = _node(r, "guide.md")
refs = _references(r)
assert (guide["id"], token["id"]) in refs
# The link itself is a real reference from the page to the scanned file
# node — EXTRACTED, since the document names the file verbatim.
assert refs[(page["id"], charts_file["id"])]["confidence"] == "EXTRACTED"
def test_extract_markdown_records_a_source_file_link_as_a_citation(tmp_path):
"""The citation rides the markdown raw-call channel with only `path`, so the
corpus-aware resolver can decide edge vs evidence-only (#4804)."""
doc = tmp_path / "docs" / "guide.md"
doc.parent.mkdir()
doc.write_text("# Guide\n\nSee [charts](../web/charts.js) and `token`.\n")
r = extract_markdown(doc)
assert all(e["relation"] == "contains" for e in r["edges"])
page = next(n for n in r["nodes"] if n.get("node_kind") == "page")
citations = [rc for rc in r["raw_calls"] if rc["callee"] == "" and rc.get("path")]
assert [(rc["caller_nid"], rc["path"]) for rc in citations] == [
(page["id"], "../web/charts.js")]
assert all(rc.get("file_link") for rc in citations)
# The symbol mention still travels as a normal markdown raw call.
assert [rc["callee"] for rc in r["raw_calls"] if rc.get("path") is None] == ["token"]
def test_link_to_unscanned_source_file_yields_no_edge_or_phantom(tmp_path):
"""A link to a source file outside the corpus is evidence only, never a dangling edge."""
outside = tmp_path / "outside" / "script.py"
outside.parent.mkdir()
outside.write_text("def run():\n pass\n")
r = _extract(tmp_path, {"docs/guide.md": "# Guide\n\nSee [script](../outside/script.py).\n"})
assert r["edges"] == [e for e in r["edges"] if e["relation"] == "contains"]
def test_wikilink_to_scanned_source_file_yields_only_a_file_edge(tmp_path):
"""An Obsidian wikilink naming a scanned source file is a page->file reference."""
r = _extract(tmp_path, {
"setup.py": "def setup():\n pass\n",
"docs/guide.md": "# Guide\n\nSee [[setup.py]].\n",
})
page = _node(r, "guide.md")
setup_file = _node(r, "setup.py", "setup.py")
assert set(_references(r)) == {(page["id"], setup_file["id"])}
def test_single_word_pascal_case_function_resolves_standalone(tmp_path):
"""An exported Go/C#/Swift entry point (`Serve`) is a distinct identifier, not prose (#4804)."""
r = _extract(tmp_path, {
"worker.go": "package worker\n\nfunc Serve() {}\n",
"docs/guide.md": "# Guide\n\n`Serve` starts the server.\n",
})
guide = _node(r, "Guide")
serve = _node(r, "Serve()", "worker.go")
assert (guide["id"], serve["id"]) in _references(r)
def test_single_word_lowercase_function_still_needs_evidence(tmp_path):
"""The PascalCase exemption does not loosen the prose-like test (`serve`)."""
r = _extract(tmp_path, {
"worker.go": "package worker\n\nfunc serve() {}\n",
"docs/guide.md": "# Guide\n\n`serve` starts the server.\n",
})
guide = _node(r, "Guide")
assert {t for (s, t) in _references(r) if s == guide["id"]} == set()
def test_file_citation_evidence_survives_a_rebuild(tmp_path):
"""A source-file link's citation comes from the cached fragment, so a rebuild keeps the edge.
Runs in a subprocess: ``_rebuild_code`` shares the cache stat index and the
active scan root as process globals, and a prior test in the full suite can
leave a root bound that makes a partial rebuild drop the reference edges.
A fresh interpreter gives the test the same clean slate it has in isolation.
"""
corpus = tmp_path / "corpus"
(corpus / "docs").mkdir(parents=True)
(corpus / "web").mkdir()
(corpus / "web" / "charts.js").write_text(
"export function token(name) { return name; }\n")
doc = corpus / "docs" / "guide.md"
doc.write_text("# Guide\n\nSee [charts](../web/charts.js). Sends `token`.\n")
result_file = tmp_path / "result.json"
script = '''
import json, sys
from pathlib import Path
from graphify.watch import _rebuild_code
corpus = Path(sys.argv[1])
result_file = Path(sys.argv[2])
doc = corpus / "docs" / "guide.md"
charts = corpus / "web" / "charts.js"
graph_path = corpus / "graphify-out" / "graph.json"
def reference_edges():
links = json.loads(graph_path.read_text(encoding="utf-8"))["links"]
return sorted((e["source"], e["target"]) for e in links
if e.get("relation") == "references")
assert _rebuild_code(corpus, no_cluster=True, acquire_lock=False) is True
first = reference_edges()
doc.write_text(doc.read_text() + "\\nStill `token`.\\n")
assert _rebuild_code(corpus, changed_paths=[doc], no_cluster=True,
acquire_lock=False) is True
second = reference_edges()
charts.write_text(
"export function token(name) { return name; }\\n"
"export function palette() { return 'dark'; }\\n")
assert _rebuild_code(corpus, changed_paths=[charts], no_cluster=True,
acquire_lock=False) is True
third = reference_edges()
result_file.write_text(
json.dumps({"first": first, "second": second, "third": third}),
encoding="utf-8")
'''
completed = _run_isolated(script, str(corpus), str(result_file))
assert completed.returncode == 0, completed.stderr[-2000:]
payload = json.loads(result_file.read_text(encoding="utf-8"))
expected = payload["first"]
# Two edges: the doc->file link reference and the licensed mention edge.
assert len(expected) == 2
assert payload["second"] == expected, "document re-extracted"
assert payload["third"] == expected, "code re-extracted"
def test_bare_function_mention_in_a_sibling_section_needs_its_own_evidence(tmp_path):
"""Evidence is section-scoped: a citation in one h1 does not license a sibling h1 (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"docs/guide.md": (
"# Charts\n\n"
"`palette()` configures the theme.\n\n"
"# Token notes\n\n"
"The API key travels as the `token` query parameter.\n"
),
})
token_notes = _node(r, "Token notes")
charts = _node(r, "Charts")
token = _node(r, "token()", "charts.js")
palette = _node(r, "palette()", "charts.js")
refs = _references(r)
# The explicit () citation resolves on its own.
assert (charts["id"], palette["id"]) in refs
# The sibling section's prose word gets no license from it...
assert {t for (s, t) in refs if s == token_notes["id"]} == set()
# ...but a nested section would: evidence at h1 licenses its h2 children.
r = _extract(tmp_path, {
"web/charts.js": (
"export function palette() { return 'dark'; }\n"
"export function token(name) { return name; }\n"
),
"docs/guide.md": (
"# Charts\n\n"
"`palette()` configures the theme.\n\n"
"## Colors\n\n"
"Reads `palette` for the current scheme.\n"
),
})
colors = _node(r, "Colors")
assert (colors["id"], palette["id"]) in _references(r)
def test_pascal_case_in_a_lowercase_convention_language_needs_evidence(tmp_path):
"""`Token` in Python is prose as often as not; only PascalCase-export languages skip the test (#4804)."""
r = _extract(tmp_path, {
"build.py": "def Token():\n pass\n",
"notes.md": "# Notes\n\n`Token` builds the response.\n",
})
notes = _node(r, "Notes")
assert {t for (s, t) in _references(r) if s == notes["id"]} == set()
# With the defining file cited, the same mention resolves.
r = _extract(tmp_path, {
"build.py": "def Token():\n pass\n",
"notes.md": "# Notes\n\nSee `build.py`. `Token` builds the response.\n",
})
notes = _node(r, "Notes")
token = _node(r, "Token()", "build.py")
assert (notes["id"], token["id"]) in _references(r)
def test_file_span_is_evidence_but_not_a_doc_file_edge(tmp_path):
"""A source-file code span licenses bare mentions; only a link is a doc->file reference (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/span.md": "# Span\n\n- `web/charts.js` — uses `token` to read styles.\n",
})
span_node = _node(r, "Span")
token = _node(r, "token()", "charts.js")
refs = _references(r)
assert (span_node["id"], token["id"]) in refs
assert len(refs) == 1, "a span is evidence, not a link: no doc->file edge"
def test_cited_file_fallback_respects_explicit_relative_discipline():
"""The suffix fallback fires only under detected path-form mixing (#4804).
Runs in a subprocess so ``_active_scan_root()`` is None: the resolver's
fallback consults that process global, and a root leaked by an earlier test
would prefix-mismatch the synthetic ``/repo`` path and return None.
"""
script = '''
import json
from graphify.markdown_resolution import _match_cited_file_any_form
sources = {"web/charts.js"}
# Uniform path forms: an explicit ../ cite resolves against the citing
# document's directory only — even when the doc sits outside the corpus
# root and a corpus file shares the tail (#4804's discipline).
uniform = _match_cited_file_any_form(
"../web/charts.js", "/other/docs/guide.md", sources,
form_mismatch=False)
# An absolute citing document against a relative corpus is exactly the
# partial-rebuild mixing the fallback exists for.
mixed = _match_cited_file_any_form(
"../web/charts.js", "/repo/docs/guide.md", sources,
form_mismatch=True)
print("===RESULT===" + json.dumps({"uniform": uniform, "mixed": mixed}))
'''
completed = _run_isolated(script)
assert completed.returncode == 0, completed.stderr[-2000:]
line = next(l for l in completed.stdout.splitlines()
if l.startswith("===RESULT==="))
payload = json.loads(line[len("===RESULT==="):])
assert payload["uniform"] is None
assert payload["mixed"] == "web/charts.js"
def test_escaping_citation_does_not_match_in_corpus_file():
"""An explicit cite escaping the scan root does not match an in-corpus file."""
from graphify.markdown_resolution import _match_cited_file_any_form
sources = {"web/charts.js"}
assert _match_cited_file_any_form(
"../../outside/web/charts.js", "/repo/docs/guide.md", sources,
form_mismatch=True, scan_root="/repo",
) is None
def test_source_file_link_in_heading_does_not_license_sibling_heading(tmp_path):
"""A source-file link licenses mentions in its own section, not sibling sections."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": (
"# Charts\n\n"
"See [charts](../web/charts.js).\n\n"
"# Authentication\n\n"
"Sends `token` for auth.\n"
),
})
auth = _node(r, "Authentication")
token = _node(r, "token()", "charts.js")
assert (auth["id"], token["id"]) not in _references(r)
def test_missing_source_link_does_not_reference_other_files(tmp_path):
"""An inline Markdown link to a missing path does not fall back to unrelated files."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": "# Guide\n\nSee [charts](web/charts.js).\n",
})
page = _node(r, "guide.md")
charts_file = _node(r, "charts.js", "charts.js")
assert (page["id"], charts_file["id"]) not in _references(r)
def test_reference_style_use_licenses_its_own_section(tmp_path):
"""A reference-style use `[charts][source]` licenses a bare mention in its own section,
not the section where the definition sits (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": (
"# Charts\n\n"
"See [charts][source]. Uses `token`.\n\n"
"# Authentication\n\n"
"[source]: ../web/charts.js\n"
),
})
charts = _node(r, "Charts")
token = _node(r, "token()", "charts.js")
charts_file = _node(r, "charts.js", "charts.js")
page = _node(r, "guide.md")
refs = _references(r)
# The use's section licenses the bare mention.
assert (charts["id"], token["id"]) in refs
# The link itself is a doc->file edge from the page.
assert (page["id"], charts_file["id"]) in refs
def test_reference_definition_section_does_not_license_bare_mention(tmp_path):
"""A definition's own section does not inherit citation evidence from the
definition line (#4804 regression)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": (
"# Charts\n\n"
"Uses `token`.\n\n"
"# Authentication\n\n"
"Sends `token` for auth.\n\n"
"[source]: ../web/charts.js\n"
),
})
auth = _node(r, "Authentication")
token = _node(r, "token()", "charts.js")
assert (auth["id"], token["id"]) not in _references(r)
def test_reference_style_use_shared_by_multiple_sections(tmp_path):
"""Each use of a shared definition licenses its own section (#4804)."""
r = _extract(tmp_path, {
"web/charts.js": "export function token(name) { return name; }\n",
"docs/guide.md": (
"# Charts\n\n"
"See [charts][source]. Uses `token`.\n\n"
"# Token notes\n\n"
"Also [charts][source]. Sends `token`.\n\n"
"[source]: ../web/charts.js\n"
),
})
charts = _node(r, "Charts")
token_notes = _node(r, "Token notes")
token = _node(r, "token()", "charts.js")
refs = _references(r)
assert (charts["id"], token["id"]) in refs
assert (token_notes["id"], token["id"]) in refs
+51
View File
@@ -560,3 +560,54 @@ def test_path_scoped_endpoint_honors_file_qualifier(monkeypatch, tmp_path, capsy
gp = _cross_file_symbol_graph(tmp_path)
out = _run(monkeypatch, gp, "src/billing/route.ts::readRoute", "chargeCard", capsys)
assert "readRoute() --calls [EXTRACTED]--> chargeCard()" in out
def _no_such_node_graph(tmp_path):
"""#5079: `zzqqxx_no_such_symbol_9137` names nothing, but `no_such_symbol_helper()`
shares three of its `_`-split tokens and wins the score fallback, so `path` used
to print the helper's route and exit 0 while `explain` said "No node matching"."""
return _write_nodes(tmp_path, [
("src_a_ts", "a.ts", "src/a.ts", "L1"),
("src_a_ts_parse", "parse()", "src/a.ts", "L1"),
("src_b_ts", "b.ts", "src/b.ts", "L1"),
("src_b_ts_helper", "no_such_symbol_helper()", "src/b.ts", "L1"),
("src_b_ts_format", "format()", "src/b.ts", "L1"),
("src_c_ts", "c.ts", "src/c.ts", "L1"),
("src_c_ts_format", "format()", "src/c.ts", "L1"),
], [
("src_a_ts", "src_a_ts_parse", "contains"),
("src_a_ts_parse", "src_b_ts_helper", "calls"),
("src_b_ts", "src_b_ts_helper", "contains"),
("src_b_ts", "src_b_ts_format", "contains"),
("src_c_ts", "src_c_ts_format", "contains"),
("src_b_ts_helper", "src_b_ts_format", "calls"),
])
_NO_SUCH_NODE = "zzqqxx_no_such_symbol_9137"
def test_path_refuses_endpoint_that_names_no_node(monkeypatch, tmp_path, capsys):
"""An endpoint matching no node name at all must fail closed, like `explain`,
instead of routing from whichever node happened to share some tokens (#5079)."""
gp = _no_such_node_graph(tmp_path)
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(mainmod.sys, "argv",
["graphify", "path", _NO_SUCH_NODE, "src/b.ts::format()", "--graph", str(gp)])
with pytest.raises(SystemExit) as exc_info:
mainmod.main()
assert exc_info.value.code == EXIT_NOT_FOUND
captured = capsys.readouterr()
assert "Shortest path" not in captured.out
assert _NO_SUCH_NODE in captured.err
assert "no_such_symbol_helper" not in captured.out
def test_shortest_path_tool_refuses_endpoint_that_names_no_node(tmp_path):
"""The MCP tool shares the resolver, so a bare name it cannot place is a miss too."""
from graphify.serve import _shortest_path_text
raw = json.loads(_no_such_node_graph(tmp_path).read_text())
G = json_graph.node_link_graph(raw, edges="links")
out = _shortest_path_text(G, {"source": _NO_SUCH_NODE, "target": "src/b.ts::format()"})
assert "Shortest path" not in out
assert f"No node matching source '{_NO_SUCH_NODE}' found." in out
+84
View File
@@ -2166,3 +2166,87 @@ def test_an_exact_spelling_does_not_break_a_tie_between_two_files():
nid, err = _resolve_single_node(G, "CheckHealth")
assert nid is None
assert err.startswith("Ambiguous:"), err
# --- schema/namespace-qualified labels (#5080) ---
def _qualified_graph() -> nx.Graph:
"""A SQL function behind a schema prefix, plus nodes whose whole label is one query token."""
G = nx.Graph()
for i in range(4):
G.add_node(f"migrations/04{i}_widget_sweep.sql::public.sweep_widget_state()",
label="public.sweep_widget_state()", norm_label="public.sweep_widget_state()",
source_file=f"migrations/04{i}_widget_sweep.sql", community=0)
G.add_node("consts_sweep", label="SWEEP", norm_label="sweep", source_file="src/consts.py", community=0)
G.add_node("consts_widget", label="WIDGET", norm_label="widget", source_file="src/consts.py", community=0)
G.add_node("types_state", label="State", norm_label="state", source_file="src/types.py", community=0)
for i in range(6):
G.add_node(f"noise_{i}", label=f"unrelated_{i}", source_file=f"src/noise{i}.py", community=1)
return G
def test_qualified_label_beats_a_whole_label_token_collision():
"""`query sweep_widget_state` must seed on `public.sweep_widget_state()` (#5080).
Every one of `SWEEP`, `WIDGET` and `State` exactly equals a query token while
the function only prefix/substring-matches them, so without the qualified
tier the three collisions take the seed slots and the function never gets
traversed — whereas `explain sweep_widget_state` lists it. The user does not
type the schema, so the qualifier cannot be part of the match.
"""
G = _qualified_graph()
scored = _score_nodes(G, ["sweep_widget_state"])
target = "migrations/040_widget_sweep.sql::public.sweep_widget_state()"
assert scored[0][1] == target
# All four migrations define the same function, so they tie; what matters is
# that the collisions come after them rather than taking the seed slots.
assert all(nid.startswith("migrations/") for _s, nid in scored[:4])
assert scored[4][0] < scored[0][0], "the qualified match must strictly outrank the token collisions"
text = _query_graph_text(G, "sweep_widget_state", token_budget=4000)
assert "public.sweep_widget_state()" in text
@pytest.mark.parametrize("question", ["public.sweep_widget_state", "public.sweep_widget_state()"])
def test_typing_the_qualifier_still_works(question):
"""Pinning the qualifier keeps resolving — and lands on the exact tier, not the qualified one."""
G = _qualified_graph()
scored = _score_nodes(G, [question])
assert scored[0][1].startswith("migrations/040_widget_sweep.sql::public.sweep_widget_state()")
assert _find_node(G, question)
def test_qualified_tier_stays_below_an_exact_label():
"""A label equal to the query always wins over a qualified label ending in it."""
G = nx.Graph()
G.add_node("qualified", label="public.sweep()", norm_label="public.sweep()", source_file="m.sql", community=0)
G.add_node("plain", label="sweep", norm_label="sweep", source_file="s.py", community=0)
scored = _score_nodes(G, ["sweep"])
assert scored[0][1] == "plain"
def test_qualified_tier_ignores_a_partial_tail():
"""Only a tail equal to the whole query counts; a longer tail must not."""
G = nx.Graph()
G.add_node("long", label="public.sweep_state_machine()", norm_label="public.sweep_state_machine()",
source_file="m.sql", community=0)
G.add_node("other", label="sweep", norm_label="sweep", source_file="s.py", community=0)
by_id = {nid: s for s, nid in _score_nodes(G, ["sweep"])}
assert by_id["other"] > 0
assert by_id["long"] < by_id["other"]
def test_qualified_tail_split():
from graphify.serve import _qualified_tail
assert _qualified_tail("public.sweep_widget_state()") == (1, "sweep widget state")
assert _qualified_tail("Index.ClientLive") == (1, "clientlive")
assert _qualified_tail("fmt.Println") == (1, "println")
assert _qualified_tail("Widget::sweep") == (1, "sweep")
# Not names: file extensions, numbers, plain snake_case.
assert _qualified_tail("lib/foo/bar.py") == (2, "bar")
assert _qualified_tail("3.14") is None
assert _qualified_tail("HTTPClient") is None
assert _qualified_tail("sweep_widget_state") is None
assert _qualified_tail("") is None
+131
View File
@@ -0,0 +1,131 @@
"""to_json's lost-node check excuses sources build_merge replaced or pruned.
LLM extraction is not id-stable: re-extracting an edited doc gives its
semantic nodes new ids. build_merge drops the old ones on purpose, so the
#479 write guard must not count them as lost. Nodes of files this run did not
touch, and files with an unverified shrink (#3203), stay guarded.
"""
from __future__ import annotations
import json
from pathlib import Path
import graphify.__main__ as mainmod
import graphify.llm as llmmod
from graphify.build import build_merge
from graphify.export import to_json
def _sem(sf: str, name: str) -> dict:
stem = sf.replace(".", "_")
return {"id": f"{stem}_{name}", "label": f"{sf} {name}",
"file_type": "document", "source_file": sf}
def _write_graph(gp: Path, nodes) -> None:
gp.parent.mkdir(parents=True, exist_ok=True)
gp.write_text(json.dumps({"nodes": list(nodes), "edges": [], "hyperedges": []}),
encoding="utf-8")
def _saved(tmp_path: Path) -> Path:
gp = tmp_path / "graphify-out" / "graph.json"
_write_graph(gp, [_sem("a.md", f"old{i}") for i in range(2)]
+ [_sem("b.md", f"b{i}") for i in range(3)])
return gp
def _ids(gp: Path) -> set[str]:
return {n["id"] for n in json.loads(gp.read_text(encoding="utf-8"))["nodes"]}
def test_reextracted_source_with_new_ids_is_not_lost(tmp_path):
gp = _saved(tmp_path)
chunk = {"nodes": [_sem("a.md", f"new{i}") for i in range(2)], "edges": []}
G = build_merge([chunk], gp, dedup=False, root=tmp_path)
assert to_json(G, {0: list(G.nodes)}, str(gp), force=False) is True
assert _ids(gp) == {"a_md_new0", "a_md_new1", "b_md_b0", "b_md_b1", "b_md_b2"}
assert "_replaced_sources" not in json.loads(gp.read_text(encoding="utf-8")).get("graph", {})
def test_pruned_source_is_not_lost(tmp_path, capsys):
gp = _saved(tmp_path)
G = build_merge([{"nodes": [], "edges": []}], gp, prune_sources=["b.md"],
dedup=False, root=tmp_path)
# The separate node-count check may still refuse a net shrink; only the
# lost-id check is under test here.
to_json(G, {0: list(G.nodes)}, str(gp), force=False)
assert "saved semantic node(s) are missing" not in capsys.readouterr().err
def test_untouched_source_loss_still_refused(tmp_path, capsys):
gp = _saved(tmp_path)
chunk = {"nodes": [_sem("a.md", f"new{i}") for i in range(2)], "edges": []}
G = build_merge([chunk], gp, dedup=False, root=tmp_path)
G.remove_node("b_md_b1") # b.md was neither re-extracted nor pruned
assert to_json(G, {0: list(G.nodes)}, str(gp), force=False) is False
err = capsys.readouterr().err
assert "b_md_b1" in err and "a_md_old0" not in err
def test_unverified_shrink_source_still_refused(tmp_path, capsys):
gp = _saved(tmp_path)
chunk = {"nodes": [_sem("a.md", "new0"), _sem("a.md", "new1"), _sem("b.md", "b0")],
"edges": []}
G = build_merge([chunk], gp, dedup=False, root=tmp_path)
assert G.graph["_unverified_semantic_shrink"] == {"b.md": (3, 1)}
assert to_json(G, {0: list(G.nodes)}, str(gp), force=False) is False
err = capsys.readouterr().err
assert "b_md_b1" in err and "a_md_old0" not in err
def _run_cli():
try:
mainmod.main()
except SystemExit as exc:
return exc.code
return 0
def _llm(nodes, uncovered=()):
def run(files, **kwargs):
res = {"nodes": nodes, "edges": [], "hyperedges": [], "input_tokens": 1,
"output_tokens": 1, "uncovered_files": list(uncovered)}
if kwargs.get("on_chunk_done"):
kwargs["on_chunk_done"](0, 1, res)
return res
return run
def test_extract_edit_with_new_ids_and_omitted_file_writes(tmp_path, monkeypatch):
"""Edited README comes back with new ids while GUIDE is omitted by the model.
The omission arms the guard, but GUIDE's saved nodes are kept and README
was re-extracted, so nothing is lost and the write must go through.
"""
corpus = tmp_path / "repo"
corpus.mkdir()
(corpus / "README.md").write_text("# Readme\nv1\n", encoding="utf-8")
(corpus / "GUIDE.md").write_text("# Guide\nv1\n", encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-fake")
argv = ["graphify", "extract", str(corpus), "--backend", "claude"]
monkeypatch.setattr(mainmod.sys, "argv", argv)
monkeypatch.setattr(llmmod, "extract_corpus_parallel", _llm(
[_sem("README.md", "a"), _sem("README.md", "b"), _sem("GUIDE.md", "g")]))
assert _run_cli() == 0
(corpus / "README.md").write_text("# Readme\nv2\n", encoding="utf-8")
(corpus / "GUIDE.md").write_text("# Guide\nv2\n", encoding="utf-8")
monkeypatch.setattr(llmmod, "extract_corpus_parallel", _llm(
[_sem("README.md", "c"), _sem("README.md", "d")], uncovered=["GUIDE.md"]))
assert _run_cli() == 0
ids = _ids(corpus / "graphify-out" / "graph.json")
assert {"README_md_c", "README_md_d", "GUIDE_md_g"} <= ids
assert not ids & {"README_md_a", "README_md_b"}
+29 -5
View File
@@ -1201,9 +1201,9 @@ def _write_chunk(out_dir: Path, payload: dict) -> None:
def test_extraction_specs_demand_complete_reads_and_report_coverage():
"""Every host's subagent prompt states the Read cap and asks for coverage.
Both spec variants must carry it: the compact prompt ships to codex/claw/
kiro/pi, the verbose one everywhere else, so fixing only one leaves hosts
silently half-reading files.
Every spec variant must carry it: the compact prompt ships to codex, its
disk-writing twin to claw/kiro/pi, the verbose one everywhere else, so
fixing only one leaves hosts silently half-reading files.
"""
platforms = gen.load_platforms()
seen_variants = set()
@@ -1217,11 +1217,35 @@ def test_extraction_specs_demand_complete_reads_and_report_coverage():
assert "coverage" in spec, f"[{key}] the prompt never asks for a coverage report"
# The contract must be in the schema the subagent emits, not only the prose.
assert '"coverage":{' in spec, f"[{key}] the emitted schema carries no coverage field"
assert seen_variants == {"verbose", "compact"}, (
"this test must cover both spec variants, not just one"
assert seen_variants == {"verbose", "compact", "compact-disk"}, (
"this test must cover every spec variant, not just one"
)
def test_extraction_spec_writes_chunk_path_when_dispatch_passes_one():
"""A host whose dispatch substitutes CHUNK_PATH must get a spec that writes it.
claw/kiro/pi dispatch says "have it write the result to CHUNK_PATH", but
they used to ship the compact spec, which never named CHUNK_PATH — so a
subagent following the prompt verbatim returned JSON inline and Step B3
found no chunk file. Codex is the inverse: its workers return JSON and the
orchestrator writes the file, so its spec must not ask for a write.
"""
platforms = gen.load_platforms()
for key, platform in sorted(platforms.items()):
if platform.bucket != "split":
continue
core = _platform_artifacts(key)[0]
spec = _platform_artifacts(key)[1]["extraction-spec.md"]
if "CHUNK_PATH must be an **absolute** path" in core:
assert "and CHUNK_PATH)" in spec, f"[{key}] spec omits CHUNK_PATH from its substitutions"
assert spec.rstrip().endswith("CHUNK_PATH\n```"), (
f"[{key}] spec never tells the subagent to write its JSON to CHUNK_PATH"
)
if "return the JSON inline" in core:
assert "CHUNK_PATH" not in spec, f"[{key}] spec asks for a CHUNK_PATH the dispatch never passes"
def test_core_bounds_semantic_chunks_by_lines_as_well_as_file_count():
"""Step B1 caps a chunk by total lines, and long files get a chunk to themselves.
+8
View File
@@ -94,6 +94,14 @@ def test_build_tree_default_root_keeps_hierarchy():
assert "a.py" in names and "sub" in names
def test_build_tree_single_file_common_root_is_directory():
graph = _graph({"pkg/a.py": "func_a"})
tree = build_tree(graph)
assert tree["name"] == "pkg"
assert [c["name"] for c in tree["children"]] == ["a.py"]
assert [c["name"] for c in tree["children"][0]["children"]] == ["func_a"]
def _merged_graph(per_repo: dict[str, dict[str, str]]) -> dict:
"""Node-link graph shaped like a merge-graphs result: every node is
repo-tagged and keeps its repo-relative source_file."""
+147
View File
@@ -315,3 +315,150 @@ def test_3203_allow_partial_override_permits_intentional_reduction(tmp_path, mon
# With override, the 1-node graph is persisted
graph = json.loads((out_dir / "graph.json").read_text(encoding="utf-8"))
assert len(graph["nodes"]) == 1
# -- 3. #5083: the degraded cache entry must not pin the corpus forever --------
_PROMPT = llmmod._extraction_system(deep=False)
def _doc_result(sf: str, count: int, prefix: str) -> dict:
return {
"nodes": [
{
"id": f"{prefix}_{i}",
"label": f"{sf} {i}",
"file_type": "document",
"source_file": sf,
}
for i in range(count)
],
"edges": [],
"hyperedges": [],
"input_tokens": 10,
"output_tokens": 10,
"uncovered_files": [],
}
def _mock_extract(result: dict, calls: list):
def _run(files, **kwargs):
calls.append([str(f) for f in files])
on_chunk = kwargs.get("on_chunk_done")
if on_chunk:
on_chunk(0, 1, result)
return result
return _run
def _cache_entry(root: Path, path: Path) -> Path:
from graphify.cache import _resolve_prompt_fp, cache_dir, file_hash
fp = _resolve_prompt_fp(_PROMPT)
return cache_dir(root, "semantic", fp) / f"{file_hash(path, root)}.json"
def _clear_partial_flag(entry: Path) -> None:
"""Simulate an entry written by a graphify that predates this fix."""
data = json.loads(entry.read_text(encoding="utf-8"))
data.pop("partial", None)
entry.write_text(json.dumps(data), encoding="utf-8")
def _boot_corpus(tmp_path, monkeypatch, capsys, calls):
corpus = tmp_path / "repo"
corpus.mkdir()
readme = corpus / "README.md"
readme.write_text("# Readme\nInitial content\n", encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-fake")
monkeypatch.setattr(
llmmod, "extract_corpus_parallel", _mock_extract(_doc_result("README.md", 3, "readme_n"), calls)
)
monkeypatch.setattr(
mainmod.sys, "argv", ["graphify", "extract", str(corpus), "--backend", "claude"]
)
assert _run_cli() == 0
capsys.readouterr()
return corpus, readme
def test_5083_degraded_entry_is_marked_partial_and_next_run_reextracts(
tmp_path, monkeypatch, capsys
):
calls: list = []
corpus, readme = _boot_corpus(tmp_path, monkeypatch, capsys, calls)
out_dir = corpus / "graphify-out"
readme.write_text("# Readme\nEdited content\n", encoding="utf-8")
monkeypatch.setattr(
llmmod, "extract_corpus_parallel", _mock_extract(_doc_result("README.md", 1, "readme_doc"), calls)
)
assert _run_cli() == 1
err = capsys.readouterr().err
assert "unverified semantic shrink detected for 'README.md' (3 -> 1 nodes)" in err
assert "marked 1 semantic cache entry partial" in err
from graphify.cache import load_cached
assert load_cached(readme, root=corpus, kind="semantic", prompt=_PROMPT) is None
kept = load_cached(
readme, root=corpus, kind="semantic", prompt=_PROMPT, allow_partial=True
)
assert kept["partial"] is True
assert len(kept["nodes"]) == 1
# The graph on disk is untouched.
assert len(json.loads((out_dir / "graph.json").read_text(encoding="utf-8"))["nodes"]) == 3
# Next run: the partial entry is a MISS, so the model is consulted again and
# the healthy extraction lands instead of re-failing against the cache.
monkeypatch.setattr(
llmmod, "extract_corpus_parallel", _mock_extract(_doc_result("README.md", 24, "readme_h"), calls)
)
assert _run_cli() == 0
assert any(str(readme) in c for c in calls[-1])
assert len(json.loads((out_dir / "graph.json").read_text(encoding="utf-8"))["nodes"]) == 24
def test_5083_cached_degraded_replay_is_marked_and_does_not_advise_allow_partial(
tmp_path, monkeypatch, capsys
):
calls: list = []
corpus, readme = _boot_corpus(tmp_path, monkeypatch, capsys, calls)
readme.write_text("# Readme\nEdited content\n", encoding="utf-8")
monkeypatch.setattr(
llmmod, "extract_corpus_parallel", _mock_extract(_doc_result("README.md", 1, "readme_doc"), calls)
)
assert _run_cli() == 1
capsys.readouterr()
# Pretend the 1-node entry was written by a graphify that predates the fix:
# the shrink guard refuses, but nothing marks the entry, so the next run
# replays it without ever calling the model.
entry = _cache_entry(corpus, readme)
_clear_partial_flag(entry)
def _must_not_call(files, **kwargs): # pragma: no cover - must stay uncalled
raise AssertionError(f"a cached degraded replay must not call the model: {files}")
monkeypatch.setattr(llmmod, "extract_corpus_parallel", _must_not_call)
assert _run_cli() == 1
err = capsys.readouterr().err
assert "replayed from the semantic" in err
assert "Do NOT pass --allow-partial" in err
# No misleading "pass --allow-partial" advice for a cached replay.
assert "pass --allow-partial to overwrite a larger existing graph" not in err
assert "marked 1 semantic cache entry partial" in err
assert json.loads(entry.read_text(encoding="utf-8"))["partial"] is True
# Re-run now re-extracts and heals the graph.
monkeypatch.setattr(
llmmod, "extract_corpus_parallel", _mock_extract(_doc_result("README.md", 24, "readme_h"), calls)
)
assert _run_cli() == 0
assert any(str(readme) in c for c in calls[-1])
assert len(
json.loads((corpus / "graphify-out" / "graph.json").read_text(encoding="utf-8"))["nodes"]
) == 24
+46
View File
@@ -1,4 +1,5 @@
import pytest
from copy import deepcopy
from graphify.validate import validate_extraction, assert_valid
VALID = {
@@ -15,6 +16,51 @@ VALID = {
def test_valid_passes():
assert validate_extraction(VALID) == []
@pytest.mark.parametrize("value", [[], {}, ["code"], {"value": "code"}])
@pytest.mark.parametrize("collection,field", [("nodes", "file_type"), ("edges", "confidence")])
def test_structured_enum_values_reported_not_raised(collection, field, value):
data = deepcopy(VALID)
data[collection][0][field] = value
errors = validate_extraction(data)
assert any(f"invalid {field}" in error for error in errors)
with pytest.raises(ValueError, match=f"invalid {field}"):
assert_valid(data)
@pytest.mark.parametrize("value", [[], {}, ["code"], {"value": "code"}])
@pytest.mark.parametrize("entry_point", ["build", "build_from_json"])
def test_build_repairs_structured_enum_values(entry_point, value):
from graphify.build import build, build_from_json
data = deepcopy(VALID)
data["nodes"][0]["file_type"] = value
data["edges"][0]["confidence"] = value
graph = build([data]) if entry_point == "build" else build_from_json(data)
assert graph.number_of_nodes() == 2
assert graph.number_of_edges() == 1
assert graph.nodes["n1"]["file_type"] == "concept"
assert graph.nodes["n2"]["file_type"] == "document"
edge = next(iter(graph.edges(data=True)))[2]
assert edge["confidence"] == "INFERRED"
assert "confidence_score" not in edge
assert edge["relation"] == "references"
assert edge["source_file"] == "foo.py"
@pytest.mark.parametrize("value", [["EXTRACTED"], {"value": "EXTRACTED"}])
def test_build_repairs_structured_confidence_on_hyperedges(value):
from graphify.build import build_from_json
data = deepcopy(VALID)
data["nodes"].append(
{"id": "n3", "label": "Baz", "file_type": "document", "source_file": "baz.md"}
)
data["hyperedges"] = [{"nodes": ["n1", "n2", "n3"], "confidence": value}]
graph = build_from_json(data)
assert graph.graph["hyperedges"][0]["confidence"] == "INFERRED"
assert set(graph.graph["hyperedges"][0]["nodes"]) == {"n1", "n2", "n3"}
def test_missing_nodes_key():
errors = validate_extraction({"edges": []})
assert any("nodes" in e for e in errors)
+64 -3
View File
@@ -1864,6 +1864,64 @@ def test_watch_handler_honors_graphifyignore(tmp_path, monkeypatch):
assert rebuild_calls, "non-ignored .py write should have triggered _rebuild_code"
@pytest.mark.skipif(not _watchdog_available(), reason="watchdog not installed")
def test_watch_non_linux_handler_accepts_events_without_watched_entry(
tmp_path, monkeypatch
):
"""#5075: macOS and Windows keep the recursive schedule, so their handler
must accept file events even though the manual `watched` map is empty."""
import threading
from graphify import watch as watch_mod
from watchdog import observers
from watchdog.events import FileCreatedEvent
from watchdog.observers import polling
watch_root = tmp_path / "corpus"
watch_root.mkdir()
target = watch_root / "app.py"
target.write_text("x = 1\n", encoding="utf-8")
captured = {}
rebuild_calls: list[Path] = []
class FakeObserver:
def schedule(self, handler, path, *, recursive=False, event_filter=None):
captured["handler"] = handler
captured["recursive"] = recursive
def start(self):
pass
fake = FakeObserver()
monkeypatch.setattr(observers, "Observer", lambda: fake)
monkeypatch.setattr(polling, "PollingObserver", lambda: fake)
monkeypatch.setattr(sys, "platform", "darwin")
monkeypatch.setattr(
watch_mod, "_rebuild_code", lambda p, **kw: rebuild_calls.append(p) or True
)
monkeypatch.setattr(watch_mod, "_notify_only", lambda p: None)
thread = threading.Thread(
target=watch_mod.watch,
args=(watch_root,),
kwargs={"debounce": 0.1},
daemon=True,
)
thread.start()
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and "handler" not in captured:
time.sleep(0.01)
assert captured.get("recursive") is True
captured["handler"].on_any_event(FileCreatedEvent(str(target)))
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and not rebuild_calls:
time.sleep(0.05)
assert rebuild_calls, "the recursive handler dropped a real file event"
@pytest.mark.skipif(not _watchdog_available(), reason="watchdog not installed")
def test_watch_loads_graphifyignore_once(tmp_path, monkeypatch):
"""gh-928: .graphifyignore must be parsed exactly once at watch() startup,
@@ -4938,7 +4996,7 @@ def test_watch_schedules_change_only_event_filter(tmp_path, monkeypatch):
_run_watch_with_fake_observer(tmp_path, monkeypatch, FakeObserver())
assert captured["recursive"] is True
assert captured["recursive"] is (not sys.platform.startswith("linux"))
assert captured["event_filter"] == _watch_event_filter()
assert we.FileOpenedEvent not in captured["event_filter"]
if hasattr(we, "FileClosedNoWriteEvent"):
@@ -4957,7 +5015,10 @@ def test_watch_falls_back_when_watchdog_lacks_event_filter(tmp_path, monkeypatch
_run_watch_with_fake_observer(tmp_path, monkeypatch, OldObserver())
assert captured == {"recursive": True, "called": True}
assert captured == {
"recursive": not sys.platform.startswith("linux"),
"called": True,
}
@pytest.mark.skipif(not _watchdog_available(), reason="watchdog not installed")
@@ -4994,7 +5055,7 @@ def test_watch_warns_when_observer_hides_event_filter_in_kwargs(
with caplog.at_level(logging.WARNING, logger="graphify.watch"):
_run_watch_with_fake_observer(tmp_path, monkeypatch, KwargsObserver())
assert captured == {"recursive": True}
assert captured == {"recursive": not sys.platform.startswith("linux")}
assert any("event_filter" in r.getMessage() for r in caplog.records)
+110
View File
@@ -0,0 +1,110 @@
import sys
from pathlib import Path
import pytest
pytest.importorskip("watchdog")
@pytest.mark.skipif(
not sys.platform.startswith("linux"),
reason="the pruned watch tree is Linux-only",
)
def test_watch_schedules_only_kept_directories(tmp_path, monkeypatch):
"""#5033: ignored directories must not get an inotify watch.
Smallest case: root + one kept dir + one .graphifyignore'd dir. The
watcher should schedule root and keep/ only, non-recursively.
"""
from graphify import watch as watch_mod
from watchdog import observers
from watchdog.observers import polling
(tmp_path / "keep").mkdir()
(tmp_path / "ignored").mkdir()
(tmp_path / "keep" / "a.py").write_text("x = 1\n", encoding="utf-8")
(tmp_path / "ignored" / "b.py").write_text("x = 2\n", encoding="utf-8")
(tmp_path / ".graphifyignore").write_text("ignored/\n", encoding="utf-8")
calls = []
class StopWatch(Exception):
pass
class FakeObserver:
def schedule(self, handler, path, *, recursive=False, event_filter=None):
calls.append((Path(path).resolve(), recursive))
def start(self):
raise StopWatch
fake = FakeObserver()
monkeypatch.setattr(observers, "Observer", lambda: fake)
monkeypatch.setattr(polling, "PollingObserver", lambda: fake)
monkeypatch.setattr(watch_mod, "_rebuild_code", lambda p, **kw: True)
monkeypatch.setattr(watch_mod, "_notify_only", lambda p: None)
with pytest.raises(StopWatch):
watch_mod.watch(tmp_path, debounce=0.1)
scheduled = {path for path, _ in calls}
assert scheduled == {tmp_path.resolve(), (tmp_path / "keep").resolve()}
assert all(recursive is False for _, recursive in calls)
def _inotify_watch_count():
import os
total = 0
for fd in os.listdir("/proc/self/fd"):
try:
target = os.readlink(f"/proc/self/fd/{fd}")
except OSError:
continue
if "inotify" not in target:
continue
try:
with open(f"/proc/self/fdinfo/{fd}") as f:
total += sum(1 for line in f if line.startswith("inotify wd:"))
except OSError:
pass
return total
@pytest.mark.skipif(
not __import__("sys").platform.startswith("linux"),
reason="inotify is Linux-only",
)
def test_watch_does_not_watch_ignored_directories(tmp_path, monkeypatch):
"""The kernel should see watches for root and keep/ only, not ignored/."""
import threading
import time
from graphify import watch as watch_mod
(tmp_path / "keep").mkdir()
(tmp_path / "ignored").mkdir()
(tmp_path / "keep" / "a.py").write_text("x = 1\n", encoding="utf-8")
(tmp_path / "ignored" / "b.py").write_text("x = 2\n", encoding="utf-8")
(tmp_path / ".graphifyignore").write_text("ignored/\n", encoding="utf-8")
monkeypatch.setattr(watch_mod, "_rebuild_code", lambda p, **kw: True)
monkeypatch.setattr(watch_mod, "_notify_only", lambda p: None)
before = _inotify_watch_count()
thread = threading.Thread(
target=watch_mod.watch,
args=(tmp_path,),
kwargs={"debounce": 0.1},
daemon=True,
)
thread.start()
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline:
if _inotify_watch_count() > before:
break
time.sleep(0.05)
time.sleep(0.2)
assert _inotify_watch_count() - before == 2
+107 -5
View File
@@ -287,8 +287,8 @@ def test_to_wiki_case_only_distinct_labels_dont_overwrite(tmp_path):
# both communities survive as separate files on disk (no silent overwrite)
assert len(articles) == n == 2, [p.name for p in articles]
# filenames are distinct even when compared case-insensitively
lowered = [p.stem.lower() for p in articles]
assert len(set(lowered)) == len(lowered), [p.name for p in articles]
folded = [p.stem.casefold() for p in articles]
assert len(set(folded)) == len(folded), [p.name for p in articles]
def test_to_wiki_god_node_label_case_collides_with_community(tmp_path):
@@ -305,8 +305,8 @@ def test_to_wiki_god_node_label_case_collides_with_community(tmp_path):
n = to_wiki(G, communities, tmp_path, community_labels=labels, god_nodes_data=god_nodes)
articles = [p for p in tmp_path.glob("*.md") if p.name != "index.md"]
assert len(articles) == n == 2, [p.name for p in articles]
lowered = [p.stem.lower() for p in articles]
assert len(set(lowered)) == len(lowered), [p.name for p in articles]
folded = [p.stem.casefold() for p in articles]
assert len(set(folded)) == len(folded), [p.name for p in articles]
def test_to_wiki_article_labelled_index_does_not_overwrite_index_md(tmp_path):
@@ -327,7 +327,7 @@ def test_to_wiki_article_labelled_index_does_not_overwrite_index_md(tmp_path):
labels = {0: "index", 1: "Search"}
god_nodes = [{"id": "n3", "label": "Index", "degree": 1}]
n = to_wiki(G, communities, tmp_path, community_labels=labels, god_nodes_data=god_nodes)
articles = [p for p in tmp_path.glob("*.md") if p.stem.lower() != "index"]
articles = [p for p in tmp_path.glob("*.md") if p.stem.casefold() != "index"]
# every article survives as its own file next to the catalog
assert len(articles) == n == 3, sorted(p.name for p in tmp_path.glob("*.md"))
index_text = (tmp_path / "index.md").read_text(encoding="utf-8")
@@ -336,6 +336,108 @@ def test_to_wiki_article_labelled_index_does_not_overwrite_index_md(tmp_path):
assert "(index.md)" not in index_text, index_text
# Unicode labels that share a case fold but not a lower() spelling. On 0.9.104,
# lower()-based slug dedup allocated a distinct slug for each, while the
# casefold()-based orphan sweep mapped both filenames to the same key and
# unlinked whichever current article it did not keep (#5087).
_UNICODE_FOLD_PAIRS = [
("Straße", "STRASSE"),
("Σ", "ς"),
]
def _assert_wiki_complete(root: Path, expected_headings: set[str]) -> None:
"""Every expected article survives under a distinct folded slug, its body is
the one generated for it, and every inline link target exists on disk."""
files = sorted(p.name for p in root.glob("*.md"))
articles = [p for p in root.glob("*.md") if p.name != "index.md"]
assert len(articles) == len(expected_headings), files
assert len({p.stem.casefold() for p in articles}) == len(articles), files
headings = {p.read_text(encoding="utf-8").splitlines()[0] for p in articles}
assert headings == {f"# {label}" for label in expected_headings}, headings
for md in root.glob("*.md"):
for display, target in _inline_links(md.read_text(encoding="utf-8")):
assert (root / target).exists(), f"{md.name}: [{display}] -> {target} is dead"
@pytest.mark.parametrize("labels", _UNICODE_FOLD_PAIRS, ids=["german-sharp-s", "greek-sigma"])
@pytest.mark.parametrize("kind", ["community-community", "community-hub", "hub-hub"])
def test_to_wiki_unicode_case_fold_collision_keeps_both_articles(tmp_path, kind, labels):
"""Two simultaneously produced Unicode labels with the same case fold must
both survive. Allocating slugs with lower() while the orphan sweep folds with
casefold() let both slugs through and then deleted one as if it were a stale
spelling, leaving index.md linking to a file that no longer existed (#5087)."""
first, second = labels
G = nx.Graph()
G.add_node("n1", label=first, file_type="code", source_file="a.py")
G.add_node("n2", label=second, file_type="code", source_file="b.py")
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", weight=1.0)
if kind == "community-community":
communities = {0: ["n1"], 1: ["n2"]}
community_labels = {0: first, 1: second}
god_nodes = []
expected = {first, second}
elif kind == "community-hub":
communities = {0: ["n1"]}
community_labels = {0: first}
god_nodes = [{"id": "n2", "label": second, "degree": 1}]
expected = {first, second}
else:
communities = {0: ["n1", "n2"]}
community_labels = {0: "Core"}
god_nodes = [
{"id": "n1", "label": first, "degree": 1},
{"id": "n2", "label": second, "degree": 1},
]
expected = {"Core", first, second}
count = to_wiki(
G, communities, tmp_path,
community_labels=community_labels, god_nodes_data=god_nodes,
)
assert count == len(expected)
_assert_wiki_complete(tmp_path, expected)
def test_to_wiki_unicode_case_fold_repeat_export_is_stable(tmp_path):
"""Re-exporting the same graph must not delete an article the first export
wrote, and must leave the wiki byte-identical (#5087)."""
first, second = _UNICODE_FOLD_PAIRS[0]
G = nx.Graph()
G.add_node("n1", label=first, file_type="code", source_file="a.py")
G.add_node("n2", label=second, file_type="code", source_file="b.py")
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", weight=1.0)
communities = {0: ["n1"], 1: ["n2"]}
labels = {0: first, 1: second}
to_wiki(G, communities, tmp_path, community_labels=labels)
after_first = {p.name: p.read_text(encoding="utf-8") for p in tmp_path.glob("*.md")}
_assert_wiki_complete(tmp_path, {first, second})
to_wiki(G, communities, tmp_path, community_labels=labels)
after_second = {p.name: p.read_text(encoding="utf-8") for p in tmp_path.glob("*.md")}
assert after_second == after_first
_assert_wiki_complete(tmp_path, {first, second})
def test_to_wiki_unicode_case_fold_relabel_removes_stale_twin(tmp_path):
"""The fold-aware sweep must still remove a genuinely stale spelling when a
community is relabelled from one fold-equal form to the other. Keeping both
current articles must not turn the cleanup into a no-op (#4508, #5087)."""
first, second = _UNICODE_FOLD_PAIRS[0]
G = nx.Graph()
G.add_node("n1", label="parse", file_type="code", source_file="a.py")
to_wiki(G, {0: ["n1"]}, tmp_path, community_labels={0: first})
assert (tmp_path / f"{first}.md").exists()
to_wiki(G, {0: ["n1"]}, tmp_path, community_labels={0: second})
articles = [p.name for p in tmp_path.glob("*.md") if p.name != "index.md"]
assert articles == [f"{second}.md"], articles
_assert_wiki_complete(tmp_path, {second})
# Regression tests for portable wiki links - Obsidian [[wikilinks]] break in
# every non-Obsidian renderer (VS Code preview, GitHub, GitLab, plain browsers).
@@ -1,6 +1,6 @@
# graphify reference: extraction subagent prompt (compact)
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
@@ -1,6 +1,6 @@
# graphify reference: extraction subagent prompt (compact)
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
@@ -1,6 +1,6 @@
# graphify reference: extraction subagent prompt (compact)
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
@@ -0,0 +1,42 @@
# graphify reference: extraction subagent prompt (compact)
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Read every file COMPLETELY before extracting from it. The Read tool returns at most 2000 lines per
call and reports NO error when it truncates, so a long file silently yields a partial extraction.
Page with offset/limit until you have seen the last line; never emit nodes for a partly-read file -
replace-on-re-extract drops that file's existing nodes and re-adds only what you saw, so the unread
tail is lost and the file is never retried (#2225). Report what you read in a top-level
"coverage" object mapping each FILE_LIST path to its line count, e.g.
{"coverage": {"docs/plan.md": 452}} - a short count is caught and retried, a missing one is not.
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation)
- INFERRED: reasonable inference (shared structure, implied dependency)
- AMBIGUOUS: uncertain — flag it, do not omit
- Code files: semantic edges AST cannot find. Do not re-extract imports. When adding `calls` edges: source is the caller, target is the callee, never reversed; keep `calls` within one language.
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms) and `file_type:"concept"` for named concepts. `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
- Image files: use vision — understand what the image IS, not just OCR
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges — indirect deps, shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
- Semantic similarity: if two concepts solve the same problem or represent the same idea without a structural link (no import, call, or citation), add a `semantically_similar_to` edge marked INFERRED with confidence_score 0.6-0.95. Non-obvious cross-file links only.
- Hyperedges: if 3+ nodes share a concept, flow, or pattern not captured by pairwise edges, add a hyperedge to a top-level `hyperedges` array. Use sparingly. Max 3 per chunk.
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[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 is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
+4
View File
@@ -158,6 +158,10 @@ _SHARED_REFERENCES = {
_EXTRACTION_SOURCE = {
"verbose": "references/shared/extraction-spec.md",
"compact": "references/shared/extraction-spec-compact.md",
# Compact prompt for hosts whose subagents write their own chunk file
# (the dispatch passes CHUNK_PATH). Codex keeps "compact": its workers
# return JSON inline and the orchestrator writes the files.
"compact-disk": "references/shared/extraction-spec-compact-disk.md",
}
# Single unified query reference + stub: superior vocab-expansion (Step 0) plus
# CLI traversal plus inline NetworkX fallback, shipped to every platform. The
+3 -3
View File
@@ -105,7 +105,7 @@ skill_dst = "graphify/skill-claw.md"
refs_dst = "graphify/skills/claw/references"
description = "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
dispatch = "agent-tool-disk"
extraction = "compact"
extraction = "compact-disk"
[platform.droid]
bucket = "split"
@@ -167,7 +167,7 @@ skill_dst = "graphify/skill-kiro.md"
refs_dst = "graphify/skills/kiro/references"
description = "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
dispatch = "agent-tool-disk"
extraction = "compact"
extraction = "compact-disk"
[platform.pi]
bucket = "split"
@@ -176,7 +176,7 @@ skill_dst = "graphify/skill-pi.md"
refs_dst = "graphify/skills/pi/references"
description = "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
dispatch = "pi-subagents"
extraction = "compact"
extraction = "compact-disk"
[platform.vscode]
bucket = "split"
Generated
+49 -49
View File
@@ -8,10 +8,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version < '3.11'",
]
@@ -633,10 +633,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -948,10 +948,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/d2/79/e78bd8f75a9b8e32233ce92d4607f0a21ce88a9156cace2884e7175a82f5/coverage-7.17.0.tar.gz", hash = "sha256:cc010a0a7fbdd9bb8bdfd0d3f04a5151275860213cbd7e2b876b29778489c712", size = 991021, upload-time = "2026-10-22T16:06:50.009Z" }
@@ -1313,10 +1313,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/d8/28/3893324bcadf8f89b1616637468d766af3f625008c0735bf704fdfa86617/filelock-4.2.4.tar.gz", hash = "sha256:c6d8663535e1650ee430507b4ffbac7b464dd64b7647ea0112a9f406499d163d", size = 652444, upload-time = "2026-10-19T01:57:51.001Z" }
@@ -1419,10 +1419,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/94/36/102e180f8f5dbaee88b26595b01ca8aa80bf4e62128d9aa94265b3996c96/fonttools-4.67.0.tar.gz", hash = "sha256:3cb57e6600ca77c0b1729cf8adc23bc0652633a37f18cfa934d9c7bc3de25519", size = 3750028, upload-time = "2026-10-14T13:20:28.294Z" }
@@ -1540,7 +1540,7 @@ wheels = [
[[package]]
name = "graphifyy"
version = "0.9.99"
version = "0.9.105"
source = { editable = "." }
dependencies = [
{ name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
@@ -1797,8 +1797,8 @@ requires-dist = [
{ name = "pillow", marker = "python_full_version < '3.11' and extra == 'svg'", specifier = ">=12.3.0" },
{ name = "psycopg", extras = ["binary"], marker = "extra == 'all'" },
{ name = "psycopg", extras = ["binary"], marker = "extra == 'postgres'" },
{ name = "pypdf", marker = "extra == 'all'", specifier = ">=6.19.0" },
{ name = "pypdf", marker = "extra == 'pdf'", specifier = ">=6.19.0" },
{ name = "pypdf", marker = "extra == 'all'", specifier = ">=6.21.4" },
{ name = "pypdf", marker = "extra == 'pdf'", specifier = ">=6.21.4" },
{ name = "python-docx", marker = "extra == 'all'" },
{ name = "python-docx", marker = "extra == 'office'" },
{ name = "pyyaml", specifier = ">=6.0" },
@@ -2000,8 +2000,8 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'win32'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -2043,10 +2043,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -2201,10 +2201,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -3017,10 +3017,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -3278,10 +3278,10 @@ version = "3.6.1"
source = { registry = "https://pypi.org/simple" }
resolution-markers = [
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" }
@@ -3372,10 +3372,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version < '3.11'",
]
@@ -3655,10 +3655,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -3864,10 +3864,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" }
@@ -4035,10 +4035,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/58/e6/d0abbb256b44e6a05748c6942511ff67db8dbb068de0c35b24bf1b395b09/platformdirs-4.13.5.tar.gz", hash = "sha256:05831adf87d392760f4b5c3a0a95579ab5a10b18b9b9bd43680dcb47544788a0", size = 62362, upload-time = "2026-10-19T01:02:11.778Z" }
@@ -4134,10 +4134,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -4293,10 +4293,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/cb/27/eeb9f307bf07060f3d9f9aa0fb8c15b01bdfded0a941e4b2719c7f94cacd/pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6", size = 158785, upload-time = "2026-10-22T13:40:03.56Z" }
@@ -4521,14 +4521,14 @@ wheels = [
[[package]]
name = "pypdf"
version = "6.21.2"
version = "6.21.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/06/28/081f1cbcca7042441dafc8de00f48ba60853f89e5bff92c5f26477346d81/pypdf-6.21.2.tar.gz", hash = "sha256:0a3e1c5c886a1be03646c16a04827cc166c2a0575c971b26a4bf89686551c2d4", size = 7144571, upload-time = "2026-10-21T16:44:55.272Z" }
sdist = { url = "https://files.pythonhosted.org/packages/1e/e1/ec8f4d155c997c45917153a5521e60d6ee6389d68abdcbc8e44e564caffc/pypdf-6.21.4.tar.gz", hash = "sha256:c8817e3f888d47a087872ded69812c1ef30cacb871d6e053e0c00bbaf0bc2163", size = 7109255, upload-time = "2026-10-28T17:00:54.81Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/1b/4d/c9d2d67f204eff463237a1a8f5e25a6923b7b1043982b91fcaf104c8ef60/pypdf-6.21.2-py3-none-any.whl", hash = "sha256:1d44d1a3a200f25062adff0085b02040e4646431ac2ccac22e42679e91466084", size = 407766, upload-time = "2026-10-21T16:44:53.626Z" },
{ url = "https://files.pythonhosted.org/packages/3f/4b/77e8ad4ac42c9d93600f40541a50e9feb3a61d2bbee2d76f659346072051/pypdf-6.21.4-py3-none-any.whl", hash = "sha256:33e4fb41ca352810eb4e9838aa0d82d6888a5f8bf682f43e99cce5faa666255c", size = 410430, upload-time = "2026-10-28T17:00:53.146Z" },
]
[[package]]
@@ -4835,10 +4835,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/18/97/226c43b7b5d957bc3840ed52ea99eed261f99834c4619be7a4742cbaeafa/rapidfuzz-3.14.6.tar.gz", hash = "sha256:e13a8160d017b499ec7a2fa9d0ce1ae2e7377080815785819f966fb235d4eb60", size = 57955060, upload-time = "2026-08-30T21:45:51.097Z" }
@@ -5284,10 +5284,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/42/68/3bd46b8a5e01d3c2ebdf9c5e9497912e3fe0cde02bac21a7130ca866e403/rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12", size = 63948, upload-time = "2026-10-04T16:32:36.469Z" }
@@ -5514,10 +5514,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -5641,10 +5641,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -5928,10 +5928,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
dependencies = [
@@ -6013,10 +6013,10 @@ resolution-markers = [
"python_full_version == '3.12.*' and sys_platform == 'emscripten'",
"python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'",
"python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
sdist = { url = "https://files.pythonhosted.org/packages/db/a1/3b8ed9c1fc3aa6eebb57732d924ddaa0500ecc3b638d0454816320994383/stevedore-5.9.1.tar.gz", hash = "sha256:e97a2667923efda926e8713fde6a73616df68210a3cbc6f02b48967b676fd8bf", size = 518111, upload-time = "2026-08-20T15:25:14.754Z" }