Compare commits

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

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

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

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

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

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

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

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

Refs #4828

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

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

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

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

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

Refs #4828

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

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

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

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

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

Refs #4828

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

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

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

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

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

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

Refs #4828

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #5086

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

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

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

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

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

Fixes #5079

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

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

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

Fixes #5080

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

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

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

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

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

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

Fixes #5034

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

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

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

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

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

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

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

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

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

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

Fixes #5087

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

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

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

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

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

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

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

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

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

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

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

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

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

Reported and first proposed by @danikdanik in #4762.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #5044

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(cherry picked from commit 469904a0ce)
2026-11-07 17:14:03 +00:00
160 changed files with 10174 additions and 1074 deletions

No files matched your search

+40
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.
@@ -197,6 +213,30 @@ lack this path. The merge runs after colliding ids are salted apart by path, so
a half whose file stem collides with another file's (`Spec.cs` and `_Spec.cs`,
`Cfg/Helpers.cs` and `Cfg_Helpers.cs`) still merges and keeps its members.
C# constructors (instance, static and a type's primary constructor) are nodes
owned by their type through a `method` edge, labeled `.TypeName()` with
metadata `kind: "constructor"`. The id is the one a method named after the type
would get, `_make_id(type_id, TypeName)`; each further signature is salted like
a method overload, a static constructor is its own `static` signature, and when
a member spelled like the type in another case (`foo()` in `Foo`) already owns
that id, the constructor takes a salted one, so no existing id moves. Calls in
a constructor's body and `: base(...)`/`: this(...)` arguments are its calls.
`new X(...)` keeps its edge to the type and also links the constructor whose
parameter count fits, as do `: base(...)`/`: this(...)`; two fitting overloads,
an unresolved base or an unbound type give no constructor edge. Constructors
stay out of every name-keyed call index. AST cache schema 40 retires C# entries
without them.
C# property and indexer accessor bodies (and expression bodies) are walked
with the member as the caller, and the member counts as owned by its type for
unqualified, `this.`/`base.` and partial-type lookups, like a method. It is never
a call target by name. An indexer is a `this[]` node (`defines`, context
`field`) with id `_make_id(type_id, "this")`, salted per signature and away
from a member spelled `This`. A user-defined operator or conversion is a
`.operator +()` / `.operator int()` node owned through `method`, with id
`_make_id(type_id, "operator", sha1(signature)[:6])`, since several conversions
share one parameter list. Existing ids do not move. AST cache schema 40.
R extraction preserves symbol-only bindings such as `%||%` as separate nodes.
When normal ID normalization removes an entire binding name, its UTF-8 bytes
provide a deterministic operator suffix within the same lexical owner. Its double
+55
View File
@@ -2,6 +2,61 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/Graphify-Labs/graphify/releases)
## 0.9.105 (2026-11-09)
- Fix: **watch** ignored directories (`node_modules`, `.git`, build output) are pruned from the Linux watch tree, so a large project no longer registers tens of thousands of wasted inotify watches and risks `ENOSPC`; the non-Linux recursive watcher is unchanged and still fires on every real change (#5074, #5091, thanks @Deepjyoti-Sarmah).
- Fix: **cpp** a member-call chain routed through class fields declared in other headers (`client.actions->Execute()`, with value `.`, raw-pointer `->` and single-arg `unique_ptr`/`shared_ptr` receivers) resolves to the field type's member across the include set, gated to a unique type and member and fail-closed otherwise; a typed local whose class is in another repo is parked for the cross-repo merge (#5098, thanks @xRedLeader).
- Fix: **markdown** a code span naming an uppercase `\`-namespace class (`\Foo\Bar`, `App\API`) or a type-qualified method call (`Type::member()`) is kept as a symbol mention instead of being dropped, while a non-call `Type::CONST`/`Type::class` stays dropped (#5093, thanks @Adityakk9031).
- Fix: **ts/js** a call through a destructured CommonJS barrel require (`const { Thing } = require('./barrel')` where the barrel re-exports `Thing`) resolves to the real declaration by following the barrel's exports, instead of dropping the edge (#5034, #5104, thanks @qq2514568380).
- Fix: **wiki** the orphan sweep folds slugs with `casefold` (not `lower`), so two article names that collide only under full Unicode case-folding (`Straße`/`STRASSE`, `Σ`/`ς`) each keep their own file instead of one being deleted as an orphan; a file written this run is never swept (#5087, #5102, thanks @nothariharan).
- Fix: **build** hyperedges are kept whole across an incremental `graphify update`: they are read from the nested graph slot a JSON-only writer uses, and after a deleted-source prune a hyperedge drops only its removed members (and itself only when none remain), instead of silently losing or leaving dangling hyperedges (#5081, #5103, thanks @nothariharan).
- Fix: **cache** a degraded (under-producing) semantic cache entry no longer pins the corpus: after the shrink guard sees a re-extraction come back smaller than the stored graph, the entry is stamped `partial` so the next run re-dispatches it instead of replaying the degraded result forever (#5083, #5101, thanks @nothariharan).
- Fix: **affected** `graphify affected <file>` seeds the file's nested member nodes (a method inside a class) transitively, not just one hop, so impact analysis no longer under-reports callers that bind to a nested member (#5094, thanks @Adityakk9031).
- Fix: **tree** `build_tree` derives the common directory root from file parents, so a single-file or single-directory tree is no longer self-nested under the file itself (#5092, thanks @Adityakk9031).
- Fix: **query** a label whose name is behind a schema or namespace qualifier (`public.sweep_widget_state()`, `fmt.Println`) is matched on its tail by the whole query and ranked above the per-token tiers, so it is no longer out-competed by single-token collision nodes and dropped from the seeds (#5080, #5095, thanks @sunhouy).
- Fix: **detect** an incremental staleness check hashes a file whose stamp lands within the clock-skew window on either side of its mtime, so a same-tick rewrite that does not move mtime is still caught instead of being served stale (#5090, thanks @sunhouy).
- Fix: **path** `graphify path A B` refuses an endpoint whose words appear nowhere in the graph (exit not-found) instead of returning a misleading route built from loosely-overlapping tokens (#5085, thanks @sunhouy).
- Fix: **csharp** a classic extension-method call (`x.Foo()` where `Foo` is declared `static ... Foo(this X x, ...)`) binds to the extension method's declaration through an additive pass that runs after nominal dispatch, gated to a visible namespace, a matching `this` type and a unique applicable method; an instance method of the same name wins, a non-extension static or an unimported extension gets no edge, and ambiguity fails closed (#4828, #4849, thanks @Deepjyoti-Sarmah).
- Fix: **markdown** a bare, unqualified free-function mention in prose (`token`, no `()` and no namespace) binds to a same-named function only when its defining file (or another symbol from it) is cited within the heading's section chain, instead of matching any same-named callable in the corpus; reference-style links (`[text][label]`) resolve at the use site (#4804, #4806, thanks @madanlalit).
- Fix: **export** the `to_json` shrink guard no longer counts semantic sources that were replaced on re-extract or pruned as deletions as "lost", so a legitimate `graphify update` is not refused; a genuine unexplained shrink is still refused (#5107, thanks @khkar).
- Fix: **build** a node whose `file_type` or `confidence` arrives as a structured value (list/dict) from a drifting LLM pass no longer crashes the validate/build membership checks: validation surfaces it as a schema error, and the build folds it to `concept`/`INFERRED` without fabricating a score (#5088, thanks @sdivyanshu90).
- Fix: **llm** a splittable document below the character cap whose model output truncates is promoted to a full-range slice and bisected (and retried) instead of being kept as a truncated partial result; a non-splittable or code/binary unit still fails closed (#5072, #5078, thanks @aadilrizwan).
- Feat: **llm** a custom OpenAI-compatible provider's `extra_headers` are forwarded to the client as `default_headers`, scoped to that provider and with any `Authorization` header dropped so it cannot override the configured credential (#3680, #4783, thanks @jaimemartinez).
- Perf: **extract** whole-graph intermediates (the parse memo on the one-shot CLI, build/cluster/export working lists) are freed as soon as they are consumed, cutting peak memory on a large corpus; graph output is byte-identical (#5063, thanks @TPAteeq).
- Fix: **skillgen** the claw/kiro/pi subagent prompt now tells the worker to write its chunk to `CHUNK_PATH`, so a disk-dispatch chunk is no longer returned inline and lost at the merge step (#5040, thanks @connhodendatabase).
- Fix: **deps** the pypdf floor is raised to 6.21.4 in the `pdf` and `all` extras to pick up its security fixes (#5015, thanks @yotamleo).
The AST cache schema is bumped to 42; warm caches re-run the affected C++, Markdown and C# extractions.
## 0.9.104 (2026-11-07)
- Security: **skill** the `/graphify` runbook no longer substitutes the scan path into Python code. Every generated code block (detect, AST and semantic extraction, build, diagnose, label, manifest, and `--update`) now reads the resolved scan root from the trusted `graphify-out/.graphify_root` sidecar that Step 1 writes through a quoted heredoc, instead of pasting the agent-supplied path into a string literal. A directory whose name carried a quote or `$(...)` could previously break out of `Path('INPUT_PATH')` and run as code; it is now read as inert data. Covers the assembled hosts and the Aider/Devin monoliths (#4762, thanks @danikdanik).
- Fix: **solidity** a call on a receiver of a contract or interface type (`IERC20 token; token.transfer()`, `IERC20(a).transfer()`, `token().balanceOf()`) binds by name and arity through that type's linearization to the type's own declaration, instead of producing no edge; gated to a single visible contract/interface and fail-closed on an unknown or ambiguous type (#5060, thanks @rohit-jsfreaky).
- Fix: **solidity** a call attached by a `using A for T` directive (`using SafeCast for uint256; x.toUint48()`) binds to the library or free function it attaches, matched by the receiver's type and an arity one greater than the call; fail-closed when the receiver type is unknown, the library is ambiguous, or two functions fit (#5062, thanks @rohit-jsfreaky).
- Fix: **solidity** members, free functions and types in one scope whose names differ only by a leading `_` or by case (`_grantRole` / `grantRole`) get separate node ids, so the `_` symbol no longer vanishes into its twin and its calls land on the right node (#5027, thanks @rohit-jsfreaky).
- Fix: **csharp** a constructor (instance, static or primary) is its own node owned by its type, with its body and `: base(...)`/`: this(...)` calls credited to it; `new X(...)`, `: base(...)` and `: this(...)` additively link the arity-correct overload, and two fitting overloads or an unresolved base give no constructor edge (#5054, thanks @rohit-jsfreaky).
- Fix: **csharp** calls inside a property or indexer accessor, an expression body, or an operator/conversion body are credited to that member instead of being lost; an indexer becomes a `this[]` node and an operator a `.operator +()` node (#5056, thanks @rohit-jsfreaky).
- Fix: **query** a same-label node that is the only match for a query term is kept as a seed instead of being dropped by the per-label cap, so every distinct term keeps at least one seed while generic-label flooding stays capped (#5027, thanks @Vaibhav2824).
- Fix: **watch** read-only events are kept out of the inotify mask via a change-only `event_filter`, so a large tree no longer drives watchdog into a self-sustaining queue-overflow loop; falls back with a warning on watchdog versions without `event_filter` support (#5033, thanks @Deepjyoti-Sarmah).
- Fix: **cache** the `\\?\` long-path spelling is kept out of cache identity, so the same file reached through `\\?\C:\...` and `C:\...` shares one entry; also fixes empty stat-index writes under UNC shares, a spurious "stat index switched" warning on Windows, and a junction/symlink alias wrongly sharing its target's digest (#5035, thanks @Bortlesboat).
- Fix: **cache** stat-index keys stay root-relative under a Windows long-path root, so a moved or cloned corpus keeps the portable-key fastpath (#5035, thanks @Vaibhav2824).
- Fix: **tests** the TypeScript unicode fixture is written as UTF-8 on every platform, so byte offsets match the extractor on Windows (cp1252) hosts (#5064, thanks @ayushcodes10).
- Fix: **tests** the hook-freshness source mock is normalized through `os_long_path`, so the read-error/stale branch is actually exercised on Windows (#5065, thanks @ayushcodes10).
- Fix: **tests** the watch pending-queue test compares `Path` objects so `/` and `\` separators compare equal on Windows (#5039, thanks @Yi-111-a).
- Fix: **extract** an ambiguous Python import's placeholder node id is hashed from checkout-independent data (module name, scan-root-relative source file, location) instead of the absolute path, so the same project at a different path or a moved cache gets the same ids (#5045, thanks @Fardin7798).
- Fix: **yaml** a template using CloudFormation intrinsic tags (`!Ref`, `!GetAtt`, `!Sub`) no longer fails to parse: a scoped permissive loader rebuilds each `!`-tagged node's shape without evaluating it, while `!!python/...` tags still raise and never execute (#5077, thanks @ayushcodes10).
- Fix: **watch** a `--watch` incremental update rebuilds the full corpus when `graph.json` is missing, instead of writing a partial graph from the manifest alone (#5016, #5021, thanks @azizur100389).
- Fix: **watch** a change to a JS/TS resolution input (`tsconfig.json`, `jsconfig.json`, a lockfile) triggers a full rebuild so importers pick up the new resolution, instead of leaving stale `imports_from` edges (#5017, #5022, thanks @azizur100389).
- Fix: **ingest** two concurrent `graphify add` captures for the same URL no longer clobber each other: the capture file is created exclusively (`O_EXCL`) and a collision retries a fresh name, with the payload fetched once (#5018, #5023, thanks @azizur100389).
- Fix: **reflect** a malformed entry in the learning overlay is skipped instead of crashing the whole load, and a legacy null-source entry is preserved as a source-less annotation (#5019, #5024, thanks @azizur100389).
- Fix: **global** a malformed repo entry in the global manifest is dropped on its own, keeping the other tracked repos, and only a non-object root or repos map is backed up and reset (#5020, #5025, thanks @azizur100389).
- Fix: **query** a graph freshly built on a subfolder is no longer flagged as a pre-#1504 build (which nagged a no-op `extract --force`): the legacy-id probe strips the `.graphify_root` offset before deriving file stems, and a genuine legacy graph is still caught (#2603, #5028, thanks @neumannpeter1231-lang).
- Fix: **tree** `graphify export tree` recognises the `src` node alias (and `file`/`path`/`filepath`) so a graph carrying those keys renders a populated tree instead of an empty one; a concept-only graph still reports empty (#5030, thanks @Adityakk9031).
- Fix: **cli** `graphify provider add` accepts `--pricing-input=VALUE`/`--pricing-output=VALUE` equals-syntax and rejects a non-numeric, non-finite or negative price with a clean error instead of a traceback or a poisoned cost estimate (#5031, thanks @Adityakk9031).
The AST cache schema is bumped to 40; warm caches re-run the affected Solidity and C# extractions. The Python and YAML fixes above need no bump (placeholder ids are resolved after the per-file cache, and previously-failing YAML was never cached).
## 0.9.103 (2026-11-05)
- Fix: **markdown** a code span written as a backslash namespace (`\Foo\Bar`) or a type-qualified member (`Type::member`) is recognised as a symbol mention and resolves to the real node when one exists, instead of being silently dropped; an absent chain mints nothing (#4610, #4695, thanks @viwe-monai).
+1 -1
View File
@@ -38,7 +38,7 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
| Symlink traversal | `os.walk(..., followlinks=False)` is parameterized to avoid unchecked traversal where appropriate. |
| Symlink escape during ingest | `ingest` writes through `lstat` and refuses to replace an existing directory entry, including a symlink, so a crafted source tree cannot redirect writes outside the output directory. |
| Symlink escape during ingest | `ingest` checks names with `lstat` and creates capture files exclusively. If another entry takes the selected name, the capture retries with a numbered name. |
| Credentials in persisted text | `security.redact_secrets()` replaces credential-shaped substrings in labels and rationale text before they are written to `graph.json`. |
| Destructive uninstall | `uninstall --purge` refuses to delete the project folder, the home directory, or a filesystem root, including when `GRAPHIFY_OUT` points outside the project. |
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
+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
+115 -7
View File
@@ -683,7 +683,7 @@ def _fold_node_aliases(node: dict) -> None:
if not node.get("label") and isinstance(node.get("name"), str) and node["name"]:
node["label"] = node.pop("name")
if not node.get("source_file"):
for alias in ("file", "path", "filepath"):
for alias in ("file", "path", "filepath", "src"):
val = node.get(alias)
if isinstance(val, str) and val.strip():
node["source_file"] = node.pop(alias)
@@ -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"
@@ -1434,7 +1440,37 @@ def _has_global_id(node: dict) -> bool:
return meta.get("mcp_kind") in _MCP_GLOBAL_ID_KINDS
def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: int = 300) -> bool:
def legacy_id_source_prefix(graph_path: str | Path) -> str | None:
"""The scan-root prefix that a graph's stored ``source_file`` values carry.
A build scoped to a subfolder from its parent (``graphify update sub``)
stores ``source_file`` relative to the build's cwd (``sub/pkg/mod.py``,
#2603) while every id is minted relative to the scan root (``pkg_mod``).
The relative ``.graphify_root`` marker next to the graph records exactly
that offset (``sub``). Returns it in normalized POSIX form, or None when
there is no offset: no marker, an absolute marker (the build anchored
source_file at the scan root itself), ``.``, or a path leaving the cwd.
"""
try:
text = (Path(graph_path).parent / ".graphify_root").read_text(
encoding="utf-8-sig"
).strip()
except (OSError, UnicodeError, ValueError):
return None
if not text:
return None
text = text.replace("\\", "/")
if _is_abs(text):
return None
import posixpath
prefix = posixpath.normpath(text)
if prefix in (".", "") or prefix == ".." or prefix.startswith("../"):
return None
return prefix
def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: int = 300,
source_prefix: str | None = None) -> bool:
"""Whether a loaded graph still uses pre-#1504 node IDs (parent-dir / filename
stem) rather than the full repo-relative path. Read-only consumers (query,
serve) use this to nudge the user to rebuild, since they don't re-extract.
@@ -1446,9 +1482,16 @@ def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: in
file-stem form and would otherwise false-positive. Nodes whose ID is global by
construction (see ``_MCP_GLOBAL_ID_KINDS``) are skipped for the same reason.
Returns True as soon as one file node's ID matches an OLD stem form but not the
canonical full-path form."""
canonical full-path form.
``source_prefix`` (see :func:`legacy_id_source_prefix`) is the cwd->scan-root
offset stored source_file values carry; it is stripped before the stem is
derived, since ids never include it. Without it a fresh subfolder build reads
as legacy: ``sub/pkg/mod.py`` wants ``sub_pkg_mod``, and the real ``pkg_mod``
looks exactly like the old one-parent form."""
from graphify.extractors.base import _file_stem
_r = str(root) if root is not None else None
_pfx = (source_prefix.replace("\\", "/").rstrip("/") + "/") if source_prefix else None
checked = 0
for node in nodes:
if not isinstance(node, dict):
@@ -1468,9 +1511,11 @@ def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: in
if not nid or not isinstance(nid, str) or not sf:
continue
sf_norm = _norm_source_file(str(sf), _r) or str(sf)
rel = Path(sf_norm)
if _is_abs(sf_norm):
continue
if _pfx and sf_norm.startswith(_pfx):
sf_norm = sf_norm[len(_pfx):]
rel = Path(sf_norm)
if not rel.name:
continue # source_file == scan root -> Path('.'), no file stem (#1618)
new_stem = make_id(_file_stem(rel))
@@ -1583,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
@@ -2437,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
@@ -2465,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
@@ -2477,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)),
)
@@ -3058,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
@@ -3203,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
+111 -10
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 = 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, and the digest salt no longer lowercased) so README.md and readme.md stop sharing one digest on a case-sensitive filesystem, which also changes the salt digest for any relative path carrying an uppercase char (#4925, #4937), so cached Rust extractions and any uppercase-path cache entries re-run; prior (34): A bare call inside a Python method no longer self-binds to a same-named method, so it resolves to the imported/module function instead (#4933); a Go method value reached through a receiver field is linked as an indirect_call (#4931); and a Go package-level `var` initialiser references the types it names (#4932), so cached Python and Go extractions re-run; prior (33): A Scala `extension (x: T)` method is scoped to its receiver type T (#2044, #4856); and a Terraform node carries its original scope so ids stay portable when the cached project is moved to a new directory (#4858, #4861), so cached Scala and Terraform extractions re-run; prior (32): A type and a function whose names differ only in case get separate node ids (#4904, #4908); and a PHP `Scope::MEMBER` access in a class-level initializer (const value, property/parameter default) emits a references_constant edge (#4648, #4895); R `setClass`/`setRefClass` `contains=` superclasses get inherits edges (#4902); an Elixir bare call resolves to the caller's own module first (#4900); a Dart mixin `on A, B` clause resolves every constraint (#4899); and a Fortran derived-type `extends` emits an inherits edge (#4897), so cached extractions for those languages re-run (#4904); Go credits a call in a pacLine 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
@@ -411,7 +411,10 @@ def _ensure_stat_index(root: Path, cache_root: "Path | None" = None) -> None:
# relative so a moved/cloned corpus still hits (#2199) — same load/save
# re-anchoring the detect manifest uses.
_stat_index_root = new_root
_stat_index_anchor = Path(root).resolve()
# Spell the anchor like the in-memory keys (_normalize_path): callers pass an
# os_long_path() root, and on Windows relpath() cannot relate "\\?\C:\..." to
# "C:\...", so every key stayed absolute and a moved corpus missed (#5035).
_stat_index_anchor = _normalize_path(Path(root).resolve())
p = _stat_index_file(_stat_index_root)
_stat_index_path = p
_stat_index = {}
@@ -510,7 +513,9 @@ def _normalize_path(path: Path) -> Path:
if sys.platform != "win32":
return path
s = str(path)
if s.startswith("\\\\?\\"):
if s.startswith("\\\\?\\UNC\\"):
s = "\\\\" + s[8:] # \\?\UNC\server\share -> \\server\share
elif s.startswith("\\\\?\\"):
s = s[4:] # strip extended-length prefix \\?\
return Path(os.path.normpath(s))
@@ -548,9 +553,14 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
# (cache_root), not the key-anchor root — otherwise it leaves a stray
# graphify-out/cache/stat-index.json inside the analyzed source tree even when
# the AST cache itself is redirected to CWD (#1774 completion).
_ensure_stat_index(root_src, cache_root=cache_root)
resolved = src.resolve()
abs_key = str(_normalize_path(resolved))
#
# The index root, key and salt use the normalized spelling. The \\?\ form
# from os_long_path() is for I/O only: as the root it made load_cached()'s
# plain cache_root look like a second root (#3989), and no key was relative
# to it, so every key was written absolute (#2199).
_ensure_stat_index(_normalize_path(raw_root), cache_root=cache_root)
resolved = _normalize_path(src.resolve())
abs_key = str(resolved)
# The salt is the path component that enters the digest (relative to root, or
# the absolute-path fallback). The stat-index memo MUST be keyed by it too:
# the same file hashed under two different roots yields two different digests
@@ -558,7 +568,7 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
# path served whichever was computed first — making file_hash order-dependent
# and poisoning the persisted stat-index across runs (#1989). Store one digest
# per salt so alternating roots don't force re-reads.
resolved_root = root_src.resolve()
resolved_root = _normalize_path(root_src.resolve())
try:
resolved_rel = resolved.relative_to(resolved_root)
except ValueError:
@@ -579,7 +589,7 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
walked_rel = None
for parent in walked.parents:
try:
if parent.resolve() == resolved_root:
if _normalize_path(parent.resolve()) == resolved_root:
walked_rel = walked.relative_to(parent)
break
except OSError:
@@ -643,8 +653,7 @@ def cached_word_count(path: Path, root: Path, compute, cache_root: "Path | None"
raw_path = Path(path)
raw_root = Path(root)
src = Path(_os_long_path(raw_path))
root_src = Path(_os_long_path(raw_root))
_ensure_stat_index(root_src, cache_root=cache_root)
_ensure_stat_index(_normalize_path(raw_root), cache_root=cache_root)
abs_key = str(_normalize_path(src.resolve()))
st: "os.stat_result | None" = None
try:
@@ -1840,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("."),
+159 -6
View File
@@ -7,6 +7,7 @@ import of main to avoid a cli<->__main__ import cycle.
"""
from __future__ import annotations
import json
import math
import os
import re
import sys
@@ -15,6 +16,16 @@ from graphify.paths import GRAPHIFY_OUT as _GRAPHIFY_OUT
from pathlib import Path, PurePosixPath, PureWindowsPath
def _valid_price(value: float) -> float:
"""A provider price flag must be a finite, non-negative number. A NaN, inf
or negative value parses as a float but flows into cost estimation (price x
tokens), producing NaN/inf/negative cost reports (#5031), so reject it the
same way a non-numeric value is rejected."""
if not math.isfinite(value) or value < 0:
raise ValueError("price must be finite and non-negative")
return value
# Hook reminders arrive inside the agent's tool-result stream, where commands
# ("MANDATORY", "You MUST", "include this in every subagent prompt") read like a
# prompt injection and get ignored or flagged (#2202). State facts instead; the
@@ -447,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.
@@ -474,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
@@ -1873,9 +1968,35 @@ def dispatch_command(cmd: str) -> None:
elif a.startswith("--env-key="):
env_key = a.split("=", 1)[1]; i += 1
elif a == "--pricing-input" and i + 1 < len(args):
pricing_input = float(args[i + 1]); i += 2
try:
pricing_input = _valid_price(float(args[i + 1]))
except ValueError:
print(f"Error: invalid price for --pricing-input: '{args[i + 1]}' (expected a finite, non-negative number)", file=sys.stderr)
sys.exit(1)
i += 2
elif a.startswith("--pricing-input="):
val = a.split("=", 1)[1]
try:
pricing_input = _valid_price(float(val))
except ValueError:
print(f"Error: invalid price for --pricing-input: '{val}' (expected a finite, non-negative number)", file=sys.stderr)
sys.exit(1)
i += 1
elif a == "--pricing-output" and i + 1 < len(args):
pricing_output = float(args[i + 1]); i += 2
try:
pricing_output = _valid_price(float(args[i + 1]))
except ValueError:
print(f"Error: invalid price for --pricing-output: '{args[i + 1]}' (expected a finite, non-negative number)", file=sys.stderr)
sys.exit(1)
i += 2
elif a.startswith("--pricing-output="):
val = a.split("=", 1)[1]
try:
pricing_output = _valid_price(float(val))
except ValueError:
print(f"Error: invalid price for --pricing-output: '{val}' (expected a finite, non-negative number)", file=sys.stderr)
sys.exit(1)
i += 1
else:
i += 1
if not base_url or not default_model or not env_key:
@@ -2053,7 +2174,10 @@ def dispatch_command(cmd: str) -> None:
# direction of a link persisted in flipped endpoint order.
try:
from graphify.build import graph_has_legacy_ids as _legacy
_legacy_ids = _legacy(_raw.get("nodes", []))
from graphify.build import legacy_id_source_prefix as _legacy_prefix
_legacy_ids = _legacy(
_raw.get("nodes", []), source_prefix=_legacy_prefix(gp)
)
except Exception:
_legacy_ids = False
_rows = consumed_graph_rows(dict(_raw, links=_raw.get("links", [])))
@@ -4794,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
@@ -4940,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)
@@ -4958,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.
@@ -4978,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
@@ -5002,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)
@@ -5399,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
@@ -5556,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
@@ -5574,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:
+654 -9
View File
@@ -63,6 +63,7 @@ from graphify.extractors.csharp import (
_resolve_cross_file_csharp_imports,
_resolve_csharp_type_references,
bare_csharp_method_labels_in_nodes,
is_csharp_constructor_node,
)
from graphify.extractors.dart import extract_dart # noqa: F401
from graphify.extractors.dm import extract_dm, extract_dmf, extract_dmi, extract_dmm # noqa: F401
@@ -146,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,
@@ -369,6 +371,26 @@ def _suppress_ambiguous_python_imports(
except (OSError, RuntimeError):
return False
def _root_relative_source_file(source_file: str) -> str:
"""Scan-root-relative POSIX form of ``source_file`` for id hashing."""
if not source_file:
return ""
path = Path(source_file)
if not path.is_absolute():
return path.as_posix()
try:
return path.relative_to(root).as_posix()
except ValueError:
pass
try:
return path.resolve().relative_to(root).as_posix()
except (OSError, RuntimeError, ValueError):
pass
try:
return os.path.relpath(str(path), str(root)).replace("\\", "/")
except ValueError:
return path.name # different Windows drive: no relative path
kept_edges: list[dict] = []
for edge in edges:
if not isinstance(edge, dict):
@@ -427,10 +449,16 @@ def _suppress_ambiguous_python_imports(
continue
# A raw dotted alias could itself belong to an unrelated real node. Use
# a stable, node-less id so the graph builder drops the unresolved edge
# instead of fabricating a link to that node.
# instead of fabricating a link to that node. The id is hashed only
# from checkout-independent material: at this point source_file and the
# importer's node id still embed the absolute scan root, so the same
# commit built in two directories would mint different ids (#5044).
# The root-relative file, the import's location and the module name
# already identify the import site uniquely.
identity = "\0".join((
str(module_name), str(edge.get("source_file", "")),
str(edge.get("source_location", "")), str(edge.get("source", "")),
str(module_name),
_root_relative_source_file(str(edge.get("source_file", ""))),
str(edge.get("source_location", "")),
))
target = _make_id(f"ambiguous_python_import_{hashlib.sha1(identity.encode()).hexdigest()[:12]}")
while target in node_ids:
@@ -5003,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:
@@ -6132,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
@@ -6204,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", []))
@@ -6225,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:
@@ -6278,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:
@@ -6301,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}
@@ -6310,6 +6480,7 @@ def _csharp_overload_index(nodes: list[dict], edges: list[dict]) -> dict:
e.get("target"): e.get("source") for e in edges
if e.get("relation") == "method"
and "arity" in ((node_by_id.get(e.get("target")) or {}).get("metadata") or {})
and not is_csharp_constructor_node(node_by_id.get(e.get("target")) or {})
},
}
@@ -6405,6 +6576,13 @@ def _resolve_csharp_member_calls(
method_peers: dict[tuple[str, str], list[dict]] = {}
enclosing_type: dict[str, str] = {}
for e in all_edges:
if e.get("relation") == "defines" and e.get("context") == "field":
# A property/indexer whose accessors make calls is a caller in
# its type, like a method; it is never a method_index target.
owner, member = e.get("source"), e.get("target")
if _is_cs_file(e.get("source_file")) and isinstance(owner, str) and isinstance(member, str):
enclosing_type.setdefault(member, owner)
continue
if e.get("relation") != "method":
continue
src, tgt = e.get("source"), e.get("target")
@@ -6412,6 +6590,10 @@ def _resolve_csharp_member_calls(
if tnode is None:
continue
enclosing_type.setdefault(tgt, src)
if is_csharp_constructor_node(tnode):
continue # owns its calls (enclosing_type), but is never `x.Name()`
if (tnode.get("metadata") or {}).get("kind") == "operator":
continue # `operator +` is never written as a call name
# Overloads share a key: the first declared one stands for the name,
# and the call's argument count picks among them below (#4584).
method_key = (src, _key(tnode.get("label", "")))
@@ -6496,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,
)
@@ -6667,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],
@@ -7740,6 +8224,127 @@ def _resolve_c_include_edges(
e.pop("target_file", None)
def _resolve_csharp_constructor_calls(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link a C# construction to the constructor overload it runs.
`new X(a, b)` already has a `calls` edge to the type X (in-file or from
the shared/qualified passes). This adds one to the X constructor whose
parameter count fits two arguments, and links a constructor's
`: this(...)` to its own type's overload and `: base(...)` to its base
type's. Additive: the edge to the type stays.
Fail closed, never a guess across types or overloads:
* the type is the one the caller's own `calls` edges already bound for
that name; none, or two types with the name, gives no edge;
* `: base(...)` needs exactly one resolvable `inherits` target, and no
unresolved (out-of-corpus) base;
* exactly one non-static constructor (explicit or primary) must accept
the argument count (``_csharp_pick_overload``); a type with no
declared constructor gets no edge.
"""
records = [
rc for result in per_file if isinstance(result, dict)
for rc in result.get("raw_calls", []) or []
if rc.get("lang") == "csharp"
and (rc.get("csharp_ctor_site") or rc.get("csharp_ctor_init"))
]
if not records:
return
node_by_id = {n.get("id"): n for n in all_nodes}
ctors_of: dict[str, list[dict]] = {}
owner_of: dict[str, str] = {}
for e in all_edges:
if e.get("relation") != "method":
continue
tnode = node_by_id.get(e.get("target"))
type_nid = e.get("source")
if tnode is None or not isinstance(type_nid, str) or not is_csharp_constructor_node(tnode):
continue
owner_of.setdefault(tnode["id"], type_nid)
bucket = ctors_of.setdefault(type_nid, [])
if all(c["id"] != tnode["id"] for c in bucket):
bucket.append(tnode)
def _pick(type_nid: str | None, argc: object) -> dict | None:
ctors = [
c for c in ctors_of.get(type_nid or "", [])
if (c.get("metadata") or {}).get("signature") != "static"
]
if not ctors or not isinstance(argc, int):
return None
return _csharp_pick_overload(ctors, argc)
def _bare(label: object) -> str:
return re.sub(r"\W+", "", str(label or ""))
# caller -> bare type name -> {type nid: confidence of the `new` edge}
built: dict[str, dict[str, dict[str, str]]] = {}
callers = {rc.get("caller_nid") for rc in records if rc.get("csharp_ctor_site")}
for e in all_edges:
if e.get("relation") != "calls" or e.get("source") not in callers:
continue
tnode = node_by_id.get(e.get("target"))
if tnode is None or tnode["id"] in owner_of or not tnode.get("source_file"):
continue
built.setdefault(e["source"], {}).setdefault(_bare(tnode.get("label")), {})[
tnode["id"]
] = str(e.get("confidence") or "INFERRED")
bases_of: dict[str, set[str]] = {}
unresolved_base: set[str] = set()
for e in all_edges:
derived = e.get("source")
if (e.get("relation") != "inherits" or not isinstance(derived, str)
or not _is_cs_file(e.get("source_file"))):
continue
tnode = node_by_id.get(e.get("target"))
if tnode is None or not tnode.get("source_file"):
unresolved_base.add(derived)
else:
bases_of.setdefault(derived, set()).add(tnode["id"])
existing = {
(e.get("source"), e.get("target")) for e in all_edges if e.get("relation") == "calls"
}
for rc in records:
caller = rc.get("caller_nid")
if not caller:
continue
confidence = "EXTRACTED"
if rc.get("csharp_ctor_site"):
types = built.get(caller, {}).get(rc["csharp_ctor_site"], {})
if len(types) != 1:
continue
type_nid, confidence = next(iter(types.items()))
elif rc.get("csharp_ctor_init") == "this":
type_nid = owner_of.get(caller)
else:
owner = owner_of.get(caller)
bases = bases_of.get(owner or "", set())
if owner is None or owner in unresolved_base or len(bases) != 1:
continue
type_nid = next(iter(bases))
target = _pick(type_nid, rc.get("arity"))
if target is None or target["id"] == caller or (caller, target["id"]) in existing:
continue
existing.add((caller, target["id"]))
all_edges.append({
"source": caller,
"target": target["id"],
"relation": "calls",
"context": "call",
"confidence": confidence,
"confidence_score": 1.0 if confidence == "EXTRACTED" else 0.85,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
def _resolve_csharp_qualified_calls(
per_file: list[dict],
all_nodes: list[dict],
@@ -8583,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)
)
@@ -8674,6 +9285,14 @@ register_language_resolver(
"csharp_qualified_calls", frozenset({".cs"}), _resolve_csharp_qualified_calls
)
)
# C# constructors (`new X(a, b)`, `: base(...)`, `: this(...)`): the overload
# that runs, picked by argument count once the constructed type is bound.
# Runs after csharp_qualified_calls so every `new` has its type edge.
register_language_resolver(
LanguageResolver(
"csharp_constructor_calls", frozenset({".cs"}), _resolve_csharp_constructor_calls
)
)
# C# member-level interface dispatch (#3003): a call through an injected
# dependency lands on the interface's method, so the implementation sits in the
# graph unreachable from the call site. Lives in graphify.csharp_dispatch;
@@ -10359,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.
@@ -10398,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:
@@ -11115,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
@@ -11196,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 []:
@@ -11401,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}
@@ -11530,6 +12163,9 @@ def extract(
for n in resolution_nodes:
if n.get("file_type") == "rationale" or n.get("type") == "namespace":
continue
# A C# constructor is named like its type but never called by name.
if is_csharp_constructor_node(n):
continue
raw = n.get("label", "")
normalised = raw.strip("()").lstrip(".")
if normalised:
@@ -11678,6 +12314,7 @@ def extract(
)
_csharp_stub_resolver: CsharpNameResolver | None = None # built on first use
_csharp_method_owner: dict[str, str] | None = None # method nid -> type nid, built on first use
_csharp_member_owner: dict[str, str] | None = None # property/indexer nid -> type nid, ditto
_csharp_outer_type: dict[str, str] | None = None # nested type nid -> outer type label, built on first use
_csharp_overload_cache: dict = {} # filled on first use (#4584)
_jvm_index = None # built on first Kotlin/Java bare call (#4935)
@@ -11921,7 +12558,15 @@ def extract(
e["target"]: e["source"] for e in all_edges
if e.get("relation") == "method"
}
caller_owner = _csharp_method_owner.get(rc.get("caller_nid", ""))
if _csharp_member_owner is None:
# A property/indexer accessor's call: its type is the owner.
_csharp_member_owner = {
e["target"]: e["source"] for e in all_edges
if e.get("relation") == "defines" and e.get("context") == "field"
}
caller_owner = _csharp_method_owner.get(
rc.get("caller_nid", ""), _csharp_member_owner.get(rc.get("caller_nid", ""))
)
if caller_owner is not None:
own_type_matches = [
c for c in candidates if _csharp_method_owner.get(c) == caller_owner
+43
View File
@@ -18,6 +18,21 @@ from graphify.extractors.base import _make_id
from graphify.rcfile import effective_suffix
def is_csharp_constructor_node(node: dict) -> bool:
"""A C# constructor node (instance, static or primary).
A constructor carries its type's name but is reached only through `new`
or a `: base(...)` / `: this(...)` initializer, never by that name, so the
name-keyed call indexes leave it out.
"""
metadata = node.get("metadata") or {}
return (
isinstance(metadata, dict)
and metadata.get("kind") == "constructor"
and effective_suffix(str(node.get("source_file") or "")) == ".cs"
)
def _build_csharp_type_def_index(
all_nodes: list[dict],
all_edges: list[dict] | None = None,
@@ -407,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, []):
+374 -43
View File
@@ -194,7 +194,7 @@ def _csharp_type_name_for_id(node, class_name: str) -> str:
return f"{class_name}`{arity}" if arity else class_name
def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dict]:
"""A C# method's parameter signature and the argument counts it accepts.
The signature (``"`1:this Foo,ref int,params int[]"``) tells overloads
@@ -205,7 +205,24 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
parts: list[str] = []
arity = required = 0
variadic = extension = False
params = node.child_by_field_name("parameters")
# 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 (#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":
@@ -218,6 +235,23 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
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":
@@ -225,10 +259,9 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
parts.append("params " + ("".join(_read_text(type_node, source).split()) if type_node is not None else ""))
arity += 1
variadic = True
type_params = 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}"
@@ -239,6 +272,16 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
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
@@ -250,6 +293,17 @@ def _csharp_argc(call_node) -> int | None:
return sum(1 for c in args.children if c.type == "argument") if args is not None else 0
def _csharp_creation_argc(node) -> int:
"""Argument count of a C# `new X(...)` / `new X { ... }` / `: base(...)`.
No argument list (`new X { A = 1 }`) runs the parameterless constructor.
"""
args = node.child_by_field_name("arguments")
if args is None:
args = next((c for c in node.children if c.type == "argument_list"), None)
return sum(1 for c in args.children if c.type == "argument") if args is not None else 0
def _csharp_pick_overload(overloads: list[dict], argc: int | None) -> dict | None:
"""The one overload a call with ``argc`` arguments can mean, or None.
@@ -275,7 +329,7 @@ def _csharp_pick_overload(overloads: list[dict], argc: int | None) -> dict | Non
def _csharp_pre_scan_name_collisions(
root_node, source: bytes, stem: str
) -> tuple[dict[str, set[str]], dict[str, set[str]]]:
) -> tuple[dict[str, set[str]], dict[str, set[str]], set[str]]:
"""Pre-scan a C# file for declared names that collapse to one node id.
C# is case-sensitive and `_Name` is the usual spelling of a private member,
@@ -287,8 +341,11 @@ def _csharp_pre_scan_name_collisions(
the Python #3302 collision in C#; the outcome is the same rule
(``_underscore_salted_nid``).
Returns ``(type_groups, member_groups)``, each ``{plain_nid: {raw names}}``
for the ids two or more distinct names would share. Types are keyed the way
Returns ``(type_groups, member_groups, member_ids)``: the first two are
``{plain_nid: {raw names}}`` for the ids two or more distinct names would
share; ``member_ids`` is every member's plain id, which a constructor's or
indexer's id must not take (a C# method may be spelled like its type in
another case, and a member may be spelled `This`). Types are keyed the way
the walk mints them (``_make_id(stem, namespace, name_for_id)``), members
(methods, properties, enum members) by ``_make_id(type_nid, name)`` where
``type_nid`` is the type's FINAL id, already salted when the type itself
@@ -349,7 +406,7 @@ def _csharp_pre_scan_name_collisions(
for decl, plain, name in type_decls:
_members(decl, _underscore_salted_nid(plain, name, type_groups))
member_groups = {nid: names for nid, names in member_names.items() if len(names) >= 2}
return type_groups, member_groups
return type_groups, member_groups, set(member_names)
def _csharp_classify_base(name: str, interface_names: set[str]) -> str:
@@ -3268,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]
@@ -3283,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
@@ -3387,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({
@@ -4226,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
@@ -6569,10 +6695,15 @@ def _extract_generic(
csharp_interface_names: set[str] = set()
csharp_type_groups: dict[str, set[str]] = {}
csharp_member_groups: dict[str, set[str]] = {}
csharp_member_ids: set[str] = set()
# plain constructor nid -> {signature: node}, like csharp_overloads.
csharp_ctor_overloads: dict[str, dict[str, dict]] = {}
# plain indexer nid -> {signature: node}, like csharp_overloads.
csharp_indexer_overloads: dict[str, dict[str, dict]] = {}
if config.ts_module == "tree_sitter_c_sharp":
csharp_interface_names = _csharp_pre_scan_interfaces(root, source)
csharp_type_groups, csharp_member_groups = _csharp_pre_scan_name_collisions(
root, source, stem
csharp_type_groups, csharp_member_groups, csharp_member_ids = (
_csharp_pre_scan_name_collisions(root, source, stem)
)
swift_protocol_names: set[str] = set()
@@ -6706,6 +6837,65 @@ def _extract_generic(
file_metadata["ruby_external_method_owners"] = external_owners
file_node["metadata"] = sanitize_metadata(file_metadata)
# C# `new X(...)` sites and `: base(...)` / `: this(...)` initializers.
# They join raw_calls after the call walk, with no `callee`, so every
# name-keyed consumer skips them and only the constructor pass reads them.
csharp_ctor_records: list[dict] = []
def csharp_add_constructor(type_nid: str, type_name: str, decl, params,
line: int, static: bool) -> str:
"""Mint the node for one C# constructor and own it from its type.
The id is the one a method named after the type would get, so the
first declared constructor keeps it and each other signature is salted
like a method overload (#4584). A member spelled like the type in
another case (`Foo` / `foo()`) already owns that id: the constructor,
never the existing member, takes a salted one. A static constructor
has no parameters and is never what `new` runs, so it is its own
signature.
"""
signature, meta = _csharp_method_signature(decl, source, params)
if static:
signature, meta = "static", {"arity": 0}
ctor_nid = _make_id(type_nid, type_name)
if ctor_nid in csharp_member_ids:
ctor_nid = _make_id(ctor_nid, hashlib.sha1(
b".ctor", usedforsecurity=False).hexdigest()[:6])
group = csharp_ctor_overloads.setdefault(ctor_nid, {})
if group and signature not in group:
ctor_nid = _make_id(ctor_nid, hashlib.sha1(
signature.encode("utf-8"), usedforsecurity=False).hexdigest()[:6])
add_node(ctor_nid, f".{type_name}()", line,
metadata={**meta, "signature": signature, "kind": "constructor"})
if signature not in group and nodes and nodes[-1]["id"] == ctor_nid:
group[signature] = nodes[-1]
add_edge(type_nid, ctor_nid, "method", line)
return ctor_nid
def csharp_queue_member_bodies(member_nid: str, decl, class_nid: str) -> None:
"""Walk a C# property's or indexer's accessor bodies as its calls.
`get { ... }` / `set => ...` and an expression body (`int P => F();`)
run code just like a method, so their calls belong to the member. An
auto-accessor (`get;`) and an initializer (`= F();`, which runs in the
constructor) have no body here. The declaration is the scope, so an
indexer's parameters type receivers in every accessor.
"""
bodies = []
accessors = decl.child_by_field_name("accessors")
if accessors is not None:
for accessor in accessors.children:
if accessor.type == "accessor_declaration":
body = accessor.child_by_field_name("body")
if body is not None:
bodies.append(body)
value = decl.child_by_field_name("value")
if value is not None and value.type == "arrow_expression_clause":
bodies.append(value)
for body in bodies:
csharp_method_scopes[id(body)] = (decl, class_nid)
function_bodies.append((member_nid, body))
def walk(node, parent_class_nid: str | None = None) -> None:
nonlocal ruby_singleton_context_depth
t = node.type
@@ -6913,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
@@ -6926,6 +7119,17 @@ def _extract_generic(
add_edge(parent_class_nid, class_nid, "contains", line)
else:
add_edge(file_nid, class_nid, "contains", line)
if config.ts_module == "tree_sitter_c_sharp" and t != "interface_declaration":
# `class Foo(int x)` / `record R(int A)`: the primary
# constructor is one of Foo's constructors, so `new Foo(1)`
# must weigh it against the explicit ones (it has no body).
primary_params = next(
(c for c in node.children if c.type == "parameter_list"), None
)
if primary_params is not None:
csharp_add_constructor(
class_nid, class_name, node, primary_params, line, False
)
# TS/JS decorators on the class and its members (@Component, @Injectable,
# @Input, @Inject, @Entity, …). Decorators live only in class subtrees.
@@ -7709,12 +7913,101 @@ def _extract_generic(
if (config.ts_module == "tree_sitter_c_sharp"
and t == "constructor_declaration"
and parent_class_nid):
# A C# constructor has no node of its own, so its body was never
# walked for calls. Attribute them to the declaring type (#4246).
ctor_body = node.child_by_field_name("body")
if ctor_body is not None:
csharp_method_scopes[id(ctor_body)] = (node, parent_class_nid)
function_bodies.append((parent_class_nid, ctor_body))
# A constructor is a node of its own, like a method, so the calls
# in its body and initializer are its calls, not the type's
# (#4246 credited them to the type).
ctor_name_node = node.child_by_field_name("name")
ctor_name = _read_text(ctor_name_node, source) if ctor_name_node is not None else ""
if ctor_name:
ctor_line = node.start_point[0] + 1
ctor_nid = csharp_add_constructor(
parent_class_nid, ctor_name, node, None, ctor_line,
any(c.type == "modifier" and _read_text(c, source) == "static"
for c in node.children),
)
for part in node.children:
if part.type == "constructor_initializer":
csharp_method_scopes[id(part)] = (node, parent_class_nid)
function_bodies.append((ctor_nid, part))
keyword = next((c.type for c in part.children
if c.type in ("base", "this")), None)
if keyword is not None:
csharp_ctor_records.append({
"caller_nid": ctor_nid,
"lang": "csharp",
"csharp_ctor_init": keyword,
"arity": _csharp_creation_argc(part),
"source_file": str_path,
"source_location": f"L{part.start_point[0] + 1}",
})
ctor_body = node.child_by_field_name("body")
if ctor_body is not None:
csharp_method_scopes[id(ctor_body)] = (node, parent_class_nid)
function_bodies.append((ctor_nid, ctor_body))
if (config.ts_module == "tree_sitter_c_sharp"
and t == "indexer_declaration"
and parent_class_nid):
# `this[int i]` is a property with parameters: a `this[]` node
# beside the properties, so its accessors' calls have a caller.
# Overloads (`this[int]`, `this[string]`) are salted by signature
# like methods (#4584); a member spelled `This` keeps its id.
signature, meta = _csharp_method_signature(node, source)
explicit = next((c for c in node.children
if c.type == "explicit_interface_specifier"), None)
if explicit is not None:
# `IList<T>.this[int]` and `IList.this[int]` are two indexers.
signature = "".join(_read_text(explicit, source).split()) + signature
indexer_line = node.start_point[0] + 1
indexer_nid = _make_id(parent_class_nid, "this")
if indexer_nid in csharp_member_ids:
indexer_nid = _make_id(indexer_nid, hashlib.sha1(
b"this[]", usedforsecurity=False).hexdigest()[:6])
group = csharp_indexer_overloads.setdefault(indexer_nid, {})
if group and signature not in group:
indexer_nid = _make_id(indexer_nid, hashlib.sha1(
signature.encode("utf-8"), usedforsecurity=False).hexdigest()[:6])
add_node(indexer_nid, "this[]", indexer_line,
metadata={**meta, "signature": signature, "kind": "indexer"})
if signature not in group and nodes and nodes[-1]["id"] == indexer_nid:
group[signature] = nodes[-1]
add_edge(parent_class_nid, indexer_nid, "defines", indexer_line, context="field")
csharp_queue_member_bodies(indexer_nid, node, parent_class_nid)
return
if (config.ts_module == "tree_sitter_c_sharp"
and t in ("operator_declaration", "conversion_operator_declaration")
and parent_class_nid):
# A user-defined operator or conversion is a static method with a
# body, so it is a member node and its calls are its own. Its name
# is spelled the way C# writes it (`operator +`, `operator int`)
# and is never a call name, so the id always carries the
# signature: several conversions share one parameter list.
if t == "operator_declaration":
op = node.child_by_field_name("operator")
op_name = "operator " + (_read_text(op, source) if op is not None else "")
op_key = op_name
else:
to_type = node.child_by_field_name("type")
op_name = "operator " + (
"".join(_read_text(to_type, source).split()) if to_type is not None else ""
)
direction = next((c.type for c in node.children
if c.type in ("implicit", "explicit")), "")
op_key = f"{direction} {op_name}"
signature, meta = _csharp_method_signature(node, source)
signature = f"{op_key}:{signature}"
op_line = node.start_point[0] + 1
op_nid = _make_id(parent_class_nid, "operator", hashlib.sha1(
signature.encode("utf-8"), usedforsecurity=False).hexdigest()[:6])
add_node(op_nid, f".{op_name}()", op_line,
metadata={**meta, "signature": signature, "kind": "operator"})
add_edge(parent_class_nid, op_nid, "method", op_line)
op_body = node.child_by_field_name("body")
if op_body is not None:
csharp_method_scopes[id(op_body)] = (node, parent_class_nid)
function_bodies.append((op_nid, op_body))
return
if (config.ts_module == "tree_sitter_c_sharp"
and t == "field_declaration"
@@ -7816,6 +8109,11 @@ def _extract_generic(
add_node(property_nid, property_name, property_line)
add_edge(parent_class_nid, property_nid, "defines",
property_line, context="field")
# Only the declaration that owns the node: an id
# another member already took (a method spelled
# like an explicit `IFoo.Name` property) must not
# be credited with this property's calls.
csharp_queue_member_bodies(property_nid, node, parent_class_nid)
type_node = node.child_by_field_name("type")
if type_node is not None:
# Record the property's declared type for the method-scoped
@@ -9193,6 +9491,12 @@ def _extract_generic(
continue
if n["id"] in _case_of_targets:
continue
# A C# constructor shares its type's name; it is reached through `new`
# or an initializer, never a bare call, and must not shadow the type.
if config.ts_module == "tree_sitter_c_sharp" and (
(n.get("metadata") or {}).get("kind") == "constructor"
):
continue
raw = n["label"]
normalised = raw.strip("()").lstrip(".")
if config.ts_module == "tree_sitter_lua":
@@ -9269,6 +9573,15 @@ def _extract_generic(
if config.ts_module in _SELF_CALL_LANGUAGES or lexical_calls:
label_by_nid = {n["id"]: n["label"] for n in nodes}
for e in edges:
if (
config.ts_module == "tree_sitter_c_sharp"
and e["relation"] == "defines"
and e.get("context") == "field"
):
# A property/indexer whose accessors make calls: an
# unqualified call in them looks in its type first, like a
# method's. Owner only: it is never a call target by name.
method_owner.setdefault(e["target"], e["source"])
if e["relation"] == "method":
method_owner[e["target"]] = e["source"]
name = label_by_nid.get(e["target"], "").strip("()").lstrip(".")
@@ -10009,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.
@@ -10296,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
@@ -10404,6 +10717,18 @@ def _extract_generic(
peers = csharp_overload_peers[tgt_nid]
picked = _csharp_pick_overload(peers, _csharp_argc(node))
tgt_nid = (picked or peers[0])["id"]
if (config.ts_module == "tree_sitter_c_sharp"
and node.type == "object_creation_expression" and callee_name):
# Which constructor runs is picked corpus-wide once the
# type is bound (_resolve_csharp_constructor_calls).
csharp_ctor_records.append({
"caller_nid": caller_nid,
"lang": "csharp",
"csharp_ctor_site": callee_name,
"arity": _csharp_creation_argc(node),
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
external_stub_target = bool(tgt_nid and not nid_to_sf.get(tgt_nid))
if tgt_nid and not external_stub_target:
pair = (caller_nid, tgt_nid)
@@ -10509,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
@@ -10896,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
@@ -11063,6 +11393,7 @@ def _extract_generic(
raw_calls.extend(_python_property_reads(
function_bodies, source, str_path, python_var_types, python_attr_types, method_owner,
))
raw_calls.extend(csharp_ctor_records)
result = {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
# Export the per-file field->type tables for the corpus member-call
# resolvers (#3151): a field declared on a superclass in ANOTHER file can
+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.
+706 -37
View File
@@ -9,6 +9,7 @@ from typing import Any
from tree_sitter import Node
from graphify.extractors.base import _file_stem, _make_id, _read_source_bytes, _read_text
from graphify.extractors.engine import _underscore_salted_nid
_IDENTIFIER = re.compile(r"[A-Za-z_$][A-Za-z0-9_$]*")
@@ -27,6 +28,28 @@ def _unquote(value: str) -> str:
return value
def _rightmost_operand(obj: Node) -> Node:
"""The receiver of a member call whose object tree-sitter-solidity merged
with a preceding operator (see :func:`_callee_text`)."""
base = obj
while True:
unwrapped = base.named_children[0] if base.type == "expression" and base.named_children else base
right = (
unwrapped.child_by_field_name("right") if unwrapped.type == "binary_expression"
else unwrapped.child_by_field_name("argument") if unwrapped.type == "unary_expression"
else None
)
if right is None:
return base
base = right
def _member_callee(callee: Node) -> Node | None:
"""The ``member_expression`` of a member call ``recv.f(..)``, else ``None``."""
inner = callee.named_children[0] if callee.type == "expression" and callee.named_children else callee
return inner if inner.type == "member_expression" else None
def _callee_text(callee: Node, source: bytes) -> str:
"""The callee as written, e.g. ``super.supportsInterface`` or ``_check``.
@@ -36,27 +59,149 @@ def _callee_text(callee: Node, source: bytes) -> str:
is seen as ``super.f`` (and ``a && b.c(x)`` as ``b.c``). A prefix operator
is swallowed the same way: ``!Lib.f(x)`` parses as ``(!Lib).f``.
"""
inner = callee.named_children[0] if callee.type == "expression" and callee.named_children else callee
if inner.type == "member_expression":
inner = _member_callee(callee)
if inner is not None:
obj = inner.child_by_field_name("object")
prop = inner.child_by_field_name("property")
if obj is not None and prop is not None:
base = obj
while True:
unwrapped = base.named_children[0] if base.type == "expression" and base.named_children else base
right = (
unwrapped.child_by_field_name("right") if unwrapped.type == "binary_expression"
else unwrapped.child_by_field_name("argument") if unwrapped.type == "unary_expression"
else None
)
if right is None:
break
base = right
base = _rightmost_operand(obj)
if base is not obj:
return f"{_read_text(base, source)}.{_read_text(prop, source)}"
return _read_text(callee, source)
_SIMPLE_MEMBERS = {
"struct_declaration": "struct",
"enum_declaration": "enum",
"event_definition": "event",
"error_declaration": "error",
"state_variable_declaration": "state_variable",
}
def _callable_signature(declaration: Node, source: bytes) -> str:
"""``arity:types`` of a function, modifier or constructor, the part of its
id that keeps overloads apart."""
parameters = [
child for child in declaration.named_children
if child.type in {"parameter", "fallback_receive_parameter"}
]
types = ",".join(
_read_text(child.child_by_field_name("type"), source)
for child in parameters
if child.child_by_field_name("type") is not None
)
return f"{len(parameters)}:{types}"
def _member_identity(member: Node, source: bytes) -> tuple[str, str, str] | None:
"""``(kind, name, signature)`` a contract member's node id is made from,
as extract_solidity's ``add_member`` mints it; ``None`` for a member that
gets no id there."""
if member.type in _SIMPLE_MEMBERS:
name_node = member.child_by_field_name("name")
if name_node is None:
return None
name = _read_text(name_node, source)
return _SIMPLE_MEMBERS[member.type], name, name
if member.type == "constructor_definition":
return "constructor", "constructor", _callable_signature(member, source)
if member.type == "fallback_receive_definition":
name = "receive" if _read_text(member, source).lstrip().startswith("receive") else "fallback"
return name, name, _callable_signature(member, source)
if member.type in {"function_definition", "modifier_definition"}:
name_node = member.child_by_field_name("name")
if name_node is None:
return None
kind = "modifier" if member.type == "modifier_definition" else "function"
return kind, _read_text(name_node, source), _callable_signature(member, source)
return None
def _collision_groups(declared: list[tuple[str, str]]) -> dict[str, set[str]]:
"""``{plain id: {names}}`` for the plain ids two or more distinct names
would share. ``make_id`` drops a leading ``_`` and folds case, so
``_grantRole(bytes32,address)`` and ``grantRole(bytes32,address)`` in one
contract mint ONE id; an overload is one name, never a collision."""
groups: dict[str, set[str]] = {}
for plain, name in declared:
groups.setdefault(plain, set()).add(name)
return {plain: names for plain, names in groups.items() if len(names) >= 2}
# A type's written text is read in the contract it was written in (its name
# and the structs/enums/value types it declares), see extract_solidity.qualify.
TypeContext = tuple[str | None, frozenset[str]]
# Variable name -> (normalized type text, context); None when ambiguous.
VariableTypes = dict[str, tuple[str, TypeContext] | None]
_ELEMENTARY_ALIASES = {"uint": "uint256", "int": "int256", "byte": "bytes1"}
_MAPPING_VALUE_NAME = re.compile(r"(.*\S) ([A-Za-z_$][A-Za-z0-9_$]*)")
def _normalize_type(text: str) -> str:
"""One spelling per type: whitespace collapsed (``mapping(a => b)`` ->
``mapping(a=>b)``) and the elementary aliases expanded (``uint`` ->
``uint256``), so a receiver's type compares equal to a ``using`` target or
a parameter written differently."""
text = re.sub(r"\s+", " ", text).strip()
text = re.sub(r" ?([\[\]().,]|=>) ?", r"\1", text)
return re.sub(r"\b(uint|int|byte)\b", lambda m: _ELEMENTARY_ALIASES[m.group(1)], text)
def _element_type(text: str) -> str | None:
"""The value type of ``mapping(K=>V)`` or the element type of ``T[]`` /
``T[n]`` (normalized text), else ``None``."""
if text.startswith("mapping(") and text.endswith(")"):
inner = text[len("mapping("):-1]
depth = 0
for index, char in enumerate(inner):
if char == "(":
depth += 1
elif char == ")":
depth -= 1
elif depth == 0 and inner.startswith("=>", index):
value = inner[index + 2:]
# A named mapping value (`mapping(address a => uint256 b)`).
named = _MAPPING_VALUE_NAME.fullmatch(value)
if named and named.group(2) != "payable":
value = named.group(1)
return value
return None
if text.endswith("]"):
depth = 0
for index in range(len(text) - 1, -1, -1):
if text[index] == "]":
depth += 1
elif text[index] == "[":
depth -= 1
if depth == 0:
return text[:index] or None
return None
# Globals the language types itself, so `msg.sender.f()` and
# `keccak256(b).f()` are typed like a declared variable.
_BUILTIN_MEMBER_TYPES = {
"msg.sender": "address",
"msg.value": "uint256",
"tx.origin": "address",
"block.timestamp": "uint256",
"block.number": "uint256",
"block.chainid": "uint256",
}
_BUILTIN_CALL_TYPES = {
"keccak256": "bytes32",
"sha256": "bytes32",
"blockhash": "bytes32",
"abi.encode": "bytes",
"abi.encodePacked": "bytes",
"abi.encodeWithSelector": "bytes",
"abi.encodeWithSignature": "bytes",
"abi.encodeCall": "bytes",
}
def _inherited_call(
caller_id: str, callee: str, arity: int | None, kind: str, source_file: str, node: Node,
) -> dict[str, Any]:
@@ -149,6 +294,25 @@ def resolve_solidity_inherited_calls(
to the member of the one library/contract/interface of that name the
caller's file declares or imports directly; no edge when the name or the
(name, arity) is ambiguous.
A call on a receiver of a contract or interface type (``IERC20 token;
token.transfer()``, ``IERC20(a).transfer()``, ``Ownable(x).owner()``,
``token().clock()``) binds by name and arity through that type's
linearization, as the compiler looks it up: an interface method links to
the interface's own declaration, never to a guessed implementer. No edge
when the receiver's type is unknown, is not exactly one visible
contract/interface, when the name/arity is ambiguous, or when a public
state variable of that name (its getter) comes first.
A call attached by a ``using`` directive (``using SafeCast for uint256;
x.toUint48()``, ``using EnumerableSet for EnumerableSet.AddressSet;
_set.add(a)``) binds to the library or free function it attaches: the
directives of the caller's contract and file, and the ``global`` ones of
the receiver's type, whose target is ``*`` or the receiver's declared
type, offering a function of that name with one more parameter than the
call passes (the receiver) and the receiver's type as its first. Only a
single such function is linked; no edge when the receiver's type is
unknown, a directive's library is ambiguous, or two functions fit.
"""
calls = [
rc
@@ -170,6 +334,8 @@ def resolve_solidity_inherited_calls(
functions: dict[str, dict[str, list[tuple[str, Any]]]] = {}
modifiers: dict[str, dict[str, list[str]]] = {}
bases: dict[str, list[str]] = {}
using: dict[str, list[dict]] = {}
state_variables: dict[str, dict[str, str]] = {}
existing: set[tuple[Any, Any, Any]] = set()
for edge in all_edges:
source, target, relation = edge.get("source"), edge.get("target"), edge.get("relation")
@@ -179,6 +345,8 @@ def resolve_solidity_inherited_calls(
source_meta = meta(source)
if source_meta.get("language") != "solidity" or source_meta.get("kind") not in type_kinds:
continue
if isinstance(source_meta.get("using"), list):
using[source] = source_meta["using"]
if relation == "method":
member = meta(target)
name = str(node_by_id.get(target, {}).get("label", ""))
@@ -190,6 +358,8 @@ def resolve_solidity_inherited_calls(
)
elif member.get("kind") == "modifier":
modifiers.setdefault(source, {}).setdefault(name, []).append(target)
elif relation == "contains" and meta(target).get("kind") == "state_variable":
state_variables.setdefault(source, {})[str(node_by_id.get(target, {}).get("label", ""))] = target
elif relation == "contains" and meta(target).get("kind") in {"event", "error"}:
# An event/error is a call target too (`emit E()`, `revert Err()`).
functions.setdefault(source, {}).setdefault(
@@ -200,12 +370,17 @@ def resolve_solidity_inherited_calls(
def find(linear: list[str], name: str, arity: Any, kind: str) -> str | None:
for type_id in linear:
if kind == "member" and name in state_variables.get(type_id, {}):
# `x.name()` reads a public state variable's getter.
return None
if kind == "modifier":
found = modifiers.get(type_id, {}).get(name, [])
else:
found = [
nid for nid, declared in functions.get(type_id, {}).get(name, [])
if arity is None or declared is None or declared == arity
if (arity is None or declared is None or declared == arity)
# A value's members are its functions, not its events/errors.
and (kind != "member" or meta(nid).get("kind") == "function")
]
if found:
return found[0] if len(found) == 1 else None
@@ -216,13 +391,22 @@ def resolve_solidity_inherited_calls(
types_by_file: dict[tuple[str, str], list[str]] = {}
file_by_id: dict[Any, str] = {}
imported: dict[str, set[str]] = {}
if any(rc["solidity_call"] == "qualified" for rc in calls):
# `using` directives at file level, and the `global` ones by type.
file_using: dict[str, list[dict]] = {}
global_using: list[tuple[dict, str]] = []
# Free functions by (file, name), for `using {f} for T`.
free_functions: dict[tuple[str, str], list[str]] = {}
if any(rc["solidity_call"] in {"qualified", "member"} for rc in calls):
for node in all_nodes:
node_file = node.get("source_file")
if not node_file:
continue
if node.get("label") == Path(str(node_file)).name:
file_by_id[node.get("id")] = str(node_file)
directives = meta(node.get("id")).get("using")
if isinstance(directives, list):
file_using[str(node_file)] = directives
global_using.extend((d, str(node_file)) for d in directives if d.get("global"))
elif meta(node.get("id")).get("kind") in type_kinds:
types_by_file.setdefault((str(node_file), str(node.get("label", ""))), []).append(node["id"])
for edge in all_edges:
@@ -231,8 +415,172 @@ def resolve_solidity_inherited_calls(
imported_file = file_by_id.get(edge.get("target"))
if importer and imported_file:
imported.setdefault(importer, set()).add(imported_file)
elif (
edge.get("relation") == "contains"
and edge.get("source") in file_by_id
and meta(edge.get("target")).get("kind") == "function"
):
name = str(node_by_id.get(edge.get("target"), {}).get("label", ""))
free_functions.setdefault(
(file_by_id[edge["source"]], name[:-2] if name.endswith("()") else name), [],
).append(str(edge["target"]))
reachable_cache: dict[str, list[str]] = {}
def reachable(caller_file: str) -> list[str]:
"""Every file ``caller_file`` imports, directly or through the files
it imports (`import {IERC20} from "./ERC20.sol"` re-exports a type
ERC20.sol itself imports)."""
if caller_file not in reachable_cache:
seen: set[str] = set()
stack = sorted(imported.get(caller_file, set()))
while stack:
current = stack.pop()
if current in seen or current == caller_file:
continue
seen.add(current)
stack.extend(sorted(imported.get(current, set())))
reachable_cache[caller_file] = sorted(seen)
return reachable_cache[caller_file]
def visible_types(caller_file: str, name: str, transitive: bool = False) -> list[str]:
"""The types named ``name`` that ``caller_file`` declares or imports
directly; with ``transitive``, when there is none, those of every
file it reaches through its imports."""
found = types_by_file.get((caller_file, name), []) + [
type_id
for imported_file in sorted(imported.get(caller_file, set()))
for type_id in types_by_file.get((imported_file, name), [])
]
if found or not transitive:
return found
return [
type_id
for reached in reachable(caller_file)
for type_id in types_by_file.get((reached, name), [])
]
linear_cache: dict[str, list[str]] = {}
def linearization(type_id: str) -> list[str]:
if type_id not in linear_cache:
linear_cache[type_id] = _c3_linearization(type_id, bases)
return linear_cache[type_id]
def receiver_types(rc: dict) -> list[tuple[str, str]]:
"""``(type, file)`` readings of a member call's receiver, best first:
the type the extractor read (a local, parameter, own state variable
or conversion), a base contract's state variable of the receiver's
name, or the declared return type of the function ``g`` in
``g(..).f()``. ``file`` is the file whose scope names the type."""
caller = rc.get("caller_nid")
readings: list[tuple[str, str]] = []
caller_file = str(node_by_id.get(caller, {}).get("source_file", ""))
if rc.get("receiver_type"):
readings.append((str(rc["receiver_type"]), caller_file))
contract = owner.get(str(caller))
if not contract:
return readings
linear = linearization(contract)
variable = rc.get("qualifier") if rc["solidity_call"] == "qualified" else None
if variable:
# Not a local or own state variable (the extractor checked), so
# maybe a base contract's.
for type_id in linear[1:]:
nid = state_variables.get(type_id, {}).get(str(variable))
if nid is not None:
declared = meta(nid).get("declared_type")
if declared:
readings.append((str(declared), str(node_by_id[nid].get("source_file", ""))))
break
result_of = rc.get("receiver_call")
if isinstance(result_of, list) and len(result_of) == 2:
function = find(linear, str(result_of[0]), result_of[1], "inherited")
returned = meta(function).get("returns") if function else None
if function and returned:
readings.append((str(returned), str(node_by_id[function].get("source_file", ""))))
return readings
def typed_member(rc: dict, name: str) -> str | None:
"""``recv.name()`` bound through the receiver's contract/interface
type, the first reading of it that names a visible type."""
for type_name, scope_file in receiver_types(rc):
scope = visible_types(scope_file, type_name, transitive=True)
if not scope:
# Not a type here (`uint256`, or `g(x)` was a call, not a
# conversion): try the next reading.
continue
# Fail closed when the type is ambiguous or a library (a value
# never has a library type).
if len(scope) != 1 or meta(scope[0]).get("kind") not in {"contract", "interface"}:
return None
return find(linearization(scope[0]), name, rc.get("arity"), "member")
def visible_free_functions(scope_file: str, name: str) -> list[str]:
direct = free_functions.get((scope_file, name), []) + [
nid
for imported_file in sorted(imported.get(scope_file, set()))
for nid in free_functions.get((imported_file, name), [])
]
return direct or [
nid for reached in reachable(scope_file) for nid in free_functions.get((reached, name), [])
]
def attached_functions(directive: dict, scope_file: str, name: str) -> list[str] | None:
"""The functions named ``name`` that ``directive`` attaches, read in
``scope_file``; ``None`` when its library is ambiguous."""
if "library" in directive:
libraries = visible_types(scope_file, str(directive["library"]), transitive=True)
if not libraries:
return [] # a library outside the corpus
if len(libraries) != 1 or meta(libraries[0]).get("kind") != "library":
return None
return [nid for nid, _arity in functions.get(libraries[0], {}).get(name, [])]
attached: list[str] = []
for bound in directive.get("functions", []):
qualifier, _, function = str(bound).rpartition(".")
if function != name:
continue
if not qualifier:
attached.extend(visible_free_functions(scope_file, function))
continue
libraries = visible_types(scope_file, qualifier, transitive=True)
if len(libraries) > 1:
return None
if libraries:
attached.extend(nid for nid, _arity in functions.get(libraries[0], {}).get(function, []))
return attached
def using_member(rc: dict, name: str) -> str | None:
"""``recv.name()`` bound to the one function a ``using`` directive in
scope attaches to the receiver's type, if there is exactly one."""
caller = str(rc.get("caller_nid"))
caller_file = str(node_by_id.get(caller, {}).get("source_file", ""))
contract = owner.get(caller)
scoped = [(d, caller_file) for d in using.get(contract or "", [])] + [
(d, caller_file) for d in file_using.get(caller_file, []) if not d.get("global")
]
arity = rc.get("arity")
if not isinstance(arity, int):
return None
for type_name, _scope_file in receiver_types(rc):
directives = scoped + [(d, f) for d, f in global_using if d.get("for") == type_name]
found: set[str] = set()
for directive, scope_file in directives:
if directive.get("for") not in {"*", type_name}:
continue
attached = attached_functions(directive, scope_file, name)
if attached is None:
return None
found.update(
nid for nid in attached
if meta(nid).get("arity") == arity + 1
and meta(nid).get("first_param_type") == type_name
)
if found:
return next(iter(found)) if len(found) == 1 else None
return None
for rc in calls:
caller = rc.get("caller_nid")
name = rc.get("callee")
@@ -240,25 +588,29 @@ def resolve_solidity_inherited_calls(
continue
kind = rc["solidity_call"]
contract = owner.get(caller)
if kind == "qualified":
if kind == "member":
# A type's own member beats a `using`-attached function (Solidity
# resolution precedence), so try the typed receiver first.
target = typed_member(rc, name) or using_member(rc, name)
elif kind == "qualified":
# `Lib.f()` names its type, so it needs no owning contract (a free
# function calls libraries too).
caller_file = str(node_by_id.get(caller, {}).get("source_file", ""))
qualifier = str(rc.get("qualifier", ""))
scope = types_by_file.get((caller_file, qualifier), []) + [
type_id
for imported_file in sorted(imported.get(caller_file, set()))
for type_id in types_by_file.get((imported_file, qualifier), [])
]
# Fail closed when the name is not visible or is ambiguous.
target = find(scope, name, rc.get("arity"), kind) if len(scope) == 1 else None
scope = visible_types(caller_file, str(rc.get("qualifier", "")))
# Fail closed when the name is not visible or is ambiguous. A
# name that is no type may be a base contract's state variable
# (`hevm.prank()`), or a value with a `using`-attached function
# (`_checkpoints.push()`).
target = (
find(scope, name, rc.get("arity"), kind) if len(scope) == 1
else (typed_member(rc, name) or using_member(rc, name)) if not scope
else None
)
elif not contract:
continue
else:
if contract not in linear_cache:
linear_cache[contract] = _c3_linearization(contract, bases)
# The extractor already looked in the caller's own contract.
target = find(linear_cache[contract][1:], name, rc.get("arity"), kind)
target = find(linearization(contract)[1:], name, rc.get("arity"), kind)
if target is None or target == caller:
continue
relation = "uses" if kind == "modifier" else "calls"
@@ -353,6 +705,7 @@ def extract_solidity(path: Path) -> dict:
source_backed: bool = True,
callable_node: bool = False,
arity: int | None = None,
extra: dict[str, Any] | None = None,
) -> str:
if nid not in seen_ids:
seen_ids.add(nid)
@@ -361,6 +714,8 @@ def extract_solidity(path: Path) -> dict:
# Parameter count, so the cross-contract pass can pick the
# same overload the in-contract lookup does (name, arity).
metadata["arity"] = arity
if extra:
metadata.update(extra)
item: dict[str, Any] = {
"id": nid,
"label": label,
@@ -418,6 +773,20 @@ def extract_solidity(path: Path) -> dict:
call["qualifier"] = import_aliases.get(qualifier, qualifier)
raw_calls.append(call)
def member_call(
caller_id: str, member: str, arity: int, node: Node,
receiver: str | None, receiver_call: tuple[str, int] | None,
) -> None:
"""Park ``recv.member(..)`` for resolve_solidity_inherited_calls, with
the receiver's declared type and/or, for ``g(..).member()``, the call
whose result it is (typed there from ``g``'s return type)."""
call = _inherited_call(caller_id, member, arity, "member", source_file, node)
if receiver:
call["receiver_type"] = receiver
if receiver_call:
call["receiver_call"] = list(receiver_call)
raw_calls.append(call)
def split_qualified(written: str) -> tuple[str, str] | None:
"""``("Lib", "f")`` for ``Lib.f``; ``None`` for ``a.b.f``, ``x[i].f``,
``f().g``, ``super.f`` or ``this.f``."""
@@ -463,6 +832,240 @@ def extract_solidity(path: Path) -> dict:
target_file=str(target),
)
# `contract Pair` / `contract _Pair` in one file would share an id too.
type_groups = _collision_groups([
(_make_id(stem, _TYPE_DECLARATIONS[declaration.type], _read_text(name_node, source)),
_read_text(name_node, source))
for declaration in root.named_children
if declaration.type in _TYPE_DECLARATIONS
and (name_node := declaration.child_by_field_name("name")) is not None
and declaration.child_by_field_name("body") is not None
])
# Receiver typing: the declared type of `recv` in `recv.f(..)`, so a call
# on a typed value can be bound through that type. A type is kept as its
# normalized text plus the contract it was written in (`TypeContext`), so
# a struct, enum or value type declared in a contract reads as
# `Contract.Name` everywhere, as callers in other files must write it.
file_context: TypeContext = (None, frozenset())
contract_contexts: dict[int, TypeContext] = {}
# Struct fields by qualified struct name, for `s.field.f()`.
struct_fields: dict[str, tuple[TypeContext, dict[str, str]]] = {}
def field_types(struct: Node) -> dict[str, str]:
struct_body = struct.child_by_field_name("body")
fields: dict[str, str] = {}
for field in struct_body.named_children if struct_body is not None else []:
field_type = field.child_by_field_name("type")
field_name = field.child_by_field_name("name")
if field.type == "struct_member" and field_type is not None and field_name is not None:
fields[_read_text(field_name, source)] = _normalize_type(_read_text(field_type, source))
return fields
for declaration in root.named_children:
if declaration.type == "struct_declaration":
name_node = declaration.child_by_field_name("name")
if name_node is not None:
struct_fields[_read_text(name_node, source)] = (file_context, field_types(declaration))
continue
if declaration.type not in _TYPE_DECLARATIONS:
continue
name_node = declaration.child_by_field_name("name")
body = declaration.child_by_field_name("body")
if name_node is None or body is None:
continue
owner_name = _read_text(name_node, source)
local_types = frozenset(
_read_text(member.child_by_field_name("name"), source)
for member in body.named_children
if member.type in {"struct_declaration", "enum_declaration", "user_defined_type_definition"}
and member.child_by_field_name("name") is not None
)
context: TypeContext = (owner_name, local_types)
contract_contexts[declaration.id] = context
for member in body.named_children:
member_name = member.child_by_field_name("name")
if member.type == "struct_declaration" and member_name is not None:
struct_fields[f"{owner_name}.{_read_text(member_name, source)}"] = (
context, field_types(member),
)
def qualify(text: str, context: TypeContext) -> str:
"""``text`` as written in ``context``, with its leading type name
qualified (``Trace208`` in library Checkpoints -> ``Checkpoints.Trace208``)
and an import alias replaced by the name it imports."""
match = _IDENTIFIER.match(text)
if match is None:
return text
head, rest = match.group(0), text[match.end():]
owner_name, local_types = context
if not rest.startswith(".") and owner_name and head in local_types:
return f"{owner_name}.{head}{rest}"
return import_aliases.get(head, head) + rest
def using_directives(scope: Node, context: TypeContext) -> list[dict[str, Any]]:
"""The ``using A for T;`` / ``using A for *;`` / ``using {f, L.g} for
T [global];`` directives directly in ``scope`` (a contract body or the
file), for the resolver: ``{"for": T or "*", "library": A}`` or
``{"for": T, "functions": [..]}``, plus ``"global": True``. ``T`` is
qualified like a receiver type so the two compare equal. An operator
binding (`using {eq as ==} for T`) attaches no member and is skipped."""
directives: list[dict[str, Any]] = []
for directive in scope.named_children:
if directive.type != "using_directive":
continue
target = directive.child_by_field_name("source")
if target is None:
continue
item: dict[str, Any] = {
"for": "*" if target.type == "any_source_type"
else qualify(_normalize_type(_read_text(target, source)), context),
}
library = next((child for child in directive.named_children if child.type == "type_alias"), None)
if library is not None:
item["library"] = qualify(_normalize_type(_read_text(library, source)), file_context)
else:
functions = [
_normalize_type(_read_text(bound, source))
for alias in directive.named_children
if alias.type == "using_alias" and not any(child.type == "as" for child in alias.children)
for bound in alias.named_children
if bound.type == "user_defined_type"
]
if not functions:
continue
item["functions"] = [qualify(function, file_context) for function in functions]
if any(child.type == "global" for child in directive.children):
item["global"] = True
directives.append(item)
return directives
def first_parameter_type(callable_node: Node, context: TypeContext) -> dict[str, Any]:
"""``{"first_param_type": T}`` for a library or free function, the
type a ``using`` directive attaches it to (``x.f()`` passes ``x``)."""
first = next((child for child in callable_node.named_children if child.type == "parameter"), None)
type_node = first.child_by_field_name("type") if first is not None else None
if type_node is None:
return {}
return {"first_param_type": qualify(_normalize_type(_read_text(type_node, source)), context)}
def declared_types(callable_node: Node, context: TypeContext, inherited: VariableTypes) -> VariableTypes:
"""Parameter, return and local variable types visible in a function
or modifier, over ``inherited`` (the contract's state variables). A
name declared twice with different types (sibling blocks) is
ambiguous and maps to ``None``."""
found: dict[str, set[str]] = {}
stack = [callable_node]
while stack:
current = stack.pop()
if current.type in {"parameter", "variable_declaration"}:
type_node = current.child_by_field_name("type")
name_node = current.child_by_field_name("name")
if type_node is not None and name_node is not None:
found.setdefault(_read_text(name_node, source), set()).add(
_normalize_type(_read_text(type_node, source))
)
stack.extend(current.named_children)
scope: VariableTypes = dict(inherited)
for name, types in found.items():
scope[name] = (next(iter(types)), context) if len(types) == 1 else None
return scope
def unwrap(node: Node) -> Node:
while node.type in {"expression", "parenthesized_expression"} and len(node.named_children) == 1:
node = node.named_children[0]
return node
def typed_receiver(
callee: Node, scope: VariableTypes, context: TypeContext, local_functions: set[str],
) -> str | None:
"""The qualified declared type of the receiver of the member call
``callee``: a typed variable, an element of a typed mapping/array, a
field of a struct declared in this file, a conversion (`IERC20(a)`,
`uint256(x)`) or a builtin. ``None`` (fail closed) for anything else,
including `super`, `this` and a type name (`Lib.f()`)."""
member = _member_callee(callee)
obj = member.child_by_field_name("object") if member is not None else None
if obj is None:
return None
typed = typed_expression(unwrap(_rightmost_operand(obj)), scope, context, local_functions)
return qualify(*typed) if typed is not None else None
def member_receiver(
callee: Node, scope: VariableTypes, context: TypeContext, local_functions: set[str],
) -> tuple[str | None, tuple[str, int] | None] | None:
"""``(declared type, (g, arity))`` of a member call's receiver, either
part ``None`` when unknown; ``None`` when both are."""
typed = typed_receiver(callee, scope, context, local_functions)
result_of = call_receiver(callee, scope)
return (typed, result_of) if typed or result_of else None
def call_receiver(callee: Node, scope: VariableTypes) -> tuple[str, int] | None:
"""``(g, arity)`` when the receiver of the member call ``callee`` is
the result of a bare call ``g(..)``, which the resolver types from
``g``'s declared return type."""
member = _member_callee(callee)
obj = member.child_by_field_name("object") if member is not None else None
receiver = unwrap(_rightmost_operand(obj)) if obj is not None else None
if receiver is None or receiver.type != "call_expression":
return None
function = receiver.child_by_field_name("function")
name = _read_text(unwrap(function), source) if function is not None else ""
if not _IDENTIFIER.fullmatch(name) or name in scope or name in _BUILTIN_CALL_TYPES:
return None
return name, sum(child.type == "call_argument" for child in receiver.named_children)
def typed_expression(
node: Node, scope: VariableTypes, context: TypeContext, local_functions: set[str],
) -> tuple[str, TypeContext] | None:
if node.type == "identifier":
return scope.get(_read_text(node, source))
if node.type == "array_access":
base = node.child_by_field_name("base")
typed = typed_expression(unwrap(base), scope, context, local_functions) if base is not None else None
element = _element_type(typed[0]) if typed is not None else None
return (element, typed[1]) if typed is not None and element else None
if node.type == "member_expression":
written = _read_text(node, source)
if written in _BUILTIN_MEMBER_TYPES:
return _BUILTIN_MEMBER_TYPES[written], file_context
obj = node.child_by_field_name("object")
prop = node.child_by_field_name("property")
typed = typed_expression(unwrap(obj), scope, context, local_functions) if obj is not None else None
struct = struct_fields.get(qualify(*typed)) if typed is not None else None
field = struct[1].get(_read_text(prop, source)) if struct is not None and prop is not None else None
return (field, struct[0]) if struct is not None and field else None
if node.type == "type_cast_expression":
type_node = next((child for child in node.named_children if child.type == "primitive_type"), None)
return (_normalize_type(_read_text(type_node, source)), file_context) if type_node is not None else None
if node.type == "payable_conversion_expression":
return "address payable", file_context
if node.type == "call_expression":
function = node.child_by_field_name("function")
if function is None:
return None
written = _normalize_type(_read_text(unwrap(function), source))
if written in _BUILTIN_CALL_TYPES:
return _BUILTIN_CALL_TYPES[written], file_context
arguments = sum(child.type == "call_argument" for child in node.named_children)
# `T(x)`: a conversion to the type `T`. A function of the caller's
# own contract or a variable is not a type; any other name is
# checked against the declared types by the resolver.
if (
arguments == 1
and _IDENTIFIER.fullmatch(written)
and written not in scope
and written not in local_functions
):
return written, context
return None
file_using = using_directives(root, file_context)
if file_using:
# File-level directives apply to every contract and free function of
# the file; a `global` one to every use of its type.
nodes[0]["metadata"]["using"] = file_using
for declaration in root.named_children:
type_kind = _TYPE_DECLARATIONS.get(declaration.type)
if type_kind is None:
@@ -472,12 +1075,15 @@ def extract_solidity(path: Path) -> dict:
if name_node is None or body is None:
continue
type_name = _read_text(name_node, source)
contract_using = using_directives(body, contract_contexts[declaration.id])
type_id = add_node(
_make_id(stem, type_kind, type_name),
_underscore_salted_nid(_make_id(stem, type_kind, type_name), type_name, type_groups),
type_name,
declaration,
kind=type_kind,
callable_node=type_kind == "contract",
# Read by the resolver to bind `x.f()` through `using A for T`.
extra={"using": contract_using} if contract_using else None,
)
add_edge(file_id, type_id, "contains", declaration)
@@ -499,9 +1105,22 @@ def extract_solidity(path: Path) -> dict:
functions: dict[tuple[str, int], list[str]] = {}
modifiers: dict[str, str] = {}
reference_targets: dict[tuple[str, int], str] = {}
bodies: list[tuple[Node, str]] = []
bodies: list[tuple[Node, str, Node]] = []
type_context = contract_contexts[declaration.id]
state_types: VariableTypes = {}
pending_modifiers: list[tuple[str, str, Node]] = []
# Members whose names differ only by a leading `_` (or by case) share a
# plain id; the one public name keeps it and the others are salted,
# as Python and C# do (#3302, #4415). A member that collides with
# nothing keeps its id.
member_groups = _collision_groups([
(_make_id(type_id, kind, name, signature), name)
for member in body.named_children
if (identity := _member_identity(member, source)) is not None
for kind, name, signature in [identity]
])
def add_member(
member: Node,
name: str,
@@ -512,13 +1131,16 @@ def extract_solidity(path: Path) -> dict:
signature: str = "",
callable_node: bool = False,
arity: int | None = None,
extra: dict[str, Any] | None = None,
) -> str:
# Callables carry an arity:types signature (distinguishes overloads).
# Non-callable members (struct/enum/event/error/state-var) have no
# signature; discriminate on the name — which is unique per kind
# within a contract scope — rather than the line number, so a node's
# id stays stable when the member moves (avoids incremental id churn).
member_id = _make_id(type_id, kind, name, signature or name)
member_id = _underscore_salted_nid(
_make_id(type_id, kind, name, signature or name), name, member_groups,
)
add_node(
member_id,
label,
@@ -526,6 +1148,7 @@ def extract_solidity(path: Path) -> dict:
kind=kind,
callable_node=callable_node,
arity=arity,
extra=extra,
)
add_edge(type_id, member_id, relation, member)
return member_id
@@ -620,7 +1243,17 @@ def extract_solidity(path: Path) -> dict:
for child in member.named_children
)
if kind == "state_variable_declaration":
reference_targets[(name, arity)] = add_member(member, name, name, "state_variable")
type_node = member.child_by_field_name("type")
declared: dict[str, Any] = {}
if type_node is not None:
state_type = _normalize_type(_read_text(type_node, source))
state_types[name] = (state_type, type_context)
# Read by the resolver for a receiver that is a base
# contract's state variable (`hevm.prank()`).
declared["declared_type"] = qualify(state_type, type_context)
reference_targets[(name, arity)] = add_member(
member, name, name, "state_variable", extra=declared,
)
else:
# `emit E(..)`, `revert Err(..)` and `require(c, Err(..))`
# call the event/error, like Python's `raise Err()`: bind
@@ -659,6 +1292,22 @@ def extract_solidity(path: Path) -> dict:
if child.child_by_field_name("type") is not None
)
arity = len(parameters)
returned: dict[str, Any] = {}
return_types = [
parameter.child_by_field_name("type")
for returns in member.named_children
if returns.type == "return_type_definition"
for parameter in returns.named_children
if parameter.type == "parameter"
]
if type_kind == "library" and callable_kind == "function":
returned.update(first_parameter_type(member, type_context))
if len(return_types) == 1 and return_types[0] is not None:
# Read by the resolver for a receiver that is this function's
# result (`token().clock()`).
returned["returns"] = qualify(
_normalize_type(_read_text(return_types[0], source)), type_context,
)
member_id = add_member(
member,
name,
@@ -668,6 +1317,7 @@ def extract_solidity(path: Path) -> dict:
signature=f"{arity}:{signature}",
callable_node=True,
arity=arity,
extra=returned,
)
if callable_kind == "modifier":
modifiers[name] = member_id
@@ -675,7 +1325,7 @@ def extract_solidity(path: Path) -> dict:
functions.setdefault((name, arity), []).append(member_id)
member_body = member.child_by_field_name("body")
if member_body is not None:
bodies.append((member_body, member_id))
bodies.append((member_body, member_id, member))
if callable_kind != "modifier":
for child in member.named_children:
if child.type != "modifier_invocation":
@@ -703,7 +1353,9 @@ def extract_solidity(path: Path) -> dict:
caller_id, modifier_name, None, "modifier", source_file, modifier_node,
))
for function_body, caller_id in bodies:
own_functions = {name for name, _arity in functions}
for function_body, caller_id, callable_node in bodies:
scope = declared_types(callable_node, type_context, state_types)
stack = [function_body]
while stack:
node = stack.pop()
@@ -736,6 +1388,10 @@ def extract_solidity(path: Path) -> dict:
raw_calls.append(_inherited_call(
caller_id, callee, arity, "super", source_file, node,
))
elif callee and (
receiver := member_receiver(callee_node, scope, type_context, own_functions)
):
member_call(caller_id, callee, arity, node, *receiver)
elif callee and (qualified := split_qualified(written)):
# `Lib.f(..)` / `Base.f(..)` / `Errors.Err(..)`.
# A value receiver (`token.transfer()`) names no
@@ -789,7 +1445,14 @@ def extract_solidity(path: Path) -> dict:
# type-declaration loop above only descends into named type declarations,
# so a free function — and every call it makes — was dropped entirely.
free_functions: dict[tuple[str, int], list[str]] = {}
free_bodies: list[tuple[Node, str]] = []
free_groups = _collision_groups([
(_make_id(stem, "function", _read_text(name_node, source), _callable_signature(declaration, source)),
_read_text(name_node, source))
for declaration in root.named_children
if declaration.type == "function_definition"
and (name_node := declaration.child_by_field_name("name")) is not None
])
free_bodies: list[tuple[Node, str, Node]] = []
for declaration in root.named_children:
if declaration.type != "function_definition":
continue
@@ -808,24 +1471,28 @@ def extract_solidity(path: Path) -> dict:
)
arity = len(parameters)
func_id = add_node(
_make_id(stem, "function", name, f"{arity}:{signature}"),
_underscore_salted_nid(_make_id(stem, "function", name, f"{arity}:{signature}"), name, free_groups),
f"{name}()",
declaration,
kind="function",
callable_node=True,
arity=arity,
extra=first_parameter_type(declaration, file_context),
)
add_edge(file_id, func_id, "contains", declaration)
free_functions.setdefault((name, arity), []).append(func_id)
body = declaration.child_by_field_name("body")
if body is not None:
free_bodies.append((body, func_id))
free_bodies.append((body, func_id, declaration))
# Resolve calls made from free-function bodies. Only an unambiguous
# same-file free function is linked directly; a qualified call (Lib.f())
# is left for resolve_solidity_inherited_calls. Contract methods stay out
# of scope so we never guess a relationship across a scope we cannot see
# (fail-closed).
for function_body, caller_id in free_bodies:
free_names = {name for name, _arity in free_functions}
for function_body, caller_id, callable_node in free_bodies:
scope = declared_types(callable_node, file_context, {})
stack = [function_body]
while stack:
node = stack.pop()
@@ -839,6 +1506,8 @@ def extract_solidity(path: Path) -> dict:
candidates = free_functions.get((callee, arity), [])
if len(candidates) == 1:
add_edge(caller_id, candidates[0], "calls", node)
elif callee and (receiver := member_receiver(callee_node, scope, file_context, free_names)):
member_call(caller_id, callee, arity, node, *receiver)
elif callee and (qualified := split_qualified(written)):
qualified_call(caller_id, *qualified, arity, node)
elif callee:
+53 -5
View File
@@ -23,6 +23,51 @@ from graphify.ids import normalize_id
_YAML_MAX_BYTES = 1_048_576 # 1 MiB
_MAX_PAIRS = 500
# Built lazily by _permissive_loader() once PyYAML is known to be importable
# (the module stays import-optional, so this cannot be a module-level class).
_permissive_loader_cls: Any = None
def _construct_permissive(loader: Any, tag_suffix: str, node: Any) -> Any:
"""Build a plain value for an unrecognized ``!`` tag (#5071).
CloudFormation/SAM intrinsic functions (``!Ref``, ``!Sub``, ``!GetAtt``,
``!Equals``, ...) are short, local tags SafeLoader has no constructor
for, so ``safe_load_all`` raised ``ConstructorError`` and the whole file
produced zero nodes. The intrinsic itself is never evaluated here, only
the tagged value's own shape: a scalar tag becomes its scalar value, a
sequence tag its list, and a mapping tag its dict, exactly as if the tag
were absent.
"""
import yaml # type: ignore
if isinstance(node, yaml.ScalarNode):
return loader.construct_scalar(node)
if isinstance(node, yaml.SequenceNode):
return loader.construct_sequence(node)
if isinstance(node, yaml.MappingNode):
return loader.construct_mapping(node)
return None
def _permissive_loader() -> Any:
"""A ``yaml.SafeLoader`` subclass that also accepts any unknown ``!`` tag.
Adds no safety-relevant behavior over ``SafeLoader``: it only widens which
tags construct a plain value, never which types a value can construct
into, so a ``!!python/...`` tag still raises exactly as it does under
plain ``safe_load_all``.
"""
global _permissive_loader_cls
if _permissive_loader_cls is None:
import yaml # type: ignore
class _PermissiveSafeLoader(yaml.SafeLoader):
pass
_PermissiveSafeLoader.add_multi_constructor("!", _construct_permissive)
_permissive_loader_cls = _PermissiveSafeLoader
return _permissive_loader_cls
_MAX_DEPTH = 6
# Config/manifest filenames worth structural extraction regardless of shape.
@@ -139,10 +184,13 @@ def _mapping_pairs(node: Any) -> list[tuple[str, Any, Any]]:
def extract_yaml(path: Path) -> dict:
"""Extract structural nodes/edges from a ``.yaml``/``.yml`` file.
Uses PyYAML ``safe_load_all`` (never ``load``; a ``!!python/...`` tag raises
rather than executing) and walks every document in a multi-document stream.
Returns an error payload when PyYAML is missing so callers degrade
gracefully instead of crashing.
Uses a ``SafeLoader`` (never ``load``; a ``!!python/...`` tag raises
rather than executing), widened to accept any unrecognized ``!`` tag as a
plain scalar/sequence/mapping (#5071 — CloudFormation/SAM's ``!Ref``,
``!Equals``, etc. otherwise raise ``ConstructorError`` and the whole file
produces zero nodes), and walks every document in a multi-document
stream. Returns an error payload when PyYAML is missing so callers
degrade gracefully instead of crashing.
"""
try:
import yaml # type: ignore
@@ -156,7 +204,7 @@ def extract_yaml(path: Path) -> dict:
if len(raw) > _YAML_MAX_BYTES:
return {"nodes": [], "edges": [], "error": "yaml file too large to index"}
text = raw.decode("utf-8", errors="ignore")
docs = list(yaml.safe_load_all(text))
docs = list(yaml.load_all(text, Loader=_permissive_loader()))
# The constructed values drive the config gate and document labels; the
# composed node tree (same documents, same order, nothing constructed)
# supplies keys as written and their lines, which construction discards.
+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)
+19 -1
View File
@@ -15,7 +15,25 @@ _GLOBAL_MANIFEST = _GLOBAL_DIR / "global-manifest.json"
def _load_manifest() -> dict:
if _GLOBAL_MANIFEST.exists():
try:
return json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
manifest = json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
repos = manifest.get("repos") if isinstance(manifest, dict) else None
if not isinstance(repos, dict):
raise ValueError("expected a manifest object with a repos map")
# Isolate a malformed repo entry instead of discarding every tracked
# repo: a single bad value should not lose the user's other repos
# (#5020). Drop the bad ones, keep the rest, and say which went. Only
# a non-dict root or repos map is unrecoverable enough to back up.
bad = sorted(name for name, info in repos.items() if not isinstance(info, dict))
if bad:
for name in bad:
repos.pop(name)
print(
f"[graphify global] dropped {len(bad)} malformed repo "
f"entr{'y' if len(bad) == 1 else 'ies'} ({', '.join(bad)}) "
f"from {_GLOBAL_MANIFEST}; kept {len(repos)} valid repo(s).",
file=sys.stderr,
)
return manifest
except Exception as exc:
# Don't silently wipe the user's manifest on a parse error: that
# deletes every tracked repo. Back the bad file up and surface the
+30 -7
View File
@@ -1,11 +1,14 @@
# fetch URLs (tweet/arxiv/pdf/web) and save as annotated markdown
from __future__ import annotations
from collections.abc import Callable
from contextlib import suppress
import json
import re
import uuid
import urllib.error
import urllib.parse
from datetime import datetime, timezone
from os import linesep
from pathlib import Path
from graphify.security import safe_fetch, safe_fetch_text, validate_url
@@ -226,7 +229,7 @@ def _free_capture_path(target_dir: Path, filename: str) -> Path:
Uses lstat so no existing directory entry is replaced, including a
dangling symlink that a write would otherwise follow out of the corpus.
Selection and writing are separate; concurrent captures are not atomic.
The writer still needs an exclusive open to reserve the selected name.
"""
stem, suffix = Path(filename).stem, Path(filename).suffix
out_path = target_dir / filename
@@ -240,11 +243,32 @@ def _free_capture_path(target_dir: Path, filename: str) -> Path:
counter += 1
def _write_capture(target_dir: Path, filename: str, content: str | Callable[[], bytes]) -> Path:
"""Write a capture under a unique name without clobbering another writer."""
out_path = _free_capture_path(target_dir, filename)
# Inspect the destination before fetching, and fetch at most once per capture.
payload = content() if callable(content) else content
if isinstance(payload, str):
# Preserve the newline translation of Path.write_text on Windows.
payload = payload.replace("\n", linesep).encode("utf-8")
while True:
try:
handle = out_path.open("xb")
except FileExistsError:
out_path = _free_capture_path(target_dir, filename)
continue
try:
with handle:
handle.write(payload)
except (OSError, UnicodeError):
with suppress(OSError):
out_path.unlink()
raise
return out_path
def _download_binary(url: str, suffix: str, target_dir: Path) -> Path:
"""Save a sequential capture without replacing an existing directory entry."""
out_path = _free_capture_path(target_dir, _safe_filename(url, suffix))
out_path.write_bytes(safe_fetch(url))
return out_path
return _write_capture(target_dir, _safe_filename(url, suffix), lambda: safe_fetch(url))
def ingest(url: str, target_dir: Path, author: str | None = None, contributor: str | None = None) -> Path:
@@ -288,8 +312,7 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
except (urllib.error.HTTPError, urllib.error.URLError, OSError) as exc:
raise RuntimeError(f"ingest: failed to fetch {url!r}: {exc}") from exc
out_path = _free_capture_path(target_dir, filename)
out_path.write_text(content, encoding="utf-8")
out_path = _write_capture(target_dir, filename, content)
print(f"Saved {url_type}: {out_path.name}")
return out_path
+3
View File
@@ -126,6 +126,9 @@ def resolve_interface_dispatch(
mnode = node_by_id.get(method_nid)
if mnode is None or not declared_in(mnode, suffixes):
continue
# A constructor shares its type's name but implements nothing.
if (mnode.get("metadata") or {}).get("kind") == "constructor":
continue
name = method_label(mnode)
if name:
# A set, so the same method arriving on two `method` edges cannot
+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)
+11 -3
View File
@@ -839,7 +839,8 @@ def write_learning_sidecar(agg: dict[str, Any], graph_path: Path,
def load_learning_overlay(graph_path: Path) -> dict[str, dict[str, Any]]:
"""Load the sidecar next to ``graph_path`` and return ``{node_id -> entry}``
with a recomputed ``stale: bool`` per entry. Best-effort -> {} on any error.
with a recomputed ``stale: bool`` per entry. An unreadable or malformed
sidecar yields {}; malformed entries are ignored individually.
Staleness: recompute ``file_hash(source_file)`` and compare to the entry's
stored ``code_fingerprint``. Matching fingerprints -> not stale. Differing,
@@ -852,15 +853,22 @@ def load_learning_overlay(graph_path: Path) -> dict[str, dict[str, Any]]:
data = json.loads(sidecar.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
nodes = data.get("nodes")
nodes = data.get("nodes") if isinstance(data, dict) else None
if not isinstance(nodes, dict):
return {}
out: dict[str, dict[str, Any]] = {}
for nid, entry in nodes.items():
if not isinstance(entry, dict):
continue
source = entry.get("source_file")
if source is not None and not isinstance(source, str):
continue
merged = dict(entry)
merged["stale"] = _is_stale(entry, graph_path)
try:
merged["stale"] = _is_stale(entry, graph_path)
except (OSError, ValueError):
# An inaccessible path has no verifiable fingerprint.
merged["stale"] = True
out[str(nid)] = merged
return out
+149 -5
View File
@@ -71,7 +71,8 @@ def _read_graph(graph_path: str) -> nx.Graph:
data = {**data, "multigraph": True}
try:
from graphify.build import graph_has_legacy_ids as _legacy
if _legacy(data.get("nodes", [])):
from graphify.build import legacy_id_source_prefix as _legacy_prefix
if _legacy(data.get("nodes", []), source_prefix=_legacy_prefix(safe)):
print(
"[graphify] note: this graph uses the pre-#1504 node-ID scheme; "
"rebuild with `graphify extract --force` for path-qualified IDs.",
@@ -350,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):
@@ -711,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"
@@ -863,7 +956,9 @@ def _pick_seeds(
incidental collision cannot starve out the others. The per-token winners
in `best_seed_by_term` are precomputed by `_score_query` (during the same
traversal that produced `scored`) so this function no longer rescores the
graph per term — see #1445 and the `_score_query` docstring.
graph per term — see #1445 and the `_score_query` docstring. The #1766
label cap yields to this guarantee only when the term is absent from the
shared label, since a seeded same-label node then can't cover it (#5027).
Coverage scaling in _score_nodes (#1602) now dampens a lone collision's
exact tier on multi-term queries, which brings label-matching relevant
@@ -913,7 +1008,7 @@ def _pick_seeds(
# traversal, so `_pick_seeds` no longer rescoring the graph per term.
# The per-label dedup cap also gates these additions, so the guarantee
# cannot reintroduce a second copy of an already-seeded generic label
# (#1766).
# (#1766), unless the term is not in that label (#5027, see below).
# With `term_order` (from `_score_query`), the guaranteed seeds follow the strength of each term's best
# match, strongest first, so the seeds the renderer prints first are the strongest; without it, the
# legacy sorted-term order.
@@ -923,8 +1018,13 @@ def _pick_seeds(
best_nid = best_seed_by_term[term]
# Honor the same per-label cap so the per-term guarantee can't
# reintroduce a second copy of an already-seeded generic label.
# The cap applies only when `term` is in the label: then the
# seeded twin matches `term` through that same label. Otherwise
# this node won `term` via its path/rationale/attributes, the
# twin may not match it at all, and dropping it would leave the
# term with no seed (#5027).
key = _seed_label_key(best_nid)
if best_nid not in seeds and key not in seen_labels:
if best_nid not in seeds and (key not in seen_labels or term not in key):
seen_labels.add(key)
seeds.append(best_nid)
return seeds
@@ -2248,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.
@@ -2277,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.
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -314,6 +317,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -324,7 +328,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -380,7 +384,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -466,7 +471,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -481,10 +486,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -509,7 +515,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -525,7 +531,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -538,7 +544,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -551,7 +558,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -572,9 +579,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -585,7 +593,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -600,7 +608,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -640,6 +648,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -661,7 +670,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -673,7 +682,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -703,7 +712,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+15 -10
View File
@@ -117,12 +117,13 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
print(json.dumps(result))
" > .graphify_detect.json
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -421,7 +422,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears, the same way you substitute `INPUT_PATH` - do not leave the literal `IS_DIRECTED` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears - do not leave the literal `IS_DIRECTED` in the code. INPUT_PATH is not substituted - each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -436,6 +437,7 @@ from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
G = build_from_json(extraction, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
@@ -460,7 +462,7 @@ wrote = to_json(G, communities, 'graphify-out/graph.json')
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
analysis = {
@@ -477,7 +479,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 5 - Label communities
@@ -498,6 +500,7 @@ from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
G = build_from_json(extraction, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -510,7 +513,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -524,7 +527,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -719,16 +722,17 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('.graphify_detect.json').read_text())
extract = json.loads(Path('.graphify_extract.json').read_text())
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# Stamp only semantic files that produced output so a failed chunk is re-queued next run, not lost (#2015).
from graphify.cli import _stamped_manifest_files
_corpus = detect.get('all_files') or detect['files']
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH))
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -802,7 +806,8 @@ from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -314,6 +317,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -324,7 +328,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -380,7 +384,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -466,7 +471,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -481,10 +486,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -509,7 +515,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -525,7 +531,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -538,7 +544,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -551,7 +558,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -572,9 +579,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -585,7 +593,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -600,7 +608,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -640,6 +648,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -661,7 +670,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -673,7 +682,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -703,7 +712,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -317,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -327,7 +331,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -383,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -469,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -484,10 +489,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -512,7 +518,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -528,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -541,7 +547,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -554,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -575,9 +582,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -588,7 +596,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -603,7 +611,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -643,6 +651,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -664,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -676,7 +685,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -706,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -318,6 +321,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -328,7 +332,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -384,7 +388,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -470,7 +475,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -485,10 +490,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -513,7 +519,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -529,7 +535,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -542,7 +548,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -555,7 +562,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -576,9 +583,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -589,7 +597,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -604,7 +612,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -644,6 +652,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -665,7 +674,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -677,7 +686,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -707,7 +716,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -317,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -327,7 +331,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -383,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -469,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -484,10 +489,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -512,7 +518,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -528,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -541,7 +547,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -554,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -575,9 +582,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -588,7 +596,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -603,7 +611,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -643,6 +651,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -664,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -676,7 +685,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -706,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+15 -10
View File
@@ -130,12 +130,13 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
print(json.dumps(result))
" > graphify-out/.graphify_detect.json
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -486,7 +487,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears, the same way you substitute `INPUT_PATH` - do not leave the literal `IS_DIRECTED` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears - do not leave the literal `IS_DIRECTED` in the code. INPUT_PATH is not substituted - each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -501,6 +502,7 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
G = build_from_json(extraction, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
@@ -525,7 +527,7 @@ wrote = to_json(G, communities, 'graphify-out/graph.json')
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
analysis = {
@@ -542,7 +544,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 5 - Label communities
@@ -575,7 +577,8 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -589,7 +592,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -837,16 +840,17 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# Stamp only semantic files that produced output so a failed chunk is re-queued next run, not lost (#2015).
from graphify.cli import _stamped_manifest_files
_corpus = detect.get('all_files') or detect['files']
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH))
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -941,7 +945,8 @@ from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -314,6 +317,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -324,7 +328,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -380,7 +384,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -466,7 +471,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -481,10 +486,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -509,7 +515,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -525,7 +531,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -538,7 +544,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -551,7 +558,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -572,9 +579,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -585,7 +593,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -600,7 +608,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -640,6 +648,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -661,7 +670,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -673,7 +682,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -703,7 +712,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -317,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -327,7 +331,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -383,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -469,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -484,10 +489,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -512,7 +518,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -528,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -541,7 +547,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -554,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -575,9 +582,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -588,7 +596,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -603,7 +611,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -643,6 +651,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -664,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -676,7 +685,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -706,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -317,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -327,7 +331,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -383,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -469,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -484,10 +489,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -512,7 +518,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -528,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -541,7 +547,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -554,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -575,9 +582,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -588,7 +596,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -603,7 +611,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -643,6 +651,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -664,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -676,7 +685,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -706,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -309,6 +312,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -319,7 +323,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -375,7 +379,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -461,7 +466,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -476,10 +481,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -504,7 +510,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -520,7 +526,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -533,7 +539,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -546,7 +553,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -567,9 +574,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -580,7 +588,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -595,7 +603,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -635,6 +643,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -656,7 +665,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -668,7 +677,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -698,7 +707,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -311,6 +314,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -321,7 +325,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -377,7 +381,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -463,7 +468,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -478,10 +483,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -506,7 +512,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -522,7 +528,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -535,7 +541,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -548,7 +555,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -569,9 +576,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -582,7 +590,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -597,7 +605,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -637,6 +645,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -658,7 +667,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -670,7 +679,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -700,7 +709,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -315,6 +318,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -325,7 +329,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -381,7 +385,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -467,7 +472,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -482,10 +487,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -510,7 +516,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -526,7 +532,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -539,7 +545,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -552,7 +559,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -573,9 +580,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -586,7 +594,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -601,7 +609,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -641,6 +649,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -662,7 +671,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -674,7 +683,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -704,7 +713,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -313,6 +316,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -323,7 +327,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -379,7 +383,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -465,7 +470,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -480,10 +485,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -508,7 +514,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -524,7 +530,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -537,7 +543,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -550,7 +557,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -571,9 +578,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -584,7 +592,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -599,7 +607,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -639,6 +647,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -660,7 +669,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -672,7 +681,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -702,7 +711,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -152,7 +152,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
@@ -160,7 +161,7 @@ print(f'Detected {result["total_files"]} files')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -221,6 +222,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -228,7 +230,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
else:
@@ -275,7 +277,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -345,6 +348,7 @@ A subagent that only read the first Read call's worth of a long file still write
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding="utf-8"))
@@ -355,7 +359,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -411,7 +415,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding="utf-8").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
'@ | & (Get-Content graphify-out\.graphify_python) -
@@ -497,7 +502,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```powershell
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
@@ -512,10 +517,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -540,7 +546,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -556,7 +562,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -569,7 +575,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -582,7 +589,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -603,9 +610,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -616,7 +624,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -631,7 +639,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -671,6 +679,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -692,7 +701,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding="utf-8").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -704,7 +713,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -734,7 +743,7 @@ Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction S
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+27 -18
View File
@@ -124,7 +124,8 @@ from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
@@ -132,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
@@ -193,6 +194,7 @@ import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
@@ -200,7 +202,7 @@ if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
@@ -247,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
@@ -317,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
@@ -327,7 +331,7 @@ partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
p = Path(INPUT_PATH) / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
@@ -383,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
@@ -469,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute them the same way you substitute `INPUT_PATH` — do not leave literal `IS_DIRECTED` or `IS_FORCE` in the code.
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
```bash
mkdir -p graphify-out
@@ -484,10 +489,11 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
@@ -512,7 +518,7 @@ if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
@@ -528,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 4.5 - Graph health check (read-only integrity gate)
@@ -541,7 +547,8 @@ from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
@@ -554,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
@@ -575,9 +582,10 @@ from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
@@ -588,7 +596,7 @@ labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
@@ -603,7 +611,7 @@ print('Report updated with community labels')
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
@@ -643,6 +651,7 @@ from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
@@ -664,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
@@ -676,7 +685,7 @@ _cleared = _dispatched - _stamped
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
@@ -706,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
@@ -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
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
@@ -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
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
@@ -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
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+6 -4
View File
@@ -18,7 +18,8 @@ from graphify.watch import _read_build_excludes, _read_build_gitignore
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
@@ -107,6 +108,7 @@ from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
@@ -128,7 +130,7 @@ G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
root=INPUT_PATH,
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
@@ -171,7 +173,7 @@ from graphify.cli import _stamped_manifest_files
# Leave the list on disk: Step 9 reads it too if it runs after the update.
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'), partial_source_files=_partial)
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
@@ -181,7 +183,7 @@ _cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
+11 -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]
@@ -214,6 +214,16 @@ def build_tree(
raise ValueError("--max-children must be nonnegative")
directory_ids: set[int] = set()
nodes: List[Dict[str, Any]] = list(graph.get("nodes", []))
for n in nodes:
if not n.get("source_file"):
# Same alias order as build._fold_node_aliases (`src` last), so a node
# carrying two conflicting aliases resolves to the identical
# source_file in the built graph and in this viewer.
for alias in ("file", "path", "filepath", "src"):
val = n.get(alias)
if isinstance(val, str) and val.strip():
n["source_file"] = n.pop(alias).strip()
break
file_nodes = [n for n in nodes if n.get("source_file")]
if not file_nodes:
return {"name": "(empty graph)", "total_count": 0, "children": []}
+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)}"
+214 -25
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import contextlib
import errno
import inspect
import json
import logging
import os
@@ -486,6 +487,7 @@ from graphify.detect import (
IMAGE_EXTENSIONS,
_load_graphifyignore,
_is_ignored,
ignored_predicate,
)
from graphify.rcfile import (
RC_FILENAME,
@@ -930,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:
@@ -2349,6 +2365,7 @@ def _rebuild_code(
classify_manifest_deletions,
classify_manifest_files,
detect,
is_resolution_input,
load_manifest,
)
from graphify.build import build_from_json, _is_ast_tier, _norm_source_file as _nsf
@@ -2429,21 +2446,23 @@ def _rebuild_code(
# records the ast_hash of every file the last build extracted, so the
# change set can be read off it instead of re-extracting the whole
# corpus. `detected` was computed above for the full path anyway, so this
# costs one manifest read, not a second scan.
# costs one manifest read, not a second scan. A manifest cannot
# restore unchanged nodes when the graph it describes is missing.
#
# A manifest that is missing, unreadable or empty leaves changed_paths
# None — the full path. "No rows" means the baseline is unknown, and the
# only safe reading of unknown is "do the work"; `detect_incremental`
# makes the same call for `graphify extract` (#1925).
if incremental and changed_paths is None and not force:
if incremental and changed_paths is None and not force and (out / "graph.json").is_file():
manifest = load_manifest(str(out / "manifest.json"), root=watch_root)
if manifest:
resolution_inputs = detected.get("resolution_inputs") or []
_changed_buckets, _unchanged_buckets = classify_manifest_files(
detected["files"], manifest, kind="ast"
{**detected["files"], "resolution_inputs": resolution_inputs},
manifest,
kind="ast",
)
derived = [
Path(f) for bucket in _changed_buckets.values() for f in bucket
]
modified = [f for bucket in _changed_buckets.values() for f in bucket]
# Rows that left the corpus belong in the change set too. A row
# whose file is gone from disk must reach the deleted branch
# below, or its nodes survive and the shrink guard refuses the
@@ -2451,24 +2470,33 @@ def _rebuild_code(
# A row that is still alive but out of scan is an ignore-rule
# change, which the corpus sweep handles on positive evidence
# alone (#2495), so it stays out of the change set.
_deleted_rows, _excluded_rows = classify_manifest_deletions(
deleted_rows, excluded_rows = classify_manifest_deletions(
manifest,
(f for bucket in detected["files"].values() for f in bucket),
[
*resolution_inputs,
*(f for bucket in detected["files"].values() for f in bucket),
],
root=watch_root,
)
derived.extend(Path(f) for f in _deleted_rows)
changed_paths = derived
_scanned = sum(len(v) for v in detected["files"].values())
if derived:
if any(is_resolution_input(f) for f in (*modified, *deleted_rows, *excluded_rows)):
# An unchanged importer may resolve differently when its
# config or workspace layout changes. Re-resolve the corpus.
print(
f"[graphify watch] Incremental: re-extracting {len(derived)} "
f"of {_scanned} scanned files that changed since the last build."
"[graphify watch] JS/TS resolution inputs changed; rebuilding the full code graph."
)
else:
print(
f"[graphify watch] Incremental: none of the {_scanned} scanned "
"files differ from the last build."
)
changed_paths = [Path(f) for f in (*modified, *deleted_rows)]
scanned = sum(len(v) for v in detected["files"].values())
if changed_paths:
print(
f"[graphify watch] Incremental: re-extracting {len(changed_paths)} "
f"of {scanned} scanned files that changed since the last build."
)
else:
print(
f"[graphify watch] Incremental: none of the {scanned} scanned "
"files differ from the last build."
)
# #2495: hand reconcile the same ignore decisions the detect() call
# above made, so a newly-ignored file that still exists on disk is
@@ -3442,6 +3470,42 @@ def _batch_triggers_rebuild(batch: list[Path]) -> bool:
return has_code or has_deletion
def _watch_event_filter():
"""Watchdog events that mean a file actually changed, not just was read.
Passing this as ``event_filter`` keeps ``IN_OPEN`` and
``IN_CLOSE_NOWRITE`` out of the inotify mask. The recursive watch-setup
walk then produces no events of its own, so it cannot overflow the kernel
queue and trigger watchdog's rebuild loop (#5033).
"""
from watchdog import events as we
return [
we.FileCreatedEvent,
we.FileModifiedEvent,
we.FileDeletedEvent,
we.FileMovedEvent,
we.FileClosedEvent,
we.DirCreatedEvent,
we.DirDeletedEvent,
we.DirMovedEvent,
]
def _observer_accepts_event_filter(observer) -> bool:
"""True when this watchdog's ``schedule()`` declares ``event_filter``.
``event_filter`` was added in watchdog 4.0. Graphify does not pin a minimum
watchdog version, so detect support instead of raising TypeError on older
installs. Introspection failures are treated as unsupported; the caller
warns on that path so a future signature change is visible.
"""
try:
return "event_filter" in inspect.signature(observer.schedule).parameters
except (TypeError, ValueError):
return False
_READ_ONLY_EVENT_TYPES = frozenset({"opened", "closed_no_write"})
@@ -3532,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
@@ -3547,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
@@ -3595,9 +3696,97 @@ 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()
observer.schedule(handler, str(watch_root_for_ignore), recursive=True)
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),
recursive=True,
event_filter=_watch_event_filter(),
)
else:
logger.warning(
"watchdog does not declare event_filter; read-only inotify events "
"may overflow the queue and lose changes (#5033)"
)
observer.schedule(handler, str(watch_root_for_ignore), recursive=True)
observer.start()
print(f"[graphify watch] Watching {watch_path.resolve()} - press Ctrl+C to stop")
+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.103"
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"
+7
View File
@@ -45,6 +45,13 @@ def test_node_filepath_folds_to_source_file():
assert node["source_file"] == "baz.go"
def test_node_src_folds_to_source_file():
node = {"id": "a", "label": "A", "src": "src/engine.py"}
_fold_node_aliases(node)
assert node["source_file"] == "src/engine.py"
assert "src" not in node
def test_node_source_file_wins_over_alias():
node = {"id": "a", "label": "A", "source_file": "real.py", "file": "other.py"}
_fold_node_aliases(node)
+61
View File
@@ -1528,6 +1528,67 @@ def test_graph_has_legacy_ids_detects_old_scheme():
assert graph_has_legacy_ids(go_symbol, root=".") is False
def test_graph_has_legacy_ids_honors_the_scan_root_prefix():
"""A subfolder build run from its parent (`graphify update sub`) stores
source_file cwd-relative (#2603) but mints ids scan-root-relative. With the
marker's prefix the fresh graph is canonical; without it, `pkg_mod` reads as
the old one-parent form of `sub/pkg/mod.py` and every query warned."""
from graphify.build import graph_has_legacy_ids
fresh = [{"id": "pkg_mod", "source_file": "sub/pkg/mod.py", "type": "code", "source_location": "L1"}]
assert graph_has_legacy_ids(fresh, root=None) is True # the false positive
assert graph_has_legacy_ids(fresh, root=None, source_prefix="sub") is False
assert graph_has_legacy_ids(fresh, root=None, source_prefix="sub/") is False
# A genuinely pre-#1504 id under the same prefix is still caught.
old = [{"id": "v1_readme", "source_file": "sub/docs/v1/README.md", "type": "document", "source_location": "L1"}]
assert graph_has_legacy_ids(old, root=None, source_prefix="sub") is True
# A source_file outside the prefix is judged as stored.
other = [{"id": "docs_v1_readme", "source_file": "docs/v1/README.md", "type": "document", "source_location": "L1"}]
assert graph_has_legacy_ids(other, root=None, source_prefix="sub") is False
@pytest.mark.parametrize("marker, expected", [
("sub", "sub"),
("./a/b/", "a/b"),
("a\\b", "a/b"),
(".", None),
("", None),
("../elsewhere", None),
("/abs/scan/root", None),
("C:\\scan\\root", None),
])
def test_legacy_id_source_prefix_reads_the_relative_marker(tmp_path, marker, expected):
from graphify.build import legacy_id_source_prefix
out = tmp_path / "graphify-out"
out.mkdir()
(out / ".graphify_root").write_text(marker, encoding="utf-8")
assert legacy_id_source_prefix(out / "graph.json") == expected
def test_legacy_id_source_prefix_without_marker(tmp_path):
from graphify.build import legacy_id_source_prefix
assert legacy_id_source_prefix(tmp_path / "graph.json") is None
def test_subfolder_build_from_parent_is_not_flagged_legacy(tmp_path, monkeypatch):
"""End to end: `graphify update proj` from proj's parent, then the same
probe the query/serve consumers run, must not call the fresh graph legacy."""
import json
from graphify.build import graph_has_legacy_ids, legacy_id_source_prefix
from graphify.watch import _rebuild_code
proj = tmp_path / "proj"
(proj / "pkg").mkdir(parents=True)
(proj / "pkg" / "mod.py").write_text("def a():\n return 1\n", encoding="utf-8")
(proj / "main.py").write_text("from pkg.mod import a\n", encoding="utf-8")
monkeypatch.chdir(tmp_path)
assert _rebuild_code(Path("proj"), no_cluster=True)
gp = proj / "graphify-out" / "graph.json"
nodes = json.loads(gp.read_text(encoding="utf-8"))["nodes"]
files = {n["source_file"] for n in nodes if n.get("source_location") == "L1"}
assert "proj/pkg/mod.py" in files # stored cwd-relative (#2603)
assert legacy_id_source_prefix(gp) == "proj"
assert graph_has_legacy_ids(nodes, source_prefix=legacy_id_source_prefix(gp)) is False
# ── #2408: globally-scoped MCP node ids are not file-stem derived ──────────────
@pytest.mark.parametrize("mcp_kind, nid", [
+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):
+94
View File
@@ -1,4 +1,6 @@
"""Tests for graphify/cache.py."""
import json
import os
import pytest
from pathlib import Path
from graphify.cache import file_hash, cache_dir, load_cached, save_cached, cached_files, clear_cache, _body_content
@@ -851,6 +853,27 @@ def test_warm_cache_keeps_target_and_symlink_sources_distinct(
assert {Path(source).name for source in cold_counts} == {"real.py", "link.py"}
@pytest.mark.skipif(os.name != "nt", reason="directory junctions are Windows-only")
def test_file_hash_distinguishes_walked_junction_paths(tmp_path):
r"""#2832 with junctions, which need no symlink privilege. Under a junctioned
scan root the walked-parent match compared a plain spelling with the
``\\?\`` form of the root (#4925), never matched, and the in-root alias fell
back to its target's salt and shared its digest."""
import subprocess
_reset_stat_index()
root = tmp_path / "repo"
(root / "sub").mkdir(parents=True)
target = root / "sub" / "g.py"
target.write_text("def g():\n return 1\n")
for link, dest in ((root / "alias", root / "sub"), (tmp_path / "scan", root)):
subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(dest)],
check=True, capture_output=True)
walked_alias = tmp_path / "scan" / "alias" / "g.py"
assert file_hash(walked_alias, root) != file_hash(target, root)
def test_semantic_cache_self_heals_legacy_symlink_collision(
requires_symlinks, tmp_path
):
@@ -2051,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
+6 -1
View File
@@ -162,7 +162,12 @@ def _env() -> dict[str, str]:
def _run(block: str, proj: Path, *, python_on_stdin: bool = False) -> subprocess.CompletedProcess[str]:
block = block.replace("INPUT_PATH", proj.as_posix()).replace("IS_DIRECTED", "False")
# Since #4762 the block reads the scan root from the trusted .graphify_root
# sidecar instead of a substituted literal; write it as Step 1 would.
out = proj / "graphify-out"
out.mkdir(parents=True, exist_ok=True)
(out / ".graphify_root").write_text(proj.as_posix(), encoding="utf-8")
block = block.replace("IS_DIRECTED", "False")
if python_on_stdin:
here_string = re.search(r"@'\n(.*?)\n'@", block, re.S)
assert here_string, "no PowerShell here-string in the block"
+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"]
+7 -3
View File
@@ -144,7 +144,9 @@ def test_element_access_without_element_type_gives_no_edge(tmp_path):
assert not {t for s, t in calls if s == save}
def test_constructor_calls_are_attributed_to_the_type(tmp_path):
def test_constructor_calls_are_attributed_to_the_constructor(tmp_path):
# A constructor is its own node, so its body's calls are its calls, not
# the type's (#4246 credited them to the type before constructors had nodes).
calls, r = _calls(tmp_path, {
"Bound.cs": (
"namespace Demo\n{\n"
@@ -159,7 +161,9 @@ def test_constructor_calls_are_attributed_to_the_type(tmp_path):
" }\n}\n"
),
})
assert (_find(r, "BoundFunc", "boundfunc"), _find(r, ".GameObjectOf()", "bound")) in calls
game_object_of = _find(r, ".GameObjectOf()", "bound")
assert (_find(r, ".BoundFunc()", "boundfunc"), game_object_of) in calls
assert (_find(r, "BoundFunc", "boundfunc"), game_object_of) not in calls
def test_constructor_typed_parameter_and_this_calls_resolve(tmp_path):
@@ -173,7 +177,7 @@ def test_constructor_typed_parameter_and_this_calls_resolve(tmp_path):
" }\n}\n"
),
})
holder = _find(r, "Holder", "holder")
holder = _find(r, ".Holder()", "holder")
assert (holder, _find(r, ".Apply()", "sequence")) in calls
assert (holder, _find(r, ".Apply()", "decoy")) not in calls
assert (holder, _find(r, ".Ping()", "basesvc")) in calls
+163
View File
@@ -158,3 +158,166 @@ def test_case_only_sibling_properties_do_not_duplicate_an_edge(tmp_path):
odd = _find(r, "Odd")
assert defines == {(odd, _find(r, "Count")), (odd, _find(r, "count"))}
assert _find(r, "Count") != _find(r, "count")
# The calls a property, indexer or operator makes belong to that member: its
# accessor and operator bodies run code just like a method's.
def _calls(r):
return {(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"}
def _kind(r, kind):
return [n for n in r["nodes"] if (n.get("metadata") or {}).get("kind") == kind]
def test_property_accessor_bodies_call_from_the_property(tmp_path):
_, r = _extract(tmp_path, {"S.cs": (
"public class Svc {\n"
" int _v;\n"
" public int Block { get { return Load(); } set { Save(value); } }\n"
" public int Arrow { get => Load(); }\n"
" public int Body => Compute();\n"
" public int Auto { get; set; } = Seed();\n"
" int Load() { return _v; }\n"
" void Save(int v) { _v = v; }\n"
" int Compute() { return 1; }\n"
" static int Seed() { return 0; }\n"
"}\n"
)})
calls = _calls(r)
load, save = _find(r, ".Load()"), _find(r, ".Save()")
assert {(_find(r, "Block"), load), (_find(r, "Block"), save)} <= calls
assert (_find(r, "Arrow"), load) in calls
assert (_find(r, "Body"), _find(r, ".Compute()")) in calls
# An initializer runs in the constructor, not in the property.
assert (_find(r, "Auto"), _find(r, ".Seed()")) not in calls
def test_accessor_call_prefers_its_own_type_like_a_method(tmp_path):
# Other comes last, so a file-wide name lookup would pick its Load().
_, r = _extract(tmp_path, {"S.cs": (
"public class Svc {\n"
" public int Value => Load();\n"
" int Load() { return 1; }\n"
"}\n"
"public class Other { public int Load() { return 2; } }\n"
)})
own = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "svc" in n["id"])
other = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "other" in n["id"])
assert (_find(r, "Value"), own) in _calls(r)
assert (_find(r, "Value"), other) not in _calls(r)
def test_accessor_call_through_a_typed_receiver_resolves_cross_file(tmp_path):
_, r = _extract(tmp_path, {
"Repo.cs": "namespace Demo { public class Repo { public int Count() { return 0; } } }\n",
"Svc.cs": (
"namespace Demo { public class Svc {\n"
" private Repo _repo;\n"
" public int Total => _repo.Count();\n"
"} }\n"
),
})
assert (_find(r, "Total"), _find(r, ".Count()")) in _calls(r)
def test_indexer_is_a_node_and_owns_its_accessor_calls(tmp_path):
_, r = _extract(tmp_path, {"S.cs": (
"public class Bag {\n"
" public int This { get; set; }\n"
" public int this[int i] { get { return Get(i); } }\n"
" public int this[string k] => Find(k);\n"
" int Get(int i) { return i; }\n"
" int Find(string k) { return 0; }\n"
"}\n"
)})
indexers = {n["metadata"]["signature"]: n["id"] for n in _kind(r, "indexer")}
assert set(indexers) == {"int", "string"}
assert indexers["int"] != indexers["string"]
# The `This` property keeps the id it had before indexers were nodes.
assert _find(r, "This") == _find(r, "Bag") + "_this"
assert _find(r, "This") not in indexers.values()
calls = _calls(r)
assert (indexers["int"], _find(r, ".Get()")) in calls
assert (indexers["string"], _find(r, ".Find()")) in calls
def test_operators_and_conversions_are_nodes_that_own_their_calls(tmp_path):
_, r = _extract(tmp_path, {"S.cs": (
"public class Money {\n"
" public static Money operator +(Money a, Money b) => Add(a, b);\n"
" public static explicit operator int(Money m) { return ToInt(m); }\n"
" public static explicit operator long(Money m) { return ToLong(m); }\n"
" static Money Add(Money a, Money b) { return a; }\n"
" static int ToInt(Money m) { return 0; }\n"
" static long ToLong(Money m) { return 0; }\n"
"}\n"
)})
ops = {n["label"]: n["id"] for n in _kind(r, "operator")}
assert set(ops) == {".operator +()", ".operator int()", ".operator long()"}
calls = _calls(r)
assert (ops[".operator +()"], _find(r, ".Add()")) in calls
assert (ops[".operator int()"], _find(r, ".ToInt()")) in calls
assert (ops[".operator long()"], _find(r, ".ToLong()")) in calls
assert (ops[".operator int()"], _find(r, ".ToLong()")) not in calls
def test_accessor_base_call_resolves_to_the_base_in_another_file(tmp_path):
_, r = _extract(tmp_path, {
"Base.cs": "namespace Demo { public class Base { public int Compute() { return 0; } } }\n",
"Svc.cs": (
"namespace Demo { public class Svc : Base {\n"
" public int Total => base.Compute();\n"
"} }\n"
),
})
assert (_find(r, "Total"), _find(r, ".Compute()")) in _calls(r)
def test_accessor_call_binds_the_other_partial_half_over_a_same_named_method(tmp_path):
_, r = _extract(tmp_path, {
"SvcA.cs": "namespace Demo { public partial class Svc { public int Value => Load(); } }\n",
"SvcB.cs": "namespace Demo { public partial class Svc { int Load() { return 1; } } }\n",
"Other.cs": "namespace Demo { public class Other { public int Load() { return 2; } } }\n",
})
own = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "svc" in n["id"])
other = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "other" in n["id"])
assert (_find(r, "Value"), own) in _calls(r)
assert (_find(r, "Value"), other) not in _calls(r)
def test_explicit_interface_indexers_keep_their_own_calls(tmp_path):
_, r = _extract(tmp_path, {"S.cs": (
"public interface IA { int this[int i] { get; } }\n"
"public interface IB { int this[int i] { get; } }\n"
"public class C : IA, IB {\n"
" int IA.this[int i] => A();\n"
" int IB.this[int i] => B();\n"
" int A() { return 1; }\n"
" int B() { return 2; }\n"
"}\n"
)})
by_line = {n["source_location"]: n["id"] for n in _kind(r, "indexer")
if "_c_" in n["id"]}
assert len(by_line) == 2
calls = _calls(r)
assert (by_line["L4"], _find(r, ".A()")) in calls
assert (by_line["L5"], _find(r, ".B()")) in calls
assert (by_line["L4"], _find(r, ".B()")) not in calls
def test_property_sharing_a_methods_id_does_not_lend_it_its_calls(tmp_path):
# `IRun.Next` and `Next()` normalize to one id, which the method owns; the
# property's call must not be credited to the method (a self-loop here).
_, r = _extract(tmp_path, {"S.cs": (
"public interface IRun { int Next { get; } }\n"
"public class Run : IRun {\n"
" int Next() { return Other(); }\n"
" int IRun.Next => Next();\n"
" int Other() { return 0; }\n"
"}\n"
)})
method = _find(r, ".Next()")
assert (method, method) not in _calls(r)
assert (method, _find(r, ".Other()")) in _calls(r)
+2 -1
View File
@@ -107,7 +107,8 @@ def test_extraction_keeps_the_bare_resolver_label(tmp_path):
_write(tmp_path, {"Report.cs": _ISSUE_REPRO})
raw = extract([tmp_path / "Report.cs"], root=tmp_path)
methods = sorted(n["label"] for n in raw["nodes"] if n["label"].endswith("()"))
assert methods == [".Build()", ".Build()", ".Build()", ".Run()"]
# `.Exporter()` is Exporter's constructor.
assert methods == [".Build()", ".Build()", ".Build()", ".Exporter()", ".Run()"]
def test_incremental_rebuild_binds_into_an_unchanged_file(tmp_path):
+147
View File
@@ -371,3 +371,150 @@ def test_qualified_construction_with_an_unknown_outer_type_gives_no_edge(tmp_pat
ensure = _find(r, ".Ensure()", "ensure")
slots = {n["id"] for n in r["nodes"] if n["label"] == "Slot"}
assert not any(t in slots for s, t in calls if s == ensure)
# Constructors are nodes: `new X(a, b)` and `: base(...)` / `: this(...)` reach
# the overload whose parameter count fits, next to the edge to the type.
def _ctor(r, type_name, signature):
ids = [n["id"] for n in r["nodes"]
if n["label"] == f".{type_name}()"
and (n.get("metadata") or {}).get("kind") == "constructor"
and (n.get("metadata") or {}).get("signature") == signature]
assert len(ids) == 1, (type_name, signature, ids)
return ids[0]
def test_construction_links_the_constructor_overload_its_arguments_fit(tmp_path):
calls, r = _extract(tmp_path, {
"Repo.cs": (
"public class Repo {\n"
" public Repo() { }\n"
" public Repo(int a) { }\n"
" public Repo(int a, int b) { }\n"
"}\n"
),
"User.cs": "public class User { public void Go() { var r = new Repo(1, 2); } }\n",
})
go = _find(r, ".Go()", "user")
assert (go, _find(r, "Repo", "repo")) in calls # the type edge stays
assert (go, _ctor(r, "Repo", "int,int")) in calls
assert (go, _ctor(r, "Repo", "int")) not in calls
assert (go, _ctor(r, "Repo", "")) not in calls
def test_construction_two_overloads_fit_gives_no_constructor_edge(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Repo { public Repo(int a) { } public Repo(string s) { } }\n"
"public class User { public void Go() { var r = new Repo(1); } }\n"
)})
go = _find(r, ".Go()", "user")
assert (go, _find(r, "Repo", "repo")) in calls
assert not {t for s, t in calls if s == go} & {
_ctor(r, "Repo", "int"), _ctor(r, "Repo", "string")
}
def test_constructor_body_and_initializer_calls_belong_to_the_constructor(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Base { public Base(int a) { } }\n"
"public class Svc : Base {\n"
" public Svc(int x) : base(Seed(x)) { Init(); }\n"
" static int Seed(int x) { return x; }\n"
" void Init() { }\n"
"}\n"
)})
ctor = _ctor(r, "Svc", "int")
svc = _find(r, "Svc", "svc")
for callee in (".Seed()", ".Init()"):
assert (ctor, _find(r, callee, "svc")) in calls
assert (svc, _find(r, callee, "svc")) not in calls
def test_this_initializer_links_the_own_overload(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Svc {\n"
" public Svc() : this(1, 2) { }\n"
" public Svc(int a) { }\n"
" public Svc(int a, int b) { }\n"
"}\n"
)})
assert (_ctor(r, "Svc", ""), _ctor(r, "Svc", "int,int")) in calls
assert (_ctor(r, "Svc", ""), _ctor(r, "Svc", "int")) not in calls
def test_base_initializer_links_the_base_constructor_in_another_file(tmp_path):
calls, r = _extract(tmp_path, {
"Base.cs": (
"namespace Demo {\n"
" public class Base { public Base(int a) { } public Base(string a, int b) { } }\n"
"}\n"
),
"Derived.cs": (
"namespace Demo {\n"
" public class Derived : Base { public Derived(int x) : base(\"s\", x) { } }\n"
"}\n"
),
})
derived = _ctor(r, "Derived", "int")
assert (derived, _ctor(r, "Base", "string,int")) in calls
assert (derived, _ctor(r, "Base", "int")) not in calls
def test_base_initializer_with_an_out_of_corpus_base_gives_no_edge(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Local { public Local(int a) { } }\n"
"public class Derived : System.Exception { public Derived(int x) : base(\"m\") { } }\n"
)})
derived = _ctor(r, "Derived", "int")
assert not {t for s, t in calls if s == derived}
def test_static_constructor_is_its_own_node_and_never_constructed(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Reg {\n"
" static Reg() { Load(); }\n"
" public Reg() { }\n"
" static void Load() { }\n"
"}\n"
"public class User { public void Go() { var r = new Reg(); } }\n"
)})
static_ctor, instance_ctor = _ctor(r, "Reg", "static"), _ctor(r, "Reg", "")
assert static_ctor != instance_ctor
assert (static_ctor, _find(r, ".Load()", "reg")) in calls
go = _find(r, ".Go()", "user")
assert (go, instance_ctor) in calls
assert (go, static_ctor) not in calls
def test_primary_constructor_competes_with_the_explicit_ones(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public record Point(int X, int Y) { public Point(int x) : this(x, 0) { } }\n"
"public class User { public void Go() { var a = new Point(1, 2); var b = new Point(3); } }\n"
)})
primary, explicit = _ctor(r, "Point", "int,int"), _ctor(r, "Point", "int")
go = _find(r, ".Go()", "user")
assert {(go, primary), (go, explicit), (explicit, primary)} <= calls
def test_constructor_in_an_unchanged_file_resolves_on_an_incremental_rebuild(tmp_path):
import json
from graphify.watch import _rebuild_code
files = {
"Repo.cs": "public class Repo { public Repo() { } public Repo(int a, int b) { } }\n",
"User.cs": "public class User { public void Go() { var r = new Repo(1, 2); } }\n",
}
for name, body in files.items():
(tmp_path / name).write_text(body)
assert _rebuild_code(tmp_path, no_cluster=True, acquire_lock=False, force=True)
user = tmp_path / "User.cs"
user.write_text(user.read_text() + "// touched\n")
assert _rebuild_code(tmp_path, changed_paths=[user], no_cluster=True, acquire_lock=False)
graph = json.loads((tmp_path / "graphify-out" / "graph.json").read_text())
ctor = next(n["id"] for n in graph["nodes"]
if (n.get("metadata") or {}).get("signature") == "int,int")
go = next(n["id"] for n in graph["nodes"] if n["label"].endswith("Go()"))
assert any(l["source"] == go and l["target"] == ctor and l["relation"] == "calls"
for l in graph["links"])
@@ -284,3 +284,20 @@ def test_base_call_reaches_the_underscore_method(tmp_path):
sub, base = sorted(_ids(r, "._Action()"), key=lambda nid: "subwidget" not in nid)
assert (sub, base) in _edges(r, "calls")
assert (sub, _one(r, ".Action()")) not in _edges(r, "calls")
def test_constructor_never_takes_the_id_of_a_member_spelled_like_its_type(tmp_path):
# `Foo()` (the constructor) and `foo()` normalize to one id. The method
# had it before constructors were nodes and keeps it, wherever the
# constructor is declared; the constructor gets a salted id.
for body in (
"public class Foo { public Foo() { Bar(); } public void foo() { } public void Bar() { } }\n",
"public class Foo { public void foo() { } public Foo() { Bar(); } public void Bar() { } }\n",
):
r = _extract(tmp_path, {"Foo.cs": body})
method = _one(r, "Foo") + "_foo"
assert _one(r, ".foo()") == method
ctor = _one(r, ".Foo()")
assert ctor != method
assert (ctor, _one(r, ".Bar()")) in _edges(r, "calls")
assert (method, _one(r, ".Bar()")) not in _edges(r, "calls")
+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
+65
View File
@@ -0,0 +1,65 @@
"""Global graph commands recover from JSON with the wrong manifest shape."""
import json
import pytest
from graphify import global_graph
@pytest.mark.parametrize("payload", [None, [], {}, {"repos": []}])
def test_global_list_backs_up_wrong_manifest_shape(tmp_path, monkeypatch, capsys, payload):
# A non-dict root, or a repos value that is not a map at all, is too broken
# to recover per-entry: back it up and start fresh.
manifest = tmp_path / "global-manifest.json"
original = json.dumps(payload)
manifest.write_text(original, encoding="utf-8")
monkeypatch.setattr(global_graph, "_GLOBAL_MANIFEST", manifest)
assert global_graph.global_list() == {}
assert not manifest.exists()
backup, = tmp_path.glob("global-manifest.json.corrupt.*")
assert backup.read_text(encoding="utf-8") == original
assert "moved to" in capsys.readouterr().err
def test_global_list_isolates_malformed_repo_entries(tmp_path, monkeypatch, capsys):
# A single malformed entry must not discard the user's other repos (#5020):
# drop only the bad one, keep the good ones, and do NOT back up the file.
manifest = tmp_path / "global-manifest.json"
good = {"source_path": "graph.json", "node_count": 2}
manifest.write_text(
json.dumps({"version": 1, "repos": {"goodA": good, "bad": "oops", "goodB": good}}),
encoding="utf-8",
)
monkeypatch.setattr(global_graph, "_GLOBAL_MANIFEST", manifest)
assert global_graph.global_list() == {"goodA": good, "goodB": good}
assert manifest.is_file() # not backed up
assert not list(tmp_path.glob("global-manifest.json.corrupt.*"))
err = capsys.readouterr().err
assert "dropped 1 malformed repo" in err and "bad" in err
def test_global_list_drops_all_malformed_entries_without_backup(tmp_path, monkeypatch):
# An all-malformed repos map is still a valid shape: it collapses to empty
# rather than being backed up.
manifest = tmp_path / "global-manifest.json"
manifest.write_text(json.dumps({"repos": {"legacy": "invalid"}}), encoding="utf-8")
monkeypatch.setattr(global_graph, "_GLOBAL_MANIFEST", manifest)
assert global_graph.global_list() == {}
assert manifest.is_file()
assert not list(tmp_path.glob("global-manifest.json.corrupt.*"))
def test_global_list_preserves_valid_manifest(tmp_path, monkeypatch):
manifest = tmp_path / "global-manifest.json"
repos = {"project": {"source_path": "graph.json", "node_count": 2}}
manifest.write_text(json.dumps({"version": 1, "repos": repos}), encoding="utf-8")
monkeypatch.setattr(global_graph, "_GLOBAL_MANIFEST", manifest)
assert global_graph.global_list() == repos
assert manifest.is_file()
+8 -1
View File
@@ -152,7 +152,14 @@ def test_read_errors_stay_stale(tmp_path, monkeypatch, failure):
original_open = builtins.open
def denied_source(file, *args, **kwargs):
if Path(file) == f:
# The hashing code opens the source through paths.os_long_path,
# which on win32 prepends the extended-length \\?\ marker so long
# paths survive open(). Comparing that prefixed string straight
# against f as plain Path objects never matches on Windows, so
# the mock never raised and this branch silently tested the
# readable-file case instead. Normalize both sides the same way
# the source itself does before comparing.
if paths.os_long_path(file) == paths.os_long_path(f):
raise PermissionError("unreadable fixture")
return original_open(file, *args, **kwargs)
+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
+36
View File
@@ -0,0 +1,36 @@
"""Concurrent URL captures must reserve distinct names."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier
import pytest
from graphify import ingest as ingest_mod
@pytest.mark.parametrize("suffix", [".pdf", ""])
def test_concurrent_captures_preserve_both_payloads(tmp_path, monkeypatch, suffix):
preferred = tmp_path / ("example_org_report_pdf.pdf" if suffix else "example_org_report.md")
original_lstat = Path.lstat
both_selected = Barrier(2, timeout=10)
def lstat(path, *args, **kwargs):
try:
return original_lstat(path, *args, **kwargs)
except FileNotFoundError:
if path == preferred:
both_selected.wait()
raise
monkeypatch.setattr(Path, "lstat", lstat)
monkeypatch.setattr(ingest_mod, "validate_url", lambda url: url)
monkeypatch.setattr(ingest_mod, "safe_fetch", lambda url: url.encode())
monkeypatch.setattr(ingest_mod, "_fetch_webpage", lambda url, *_: (url, preferred.name))
urls = [f"https://example.org/report{suffix}?capture={number}" for number in (1, 2)]
with ThreadPoolExecutor(max_workers=2) as pool:
paths = list(pool.map(lambda url: ingest_mod.ingest(url, tmp_path), urls))
assert len(set(paths)) == 2
assert {path.read_text(encoding="utf-8") for path in paths} == set(urls)
+4 -2
View File
@@ -295,8 +295,10 @@ def test_claude_install_ships_lean_core_and_references(tmp_path):
assert "references/extraction-spec.md" in body
# The full embedded subagent prompt was moved out into the references.
assert '"file_type":"code|document|paper|image|rationale|concept"' not in body
# The lean core is materially smaller than the old ~1156-line monolith.
assert len(body.splitlines()) < 800
# The lean core is materially smaller than the old ~1156-line monolith. The
# ceiling has a little headroom for the #4762 per-block `.graphify_root` reads
# (one line per Python block) while staying well under the monolith.
assert len(body.splitlines()) < 820
# The version stamp covers SKILL.md + references/ together.
assert (skill_dir / ".graphify_version").read_text() == mainmod.__version__
# The eight on-demand fragments all landed.
+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
+30
View File
@@ -0,0 +1,30 @@
"""Malformed optional learning data cannot hide healthy entries."""
import json
import pytest
from graphify.reflect import LEARNING_SIDECAR_NAME, load_learning_overlay
@pytest.mark.parametrize("payload", [None, [], 7, "unexpected"])
def test_learning_overlay_ignores_non_object_root(tmp_path, payload):
(tmp_path / LEARNING_SIDECAR_NAME).write_text(json.dumps(payload), encoding="utf-8")
assert load_learning_overlay(tmp_path / "graph.json") == {}
def test_learning_overlay_keeps_valid_entries_beside_malformed_source(tmp_path):
payload = {"nodes": {
"bad": {"source_file": ["app.py"], "status": "preferred"},
"good": {"status": "preferred", "score": 2},
"legacy": {"source_file": None, "status": "preferred"},
"gone": {"source_file": "deleted.py", "status": "preferred"},
}}
(tmp_path / LEARNING_SIDECAR_NAME).write_text(json.dumps(payload), encoding="utf-8")
assert load_learning_overlay(tmp_path / "graph.json") == {
"good": {"status": "preferred", "score": 2, "stale": False},
"legacy": {"source_file": None, "status": "preferred", "stale": False},
"gone": {"source_file": "deleted.py", "status": "preferred", "stale": True},
}
+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
+75
View File
@@ -162,3 +162,78 @@ def test_detect_backend_custom_provider_after_builtins(monkeypatch):
result = llm.detect_backend()
assert result == "myprovider"
def test_dispatch_command_provider_add_with_pricing_equals(tmp_path, monkeypatch):
"""`graphify provider add` supports --pricing-input=VAL and --pricing-output=VAL syntax."""
import sys
from graphify import cli, llm
providers_file = tmp_path / "providers.json"
monkeypatch.setattr(llm, "_custom_providers_path", lambda global_=True: providers_file)
test_args = [
"graphify", "provider", "add", "mycustom",
"--base-url=http://localhost:8080/v1",
"--default-model=model-x",
"--env-key=MY_KEY",
"--pricing-input=0.15",
"--pricing-output=0.60",
]
monkeypatch.setattr(sys, "argv", test_args)
cli.dispatch_command("provider")
assert providers_file.exists()
data = json.loads(providers_file.read_text(encoding="utf-8"))
assert "mycustom" in data
assert data["mycustom"]["pricing"] == {"input": 0.15, "output": 0.60}
def test_dispatch_command_provider_add_invalid_pricing_float(tmp_path, monkeypatch, capsys):
"""Invalid float for --pricing-input exits with code 1 and prints an error."""
import sys
from graphify import cli, llm
providers_file = tmp_path / "providers.json"
monkeypatch.setattr(llm, "_custom_providers_path", lambda global_=True: providers_file)
test_args = [
"graphify", "provider", "add", "mycustom",
"--base-url=http://localhost:8080/v1",
"--default-model=model-x",
"--env-key=MY_KEY",
"--pricing-input=invalid_number",
]
monkeypatch.setattr(sys, "argv", test_args)
with pytest.raises(SystemExit) as exc:
cli.dispatch_command("provider")
assert exc.value.code == 1
err = capsys.readouterr().err
assert "invalid price for --pricing-input" in err
@pytest.mark.parametrize("bad", ["nan", "inf", "-inf", "1e999", "-5"])
def test_dispatch_command_provider_add_rejects_non_finite_or_negative_pricing(
tmp_path, monkeypatch, capsys, bad
):
"""A price that parses as a float but is NaN/inf/negative is rejected: it
would otherwise flow into cost estimation as NaN/inf/negative (#5031)."""
import sys
from graphify import cli, llm
providers_file = tmp_path / "providers.json"
monkeypatch.setattr(llm, "_custom_providers_path", lambda global_=True: providers_file)
test_args = [
"graphify", "provider", "add", "mycustom",
"--base-url=http://localhost:8080/v1",
"--default-model=model-x",
"--env-key=MY_KEY",
f"--pricing-input={bad}",
]
monkeypatch.setattr(sys, "argv", test_args)
with pytest.raises(SystemExit) as exc:
cli.dispatch_command("provider")
assert exc.value.code == 1
assert "invalid price for --pricing-input" in capsys.readouterr().err
assert not providers_file.exists()
+115
View File
@@ -1022,6 +1022,37 @@ def test_pick_seeds_per_term_guarantee_does_not_reintroduce_generic_dupe(monkeyp
assert len(get_seeds) == 1, f"per-term guarantee reintroduced a GET dupe: {seeds}"
def test_pick_seeds_keeps_same_label_node_that_is_only_match_for_a_term():
"""A node sharing a seeded label must still be seeded when it is the only
match for a query term the label doesn't contain: `alpha` matches only
`alpha_pre`'s source path, so the seeded `PreToolUse` twin can't cover it (#5027)."""
G = nx.Graph()
G.add_node("hooks_pre", label="PreToolUse", source_file="plugins/core/lib/core_hooks/handler/pre_tool_use.rb")
G.add_node("hooks_run", label=".run", source_file="plugins/core/lib/core_hooks/handler/pre_tool_use.rb")
G.add_node("alpha_pre", label="PreToolUse", source_file="plugins/core-alpha/lib/alpha/pre_tool_use.rb")
G.add_edge("hooks_pre", "hooks_run")
qs = _score_query(G, ["core", "alpha", "PreToolUse", "hook", "handler"], collect_per_term_seeds=True)
assert qs.best_seed_by_term["alpha"] == "alpha_pre"
seeds = _pick_seeds(qs.ranked, G=G, best_seed_by_term=qs.best_seed_by_term, term_order=qs.term_order)
assert "alpha_pre" in seeds, f"only match for 'alpha' was dropped by the label cap: {seeds}"
def test_pick_seeds_per_term_still_caps_same_label_winner_of_a_label_term():
"""The #5027 exception is narrow: when the term is part of the shared label,
the seeded twin already matches it, so a different same-label winner is still
capped. `get2` wins `get` on the degree tie-break while the first loop seeds
`get0`, so this reaches the per-term cap (#1766)."""
G = nx.DiGraph()
for i in range(3):
G.add_node(f"get{i}", label="GET", source_file=f"r{i}.py")
G.add_node("x", label="x_helper", source_file="x.py")
G.add_edge("get2", "x")
qs = _score_query(G, ["get"], collect_per_term_seeds=True)
assert qs.best_seed_by_term["get"] == "get2"
seeds = _pick_seeds(qs.ranked, G=G, best_seed_by_term=qs.best_seed_by_term)
assert seeds == ["get0"], f"per-term guarantee added a second GET: {seeds}"
def test_score_nodes_scores_identical_labels_equally():
"""Guard against a per-label multiplicity penalty leaking into _score_nodes
(shared by shortest_path / explain endpoint resolution): two nodes with the
@@ -2135,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"}
@@ -40,7 +40,12 @@ def _section(body: str, start: str, end: str) -> str:
def _run_code(script: str, *, cwd: Path, root: Path) -> subprocess.CompletedProcess[str]:
script = script.replace("INPUT_PATH", root.as_posix()).replace("IS_DIRECTED", "False")
# Since #4762 the blocks read the scan root from the trusted .graphify_root
# sidecar instead of a substituted literal; Step 1 writes it, so simulate that.
out = cwd / "graphify-out"
out.mkdir(parents=True, exist_ok=True)
(out / ".graphify_root").write_text(root.as_posix(), encoding="utf-8")
script = script.replace("IS_DIRECTED", "False")
env = {
**os.environ,
"GRAPHIFY_OUT": "graphify-out",
+6 -1
View File
@@ -26,7 +26,12 @@ def _python_blocks(body: str, start: str, end: str) -> list[str]:
def _run(source: str, *, cwd: Path, corpus: Path, spec: Path) -> None:
source = source.replace("INPUT_PATH", corpus.as_posix()).replace("SPEC_PATH", spec.as_posix())
# Since #4762 the blocks read the scan root from the trusted .graphify_root
# sidecar instead of a substituted INPUT_PATH literal; simulate Step 1's write.
out = cwd / "graphify-out"
out.mkdir(parents=True, exist_ok=True)
(out / ".graphify_root").write_text(corpus.as_posix(), encoding="utf-8")
source = source.replace("SPEC_PATH", spec.as_posix())
subprocess.run([sys.executable, "-c", source], cwd=cwd, check=True,
capture_output=True, text=True)
+8 -4
View File
@@ -45,7 +45,9 @@ def test_part_a_passes_an_explicit_root(platform: gen.Platform):
calls = _part_a_calls(platform)
assert calls, f"[{platform.key}] Part A extract() call not found"
for call in calls:
assert "root=Path('INPUT_PATH')" in call.replace("cache_root=Path('INPUT_PATH')", ""), (
# Since #4762 the scan root is the INPUT_PATH variable read from the
# trusted .graphify_root sidecar, not a substituted literal.
assert "root=Path(INPUT_PATH)" in call.replace("cache_root=Path(INPUT_PATH)", ""), (
f"[{platform.key}] Part A calls extract() with cache_root but no root= (#3727): {call!r}"
)
@@ -61,10 +63,12 @@ def test_relocating_only_the_cache_does_not_rename_part_a_nodes(tmp_path: Path):
(call,) = _part_a_calls(gen.load_platforms()["claude"])
expression = call.removeprefix("result = ")
in_place = expression.replace("Path('INPUT_PATH')", f"Path({str(scan_root)!r})")
# The shipped call now reads the root from the sidecar (Path(INPUT_PATH)); for
# this unit test substitute the variable with concrete paths to exercise #3727.
in_place = expression.replace("Path(INPUT_PATH)", f"Path({str(scan_root)!r})")
relocated = expression.replace(
"cache_root=Path('INPUT_PATH')", f"cache_root=Path({str(elsewhere)!r})"
).replace("Path('INPUT_PATH')", f"Path({str(scan_root)!r})")
"cache_root=Path(INPUT_PATH)", f"cache_root=Path({str(elsewhere)!r})"
).replace("Path(INPUT_PATH)", f"Path({str(scan_root)!r})")
assert in_place != relocated
scope = {"extract": extract, "Path": Path, "code_files": [module]}
+8 -3
View File
@@ -16,7 +16,9 @@ def _scan_blocks():
found = []
for art in gen.render_all(gen.load_platforms()):
for block in re.findall(r'```bash\n(.*?)```', art.content, re.S):
if "result = detect(Path('INPUT_PATH')" not in block and "result = detect_incremental(Path('INPUT_PATH')" not in block:
# Since #4762 the scan root is read from the trusted .graphify_root
# sidecar, not substituted, so the call takes the INPUT_PATH variable.
if "result = detect(Path(INPUT_PATH)" not in block and "result = detect_incremental(Path(INPUT_PATH)" not in block:
continue
m = re.search(r' -c "\n(.*)\n"', block, re.S)
if m:
@@ -39,15 +41,18 @@ def test_skill_scan_honors_persisted_options(tmp_path, monkeypatch, art, source)
(corpus / name).write_text('# sample\n', encoding='utf-8')
out = tmp_path / 'graphify-out'
_write_build_config(out, excludes=['docs/skip.md'], gitignore=False)
# Since #4762 the block reads the scan root from the trusted .graphify_root
# sidecar instead of a substituted literal, so Step 1's write is simulated here.
(out / '.graphify_root').write_text(corpus.as_posix(), encoding='utf-8')
# Match the skill's documented CWD-relative output/manifest layout, with
# INPUT_PATH pointing to a distinct corpus rather than the output parent.
if 'detect_incremental' in source:
files = detect(corpus, gitignore=False, extra_excludes=['docs/skip.md'])['files']
save_manifest(files, str(out / 'manifest.json'), root=corpus)
# Only exercise the scan contract, not subsequent sidecar/report steps.
# Only exercise the scan contract, not subsequent sidecar/report steps. Keep
# the preamble (imports + the .graphify_root read) and the detect call itself.
src = source.split('result = ', 1)[0] + 'result = ' + source.split('result = ', 1)[1].split('\n', 1)[0]
src += '\nprint(json.dumps(result))\n'
src = src.replace('INPUT_PATH', corpus.as_posix())
result = subprocess.run([sys.executable, '-c', src], cwd=tmp_path, check=True, capture_output=True, text=True)
data = json.loads(result.stdout)
actual = {Path(f).relative_to(corpus).as_posix() for files in data['files'].values() for f in files}
+4 -1
View File
@@ -83,8 +83,11 @@ def test_all_cached_run_reaches_part_c_with_cached_nodes_and_no_stale_chunks(tmp
json.dumps({"nodes": [{"id": "stale_node", "label": "old", "source_file": "x.md"}],
"edges": []}), encoding="utf-8")
# Since #4762 the blocks read the scan root from the trusted .graphify_root
# sidecar instead of a substituted INPUT_PATH literal; simulate Step 1's write.
(out / ".graphify_root").write_text(corpus.as_posix(), encoding="utf-8")
for src in b0 + b3 + part_c:
src = src.replace("INPUT_PATH", corpus.as_posix()).replace("SPEC_PATH", spec.as_posix())
src = src.replace("SPEC_PATH", spec.as_posix())
subprocess.run([sys.executable, "-c", src], cwd=tmp_path, check=True,
capture_output=True, text=True)
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more