Compare commits

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

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

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

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

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

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

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

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

Refs #4828

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

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

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

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

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

Refs #4828

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

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

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

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

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

Refs #4828

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

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

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

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

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

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

Refs #4828

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #5086

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

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

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

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

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

Fixes #5079

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

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

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

Fixes #5080

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

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

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

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

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

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

Fixes #5034

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

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

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

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

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

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

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

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

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

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

Fixes #5087

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

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

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

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

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

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

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

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

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

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

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

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

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

Reported and first proposed by @danikdanik in #4762.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #5044

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #4766

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

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

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

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

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

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

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

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

Fixes #4602

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

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

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

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

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

Fixes #5011

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #4994

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #1654.

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

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

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

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

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

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

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

Fixes #4688

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

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

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

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

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

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

Fixes #4777.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #4961

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #4962

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

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

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

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

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

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

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

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

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

Fixes #4970

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

AST cache schema 34 -> 35.

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

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

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

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

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

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

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

Two halves:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #4924

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #4432

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

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

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

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

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

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

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

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

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

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

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

Fixes #4792

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #4829

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

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

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

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

Fixes #4648

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

Fixes #4886

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

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

AI-assisted: Claude Code (reproduction, regression test, PR description).
(cherry picked from commit 2836041acc)
2026-10-31 23:43:13 +00:00
339 changed files with 27128 additions and 1871 deletions

No files matched your search

+110
View File
@@ -55,6 +55,15 @@ Always pass `root`. Node ids and `source_file` values are derived relative to it
## Extraction output schema
Terraform/HCL per-file AST results record the scope used to mint their node IDs.
After a cache hit, extraction consumes that scope to rewrite node IDs and edge
endpoints relative to the current scan root, including when the cache was copied
from another checkout. Module-source topology is still resolved against the
current permitted corpus. The scope marker is internal and is not exported in
the graph. AST cache schema 33 retires entries without this marker; the semantic
cache is unchanged. Existing graphs with stale absolute Terraform IDs need a full
code rebuild: `graphify extract . --code-only --force`.
Every extractor returns:
```json
@@ -70,6 +79,35 @@ Every extractor returns:
`validate.py` enforces this schema before `build()` consumes it.
Validation reports list/object enum values as schema errors. Graph assembly
repairs structured `file_type` values to `concept` and structured `confidence`
values to `INFERRED`, without fabricating a confidence score, so malformed
semantic fields cannot abort an otherwise usable build.
JS/TS calls through default imports of directly default-exported object literals reuse existing static method nodes.
Members match the imported module path, exact label and source line. Lexically shadowed receivers, constructor calls,
spread, computed keys, accessors, duplicate keys and dynamic aliases are not inferred. These files bypass the per-file
AST cache, so resolving these cross-file calls does not require an AST cache schema bump.
## Semantic provenance during file-node folding
`build_from_json()` normally folds an evidence-free semantic mention of a
filename into its unique AST file-self node (Pass 2b, #3344); references to
that mention are rewired to the AST node. A cross-source semantic record that
contains its own `rationale`, source URL, author/contributor, capture time,
or metadata is **not** a disposable mention: a label-only fold would discard
its explanation or attribution. Such records remain separate even when their
label matches a unique AST file node. This is intentionally conservative:
a richly annotated mention may remain distinct until an explicit
provenance-preserving merge is available. The saved-semantic-node shrink guard
uses the same rule and still rejects any unexplained loss. Same-source AST/semantic twins that are evidence-free keep their
existing exact-path merge rule (#4389/#4391), but an independently evidenced
semantic YAML/document record is retained across a later AST extractor
upgrade. If AST disambiguation path-qualifies a file-node label, the shrink
guard accounts for a plain same-source fold using the exact source identity
instead of accepting a mere basename collision.
## Edge direction in graph.json
`graph.json` is written `"directed": false`, but every link is directed: **arc order is the direction** (`source` → `target`, #563). Older canonicalized files carry it in `_src`/`_tgt` markers instead, and those win where present (#2309).
@@ -84,6 +122,22 @@ A plain `json_graph.node_link_graph()` load loses this: an undirected graph re-o
| `INFERRED` | Relationship is a reasonable deduction (e.g., call-graph second pass, co-occurrence in context) |
| `AMBIGUOUS` | Relationship is uncertain; flagged for human review in GRAPH_REPORT.md |
Go member calls, including same-file calls, resolve through declared receiver types and
carry `INFERRED` confidence. Bare calls to package-level functions remain `EXTRACTED`;
unknown or ambiguous receivers do not bind by method name alone. AST cache schema 37
retires Go entries created before these receiver-binding rules.
C++ member chains such as `client.actions->Execute()` use lexical local/parameter
bindings and class-scoped field declarations, including fields in unchanged headers.
Raw pointers and single-type-argument `std::unique_ptr<T>` / `std::shared_ptr<T>`
receivers are supported; `.` does not unwrap a smart pointer. Resolved instance
calls are `INFERRED` static-type relationships, not proof of runtime dispatch.
Unknown/shadowed types, ambiguous class identities, unresolved aliases, custom
pointer wrappers, containers, and computed receivers are not guessed. AST cache
schema 41 retires entries without receiver chains and persistent class fields.
Rebuild existing graphs with `graphify extract . --code-only --force` to populate
unchanged headers before relying on changed-file-only updates.
## Adding a new language extractor
1. Add an `extract_<lang>(path: Path) -> dict` function following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges). New languages go in their own module under `graphify/extractors/` - see `graphify/extractors/MIGRATION.md`; `extract.py` re-exports them while the existing ones are ported out of it.
@@ -92,6 +146,14 @@ A plain `json_graph.node_link_graph()` load loses this: an undirected graph re-o
4. Add the tree-sitter package to `pyproject.toml` dependencies.
5. Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py`.
## Search hook scope
The search hook omits project hints when a structured Grep path or every literal
target of a simple grep/rg command resolves outside the project. Mixed targets,
implicit paths, shell composition/expansion, wrappers, unknown options and
unmapped Windows shell drive paths retain the advisory hint. It does not execute
shell input or change search permissions.
## Security
All external input passes through `graphify/security.py` before use:
@@ -134,6 +196,15 @@ ambiguous return references emit no inferred call. Resulting call edges remain
as resolver context. Changes to a producer's return annotation require a full
rebuild to recompute unchanged callers' inferred relationships.
Python direct module-level constructor assignments (`g = Service()`) retain the
class for member-call resolution inside functions, including an imported alias
or a lowercase class rebound to its instance. The constructor must be declared
or imported before the assignment and resolve to a unique visible class by exact
spelling. Local shadowing, other module bindings, conditional assignments and
dynamic namespace mutation leave these calls unresolved. Qualified constructors
and decorated classes are not inferred by this pass. Edges remain `INFERRED`;
AST cache schema 37 retires Python entries without the instance marker.
C# partial types merge across files by their path inside the namespace,
enclosing types first and each with its arity (`` Outer`1.Inner ``), within one
assembly. Nested halves merge only under the same enclosing chain, and `Foo` and
@@ -142,8 +213,47 @@ lack this path. The merge runs after colliding ids are salted apart by path, so
a half whose file stem collides with another file's (`Spec.cs` and `_Spec.cs`,
`Cfg/Helpers.cs` and `Cfg_Helpers.cs`) still merges and keeps its members.
C# constructors (instance, static and a type's primary constructor) are nodes
owned by their type through a `method` edge, labeled `.TypeName()` with
metadata `kind: "constructor"`. The id is the one a method named after the type
would get, `_make_id(type_id, TypeName)`; each further signature is salted like
a method overload, a static constructor is its own `static` signature, and when
a member spelled like the type in another case (`foo()` in `Foo`) already owns
that id, the constructor takes a salted one, so no existing id moves. Calls in
a constructor's body and `: base(...)`/`: this(...)` arguments are its calls.
`new X(...)` keeps its edge to the type and also links the constructor whose
parameter count fits, as do `: base(...)`/`: this(...)`; two fitting overloads,
an unresolved base or an unbound type give no constructor edge. Constructors
stay out of every name-keyed call index. AST cache schema 40 retires C# entries
without them.
C# property and indexer accessor bodies (and expression bodies) are walked
with the member as the caller, and the member counts as owned by its type for
unqualified, `this.`/`base.` and partial-type lookups, like a method. It is never
a call target by name. An indexer is a `this[]` node (`defines`, context
`field`) with id `_make_id(type_id, "this")`, salted per signature and away
from a member spelled `This`. A user-defined operator or conversion is a
`.operator +()` / `.operator int()` node owned through `method`, with id
`_make_id(type_id, "operator", sha1(signature)[:6])`, since several conversions
share one parameter list. Existing ids do not move. AST cache schema 40.
R extraction preserves symbol-only bindings such as `%||%` as separate nodes.
When normal ID normalization removes an entire binding name, its UTF-8 bytes
provide a deterministic operator suffix within the same lexical owner. Its double
underscore separators cannot collide with an ordinary normalized binding ID. Local
call resolution stops if malformed scope metadata cycles.
### Same-ID AST / semantic provenance during extractor upgrades (#4896)
A newly supported AST extractor can mint an ID that is already owned by an
independently evidenced semantic node in a saved graph, even when the two nodes
refer to the same file. Watch reconciliation retains the saved semantic ID and
its rationale/attribution, assigns the fresh AST record a deterministic
ID-derived AST suffix, and rewrites only fresh AST edge/hyperedge
references. This applies to full and incremental re-extractions; incrementally
rebuilt sources are not positive evidence of semantic deletion. The shrink
guard refuses same-ID losses of semantic provenance even when the total node
count grows, preventing the ordinary missing-ID guard from being bypassed.
If multiple new AST records already share that ID, all use one deterministic
AST successor ID: this retains their preexisting AST coalescing behavior while
ensuring they cannot overwrite independent semantic provenance.
+156
View File
@@ -2,6 +2,162 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/Graphify-Labs/graphify/releases)
## 0.9.105 (2026-11-09)
- Fix: **watch** ignored directories (`node_modules`, `.git`, build output) are pruned from the Linux watch tree, so a large project no longer registers tens of thousands of wasted inotify watches and risks `ENOSPC`; the non-Linux recursive watcher is unchanged and still fires on every real change (#5074, #5091, thanks @Deepjyoti-Sarmah).
- Fix: **cpp** a member-call chain routed through class fields declared in other headers (`client.actions->Execute()`, with value `.`, raw-pointer `->` and single-arg `unique_ptr`/`shared_ptr` receivers) resolves to the field type's member across the include set, gated to a unique type and member and fail-closed otherwise; a typed local whose class is in another repo is parked for the cross-repo merge (#5098, thanks @xRedLeader).
- Fix: **markdown** a code span naming an uppercase `\`-namespace class (`\Foo\Bar`, `App\API`) or a type-qualified method call (`Type::member()`) is kept as a symbol mention instead of being dropped, while a non-call `Type::CONST`/`Type::class` stays dropped (#5093, thanks @Adityakk9031).
- Fix: **ts/js** a call through a destructured CommonJS barrel require (`const { Thing } = require('./barrel')` where the barrel re-exports `Thing`) resolves to the real declaration by following the barrel's exports, instead of dropping the edge (#5034, #5104, thanks @qq2514568380).
- Fix: **wiki** the orphan sweep folds slugs with `casefold` (not `lower`), so two article names that collide only under full Unicode case-folding (`Straße`/`STRASSE`, `Σ`/`ς`) each keep their own file instead of one being deleted as an orphan; a file written this run is never swept (#5087, #5102, thanks @nothariharan).
- Fix: **build** hyperedges are kept whole across an incremental `graphify update`: they are read from the nested graph slot a JSON-only writer uses, and after a deleted-source prune a hyperedge drops only its removed members (and itself only when none remain), instead of silently losing or leaving dangling hyperedges (#5081, #5103, thanks @nothariharan).
- Fix: **cache** a degraded (under-producing) semantic cache entry no longer pins the corpus: after the shrink guard sees a re-extraction come back smaller than the stored graph, the entry is stamped `partial` so the next run re-dispatches it instead of replaying the degraded result forever (#5083, #5101, thanks @nothariharan).
- Fix: **affected** `graphify affected <file>` seeds the file's nested member nodes (a method inside a class) transitively, not just one hop, so impact analysis no longer under-reports callers that bind to a nested member (#5094, thanks @Adityakk9031).
- Fix: **tree** `build_tree` derives the common directory root from file parents, so a single-file or single-directory tree is no longer self-nested under the file itself (#5092, thanks @Adityakk9031).
- Fix: **query** a label whose name is behind a schema or namespace qualifier (`public.sweep_widget_state()`, `fmt.Println`) is matched on its tail by the whole query and ranked above the per-token tiers, so it is no longer out-competed by single-token collision nodes and dropped from the seeds (#5080, #5095, thanks @sunhouy).
- Fix: **detect** an incremental staleness check hashes a file whose stamp lands within the clock-skew window on either side of its mtime, so a same-tick rewrite that does not move mtime is still caught instead of being served stale (#5090, thanks @sunhouy).
- Fix: **path** `graphify path A B` refuses an endpoint whose words appear nowhere in the graph (exit not-found) instead of returning a misleading route built from loosely-overlapping tokens (#5085, thanks @sunhouy).
- Fix: **csharp** a classic extension-method call (`x.Foo()` where `Foo` is declared `static ... Foo(this X x, ...)`) binds to the extension method's declaration through an additive pass that runs after nominal dispatch, gated to a visible namespace, a matching `this` type and a unique applicable method; an instance method of the same name wins, a non-extension static or an unimported extension gets no edge, and ambiguity fails closed (#4828, #4849, thanks @Deepjyoti-Sarmah).
- Fix: **markdown** a bare, unqualified free-function mention in prose (`token`, no `()` and no namespace) binds to a same-named function only when its defining file (or another symbol from it) is cited within the heading's section chain, instead of matching any same-named callable in the corpus; reference-style links (`[text][label]`) resolve at the use site (#4804, #4806, thanks @madanlalit).
- Fix: **export** the `to_json` shrink guard no longer counts semantic sources that were replaced on re-extract or pruned as deletions as "lost", so a legitimate `graphify update` is not refused; a genuine unexplained shrink is still refused (#5107, thanks @khkar).
- Fix: **build** a node whose `file_type` or `confidence` arrives as a structured value (list/dict) from a drifting LLM pass no longer crashes the validate/build membership checks: validation surfaces it as a schema error, and the build folds it to `concept`/`INFERRED` without fabricating a score (#5088, thanks @sdivyanshu90).
- Fix: **llm** a splittable document below the character cap whose model output truncates is promoted to a full-range slice and bisected (and retried) instead of being kept as a truncated partial result; a non-splittable or code/binary unit still fails closed (#5072, #5078, thanks @aadilrizwan).
- Feat: **llm** a custom OpenAI-compatible provider's `extra_headers` are forwarded to the client as `default_headers`, scoped to that provider and with any `Authorization` header dropped so it cannot override the configured credential (#3680, #4783, thanks @jaimemartinez).
- Perf: **extract** whole-graph intermediates (the parse memo on the one-shot CLI, build/cluster/export working lists) are freed as soon as they are consumed, cutting peak memory on a large corpus; graph output is byte-identical (#5063, thanks @TPAteeq).
- Fix: **skillgen** the claw/kiro/pi subagent prompt now tells the worker to write its chunk to `CHUNK_PATH`, so a disk-dispatch chunk is no longer returned inline and lost at the merge step (#5040, thanks @connhodendatabase).
- Fix: **deps** the pypdf floor is raised to 6.21.4 in the `pdf` and `all` extras to pick up its security fixes (#5015, thanks @yotamleo).
The AST cache schema is bumped to 42; warm caches re-run the affected C++, Markdown and C# extractions.
## 0.9.104 (2026-11-07)
- Security: **skill** the `/graphify` runbook no longer substitutes the scan path into Python code. Every generated code block (detect, AST and semantic extraction, build, diagnose, label, manifest, and `--update`) now reads the resolved scan root from the trusted `graphify-out/.graphify_root` sidecar that Step 1 writes through a quoted heredoc, instead of pasting the agent-supplied path into a string literal. A directory whose name carried a quote or `$(...)` could previously break out of `Path('INPUT_PATH')` and run as code; it is now read as inert data. Covers the assembled hosts and the Aider/Devin monoliths (#4762, thanks @danikdanik).
- Fix: **solidity** a call on a receiver of a contract or interface type (`IERC20 token; token.transfer()`, `IERC20(a).transfer()`, `token().balanceOf()`) binds by name and arity through that type's linearization to the type's own declaration, instead of producing no edge; gated to a single visible contract/interface and fail-closed on an unknown or ambiguous type (#5060, thanks @rohit-jsfreaky).
- Fix: **solidity** a call attached by a `using A for T` directive (`using SafeCast for uint256; x.toUint48()`) binds to the library or free function it attaches, matched by the receiver's type and an arity one greater than the call; fail-closed when the receiver type is unknown, the library is ambiguous, or two functions fit (#5062, thanks @rohit-jsfreaky).
- Fix: **solidity** members, free functions and types in one scope whose names differ only by a leading `_` or by case (`_grantRole` / `grantRole`) get separate node ids, so the `_` symbol no longer vanishes into its twin and its calls land on the right node (#5027, thanks @rohit-jsfreaky).
- Fix: **csharp** a constructor (instance, static or primary) is its own node owned by its type, with its body and `: base(...)`/`: this(...)` calls credited to it; `new X(...)`, `: base(...)` and `: this(...)` additively link the arity-correct overload, and two fitting overloads or an unresolved base give no constructor edge (#5054, thanks @rohit-jsfreaky).
- Fix: **csharp** calls inside a property or indexer accessor, an expression body, or an operator/conversion body are credited to that member instead of being lost; an indexer becomes a `this[]` node and an operator a `.operator +()` node (#5056, thanks @rohit-jsfreaky).
- Fix: **query** a same-label node that is the only match for a query term is kept as a seed instead of being dropped by the per-label cap, so every distinct term keeps at least one seed while generic-label flooding stays capped (#5027, thanks @Vaibhav2824).
- Fix: **watch** read-only events are kept out of the inotify mask via a change-only `event_filter`, so a large tree no longer drives watchdog into a self-sustaining queue-overflow loop; falls back with a warning on watchdog versions without `event_filter` support (#5033, thanks @Deepjyoti-Sarmah).
- Fix: **cache** the `\\?\` long-path spelling is kept out of cache identity, so the same file reached through `\\?\C:\...` and `C:\...` shares one entry; also fixes empty stat-index writes under UNC shares, a spurious "stat index switched" warning on Windows, and a junction/symlink alias wrongly sharing its target's digest (#5035, thanks @Bortlesboat).
- Fix: **cache** stat-index keys stay root-relative under a Windows long-path root, so a moved or cloned corpus keeps the portable-key fastpath (#5035, thanks @Vaibhav2824).
- Fix: **tests** the TypeScript unicode fixture is written as UTF-8 on every platform, so byte offsets match the extractor on Windows (cp1252) hosts (#5064, thanks @ayushcodes10).
- Fix: **tests** the hook-freshness source mock is normalized through `os_long_path`, so the read-error/stale branch is actually exercised on Windows (#5065, thanks @ayushcodes10).
- Fix: **tests** the watch pending-queue test compares `Path` objects so `/` and `\` separators compare equal on Windows (#5039, thanks @Yi-111-a).
- Fix: **extract** an ambiguous Python import's placeholder node id is hashed from checkout-independent data (module name, scan-root-relative source file, location) instead of the absolute path, so the same project at a different path or a moved cache gets the same ids (#5045, thanks @Fardin7798).
- Fix: **yaml** a template using CloudFormation intrinsic tags (`!Ref`, `!GetAtt`, `!Sub`) no longer fails to parse: a scoped permissive loader rebuilds each `!`-tagged node's shape without evaluating it, while `!!python/...` tags still raise and never execute (#5077, thanks @ayushcodes10).
- Fix: **watch** a `--watch` incremental update rebuilds the full corpus when `graph.json` is missing, instead of writing a partial graph from the manifest alone (#5016, #5021, thanks @azizur100389).
- Fix: **watch** a change to a JS/TS resolution input (`tsconfig.json`, `jsconfig.json`, a lockfile) triggers a full rebuild so importers pick up the new resolution, instead of leaving stale `imports_from` edges (#5017, #5022, thanks @azizur100389).
- Fix: **ingest** two concurrent `graphify add` captures for the same URL no longer clobber each other: the capture file is created exclusively (`O_EXCL`) and a collision retries a fresh name, with the payload fetched once (#5018, #5023, thanks @azizur100389).
- Fix: **reflect** a malformed entry in the learning overlay is skipped instead of crashing the whole load, and a legacy null-source entry is preserved as a source-less annotation (#5019, #5024, thanks @azizur100389).
- Fix: **global** a malformed repo entry in the global manifest is dropped on its own, keeping the other tracked repos, and only a non-object root or repos map is backed up and reset (#5020, #5025, thanks @azizur100389).
- Fix: **query** a graph freshly built on a subfolder is no longer flagged as a pre-#1504 build (which nagged a no-op `extract --force`): the legacy-id probe strips the `.graphify_root` offset before deriving file stems, and a genuine legacy graph is still caught (#2603, #5028, thanks @neumannpeter1231-lang).
- Fix: **tree** `graphify export tree` recognises the `src` node alias (and `file`/`path`/`filepath`) so a graph carrying those keys renders a populated tree instead of an empty one; a concept-only graph still reports empty (#5030, thanks @Adityakk9031).
- Fix: **cli** `graphify provider add` accepts `--pricing-input=VALUE`/`--pricing-output=VALUE` equals-syntax and rejects a non-numeric, non-finite or negative price with a clean error instead of a traceback or a poisoned cost estimate (#5031, thanks @Adityakk9031).
The AST cache schema is bumped to 40; warm caches re-run the affected Solidity and C# extractions. The Python and YAML fixes above need no bump (placeholder ids are resolved after the per-file cache, and previously-failing YAML was never cached).
## 0.9.103 (2026-11-05)
- Fix: **markdown** a code span written as a backslash namespace (`\Foo\Bar`) or a type-qualified member (`Type::member`) is recognised as a symbol mention and resolves to the real node when one exists, instead of being silently dropped; an absent chain mints nothing (#4610, #4695, thanks @viwe-monai).
- Fix: **detect** `extract` warns loudly when a large share of the corpus has no supported extractor (a 20-file floor and a 20% threshold), instead of only printing a bare unclassified count; a normal mixed project stays silent (#2942, #4646, thanks @ayushcodes10).
- Fix: **thread-safety** the ambient scan root is held in a `ContextVar` instead of a module global, so concurrent library/async callers extracting different roots no longer clobber each other's root; the single-threaded CLI is unchanged (#4602, #4694, thanks @WyattAu).
- Feat: **tree** `graphify export tree` caps how many children a directory lists (`--max-children`, default 200) while `total_count` still reports the full count, so a directory with thousands of entries no longer renders them all (#4766, #4768, thanks @oleksii-tumanov).
- Fix: **install** the Pi project skill is written to `.pi/skills`, where Pi reads it, instead of a `.pi/agent/skills` path it never looks at; uninstall is symmetric (#5011, #5012, thanks @Vivek1898).
- Internal: stage fake install bundles in a temp package root and fail loudly (not skip) on a wheel-build error, and serialise both wheel builders under a shared lock so concurrent runs on one checkout do not collide (#4603, #4664, thanks @wanjinhao1); characterize `_is_stale` across changed/unchanged/vanished sources (#4996, thanks @PratikDhanave); isolate the ambient venv/PATH in the `_detect_run` hook test (#4991, thanks @HhH666-ux).
- Fix: **solidity** a library call (`Lib.f()`, including an aliased import) and an `emit`/`revert`/`require` naming a declared event or error now link to the member they name instead of producing no edge; resolution is gated to a single visible type whose unique name/arity member matches, so a builtin `require` or an ambiguous qualifier is left unresolved (#5001, #5005, thanks @rohit-jsfreaky).
- Fix: **csharp** preprocessor directives and `#if` branches that derail tree-sitter are blanked before parsing (byte-length preserving, so line and column numbers do not move), so a directive no longer closes the enclosing class early and orphans later members or drops their calls; the first `#if` branch and distinct framework-fallback branches are kept (#5003, thanks @rohit-jsfreaky).
- Fix: **python** a bare builtin-named call (`raise NotImplementedError(...)`, `list(...)`) no longer binds to a same-named class in another module unless that caller imported the symbol; an imported homonym still resolves (#4989, #4999, thanks @Deepjyoti-Sarmah).
- Fix: **typescript** a type-position `import('mod')` expression (a parameter/alias/`typeof`/generic-constraint annotation) no longer emits a spurious `dynamic_import` runtime edge; a real runtime `import('mod')` in the same file still does (#4992, #4998, thanks @mathewgeejo).
- Fix: **resolution** a call inside a top-level `def _main()` is attributed to `_main`, not the public `main` it collides with after id normalization; the fix matches only the underscore-collision salt, so a class member's type reference is not misattributed to a sibling method (#4994, #4997, thanks @sunhouy).
- Fix: **yaml** a `<<` merge sequence gives the earlier anchor precedence for a duplicated key, matching the YAML merge spec and PyYAML, so the winning key carries its correct source line (#4995, thanks @PratikDhanave).
- Fix: **markdown** a dotted mention whose method name is a language builtin (`Repository.open`) is no longer dropped; only a bare builtin name is skipped, and no spurious mention is minted (#4990, thanks @PratikDhanave).
- Fix: **hooks** a Bash file read (`cat`, `head`, `tail`, `sed -n`, `nl`) of an in-project code file gets the same graph read-nudge a Read tool does (nudge-only, never a strict deny); writes, stdin, heredocs, docs and globs stay silent (#5010, thanks @rohit-jsfreaky).
- Fix: **hooks** the once-per-session nudge budget is restored after a Claude Code compaction (a `SessionStart` with `source=compact`), so orientation can re-fire once the earlier nudges have left the model's context (#5008, thanks @rohit-jsfreaky).
- Fix: **hooks** the toplevel-anchor logic keeps working when `CDPATH` is exported; an exported `CDPATH` was corrupting the relative `.git` capture and silently skipping the post-commit/checkout rebuild (#4977, #4988, thanks @HhH666-ux).
- Perf: **update** the watch reconcile pass resolves AST ownership once per file instead of re-reading each header once per node, with identical graph output (#4978, #4986, thanks @Deepjyoti-Sarmah).
- **AST cache schema bumped to 39** for the C# (#5003), Solidity (#5001, #5005), YAML (#4995) and Markdown (#4695) extractor fixes; warm caches re-run the affected extractions.
## 0.9.102 (2026-11-03)
- Perf: **update** `graphify update` re-extracts only the files whose content changed since the last build (derived from the manifest inside the lock), instead of re-running the whole pipeline over the corpus for a single edit; the resulting graph is identical to a full rebuild, including cross-file edges from unchanged files into a changed one, and deletions (#4740, #4800, #4801, thanks @Deepjyoti-Sarmah).
- Fix: **watch** a contended incremental rebuild request is recorded on its own queue marker instead of being dropped, so a derived-change request that loses the rebuild lock still runs on the next pass (#4800, #4802, thanks @Deepjyoti-Sarmah).
- Fix: **query** source nodes are ranked above tests, docs and config in query results (a soft weight, not exclusion, so a term matched only by a test still seeds it and a question mentioning "tests" restores full weight), and the answer is rendered file-first (#4982, thanks @rohit-jsfreaky).
- Feat: **query** `graphify query` reads project `query_budget` and `query_depth` defaults from `.graphifyrc` (explicit CLI flags still win), and gains a `--depth N` flag; a malformed setting warns and falls back to the built-in defaults (#1654, #4760, thanks @oleksii-tumanov).
- Fix: **install** `graphify uninstall` removes the global `# graphify` skill registration it wrote into `~/.claude/CLAUDE.md`, instead of leaving a dangling pointer to the deleted skill; a hand-written `# graphify` section or another tool's registration is preserved (#4975, thanks @madhusudanpatnaik).
- Fix: **js** a class `extends` through a CommonJS require binding (`const Base = require('./base'); class D extends Base {}`) resolves the `inherits` edge to the required file's class, matching the ESM import path; an external/unresolved require is left alone (#4688, #4700, thanks @Mpasha17).
- Fix: **skill** the `--update` runbook passes `partial_source_files` to the manifest write and clears a stale `.graphify_partial.txt` at the start of the run, so a doc whose chunk was only partly read is re-queued on the next update instead of being stamped done forever (#4807, #4814, #4816, thanks @gitmotion).
- Fix: **skill** Step 4 threads `force=IS_FORCE` into `to_json`, so a `--force` rebuild actually overwrites past the #479 shrink guard the runbook told the user to use `--force` for (#4777, #4805, thanks @pei711).
- Feat: **skill** for a hub/bridge question, the query workflow now tells the agent to grep the corpus for the hub's distinctive literals in edge-less files and report code that reimplements the hub instead of calling it (#4426, #4704, thanks @ayushcodes10).
- Fix: **hooks** a file whose mtime is newer than `graph.json` but whose content is unchanged no longer weakens the strict read gate; the hook checks the file's extraction hash against the build manifest before declaring it stale, so a checkout that writes `graph.json` first does not force a re-read (#4974, thanks @andrebrait).
- Fix: **hooks** a dedicated Grep call is held to the same once-per-session orientation gate as Read in strict mode; a directory Grep needs no index match, a single-file Grep is denied only when the graph indexes it, and external or graph-output targets stay silent without consuming the deny (#4973, thanks @andrebrait).
- Fix: **hooks** a search whose every literal target is outside the project (a Bash `grep`/`rg` on a `/tmp` or sibling path) emits no project hint, so the graph nudge only fires for in-project searches (#4961, #4979, thanks @Shubham-Padkonde).
- Perf: **load** `graph.json` rows are released as the graph is built (and repeated strings interned) so a load no longer holds both the parsed rows and the finished graph at peak, with identical output (#4960, thanks @ajbmachon).
- Perf: **resolve** symbol resolution holds one parsed file at a time instead of retaining every parsed file across the JS and Python passes, collapsing them into a single per-file loop with unchanged edges (#4958, thanks @ajbmachon).
- Perf: **extract** edge-dedup keys and per-file rows are released once consumed, cutting peak retention during extraction with identical output (#4959, thanks @ajbmachon).
- Fix: **typescript** a typed tagged template (`` sql<{...}[]>`...` ``) and an import-qualified generic annotation (`import("mod").T<X>`) no longer leave the file half-parsed; the recovery runs only on files that already fail to parse, so a type-only `import("mod").T` stops minting a bogus module node and a false `dynamic_import` edge (#4976, thanks @briascoi).
- Fix: **go** a same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method; a bare package-function call no longer binds to a same-named method, and a package-level `var` fallback only applies to a genuinely unbound receiver (#4962, #4966, thanks @xiongjianxu).
- Fix: **go** a member call on a receiver typed from another package (`pkg.T`, the usual shape of a dependency injected across packages) binds only to the `T` declared at the path the file imports `pkg` from, so two packages that both declare `T` are disambiguated by import evidence; an out-of-corpus qualifier stays unresolved (#3368, #4853, thanks @nothariharan).
- Feat: **go** an interface method call additively dispatches to the interface's implicit implementers (method-set superset match, unexported methods scoped to the same directory, capped at 10 implementers and skipped past that), surfacing the concrete methods a call can reach while keeping the edge to the interface (#4934, thanks @nothariharan).
- Fix: **kotlin** a call to an overloaded method resolves (Java gives every overload one node id, which the resolver mis-counted as ambiguous), calls inside an `init {}` block are attributed to the class, and a bare call no longer binds to a class the caller cannot reach through its type chain (#4935, #4956, thanks @Deepjyoti-Sarmah).
- Fix: **python** a module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard so rebinding, local shadowing or an ambiguous constructor leaves it unresolved (#4970, #4972, thanks @Shubham-Padkonde).
- Fix: **js** a call through a default-exported object's method (`import m from './x'; m.foo()`) resolves to the static method, bound only on a single unambiguous target and suppressed by local shadowing, getters, spread or computed keys (#4963, #4967, thanks @xiongjianxu).
- Fix: **solidity** an `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling id that kept the importer's own folder (#4984, #4985, thanks @rohit-jsfreaky).
- Fix: **build** the write guard no longer counts an intentional ghost fold (a #1145 same-file twin, #3344 doc-names-a-file, or #3705 method ghost folded into its surviving twin) as a dropped node on the `build_merge` path; a genuine drop whose survivor is also gone is still refused (#4955, #4957, thanks @Deepjyoti-Sarmah).
- Fix: **extract** paths skipped by ignore rules are reported in the extract summary (bounded, sorted, root-relative, with a VCS-aware hint), surfacing the already-collected ignore list without changing the graph (#4965, #4969, thanks @xiongjianxu).
- Perf: **resolution** the #3252 cross-file repoint indexes edges by source file instead of scanning every corpus edge per importing file, cutting resolution time on large graphs with no change to the resulting edges (#4980, #4981, thanks @jinsoo).
- Fix: **python** a bare builtin name (`NotImplementedError`, `TimeoutError`, `ConnectionError`, …) no longer links to a package class of the same name when the calling module never imports it; the edge is kept (and stays EXTRACTED) only when the caller imports that exact symbol, so a module-level import of some other name from the same file can no longer certify it (#4989).
- **AST cache schema bumped to 37** for the Go (#4966, #4853, #4934), Kotlin (#4956), Python (#4972) and Solidity (#4985) extractor fixes; warm caches re-run the affected extractions.
## 0.9.101 (2026-11-02)
- Fix: **watch** AST-only updates preserve cross-file semantic evidence whose node id collides with a code definition. Semantic nodes and their document-owned links use the existing citing-file namespace, keeping both the code definition and semantic provenance in `graph.json`, including with `--no-cluster`. Fresh AST facts remain authoritative for same-source ids; full-build deduplication is unchanged.
- Fix: **python** a bare call inside a method (`do_thing()`) no longer wrongly self-binds to a same-named method on the class; it resolves to the imported or module-level function it actually names, and a bare call with no such target emits no edge (#4933, thanks @nothariharan).
- Fix: **python** imports resolve across PEP 420 namespace packages split over multiple `src/` roots (no `__init__.py`), while a module ambiguously provided by two roots stays unresolved and loose/stdlib-named modules are left alone (#4929, thanks @nothariharan).
- Fix: **go** a method value reached through a receiver field (`m.UseMiddleware(hs.handler.Middleware)`) is linked as an `indirect_call`, extending the method-value-as-argument handling to field chains rooted at the method's own receiver (#1566, #4931, thanks @nothariharan).
- Fix: **go** a package-level `var` initialiser references the types it names (`var s = wire.NewSet(new(T), ...)`, composite literals, `new(T)`), the type-reference complement to crediting its calls to the file, so a wire-set file no longer extracts as no symbols (#2360, #4932, thanks @nothariharan).
- Fix: **rust** a module-qualified call (`crate::b::helper()`, `super::m::f()`) resolves to the function it names through qualifier-verified cross-file resolution, the dominant idiomatic call form that previously produced no edge; the resolver keeps the call inside the caller's crate and will not bind to a local name, preserving the historical false-positive guards (#2135, #4944, thanks @nothariharan).
- Fix: **rust** a call written inside an expression macro's arguments (`println!("{}", f())`, `vec![g()]`) is linked instead of being lost, gated to an allowlist of expression macros so `macro_rules!` bodies and custom DSLs are left alone, and a normally parsed call still wins the dedupe (#4945, thanks @nothariharan).
- Fix: **llm** a sliced file is cached only once every slice has succeeded, and a held sliced file is assembled in chunk order rather than completion order, so a partial failure no longer leaves a truncated or out-of-order file in the semantic cache; failed slices are stamped for retry (#4943, #4947, thanks @nothariharan).
- Fix: **rebuild** a graph built with `--code-only` stays code-only across hook, `update` and watch rebuilds; the scope is recorded in `.graphify_build.json`, honoured by the rebuild path and the no-change skip key, and a later flagless extract that actually ingests docs clears the scope (#4923, #4939, thanks @Deepjyoti-Sarmah).
- Fix: **watch** a rebuild no longer waits forever when `msvcrt.locking` is unsupported on the filesystem; an unexpected errno is treated as lock-unsupported and the rebuild proceeds unlocked with a warning, matching the existing no-`fcntl`/no-`msvcrt` fallback, while genuine contention still retries (#4924, #4926, thanks @AndresDiagoM).
- Fix: **watch** a full reconcile evicts source records for a linked git worktree that the current ignore rules exclude, including sources owned only through an edge or hyperedge, so a worktree copy's nodes no longer linger after it is excluded; an intentionally scanned linked root and live unexplained sources are preserved (#4919, thanks @azizur100389).
- Fix: **cache** cache keys keep their written case so `README.md` and `readme.md` no longer collide on a case-sensitive filesystem, and hashed and word-count files are opened through `os_long_path` so a path folded by `normcase` can no longer raise `IsADirectoryError`; the digest salt is no longer lowercased, which also closes a latent same-digest collision on POSIX (#4925, #4937, thanks @Deepjyoti-Sarmah).
- Fix: **build** the write guard no longer refuses a healthy graph when entity dedup folds a saved node into a surviving twin; the dedup merge map is carried on the built graph and threaded into both the missing-node check and the net-count check, which now counts N saved ids folded into one survivor as the expected N-1 shrink, while a genuine loss (survivor also absent) is still refused (#4940, #4952, thanks @Deepjyoti-Sarmah).
- Fix: **build** independently sourced semantic file evidence survives a fold into an AST file-self node; a mention carrying its own provenance (`rationale`, `source_url`, `author`, `contributor`) is kept distinct instead of collapsing by label alone, so two docs describing the same file no longer lose one explanation. Ordinary `INFERRED` mention ghosts with only `metadata`/`captured_at` still fold, so graphs do not accumulate duplicates (#4896, #4927, thanks @Ethan-Ethan-Ethan).
- Fix: **build** the file-stem alias index only rebinds an edge onto a migrated node when the edge's file and the alias target share a language family, so a reference in one language (for example Dart) no longer binds onto an unrelated same-stemmed file in another (for example Java); same-language and provenance-less aliases resolve exactly as before (#4949, thanks @ayushcodes10).
- Fix: **cpp** a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling, so it no longer loses to a same-normalized function of the same name, and a salted alias node keeps its own `contains` edge (#4951, thanks @madhusudanpatnaik).
- Fix: **cpp** a member call `x.m()` binds by the receiver's type, now typed from function parameters and class fields and not only local variables (`void render(Base* b){ b->draw(); }` resolves to `Base::draw`), the dominant idiom of passing state by reference; an untyped or ambiguous receiver keeps its in-file binding rather than guessing (#3215, #4946, thanks @nothariharan).
- Fix: **cpp** an out-of-line or split-header definition attaches to the unique owner whose class file is in its include set, carried by a `_cpp_qualified` identity marker, instead of being file-contained or cross-binding to an unrelated same-named function in another file; an ambiguous or namespace-colliding owner fails closed with no edge (#4916, #4920, thanks @azizur100389).
- Fix: **cpp** a local callable value (a lambda or `std::function` assigned to a variable) is kept out of global call resolution by byte-range binding lifetimes, so it no longer mints a spurious `INFERRED` call to a same-named global; a later legitimate call to a real global of that name in the same function is preserved (#4917, #4921, thanks @azizur100389).
- Internal: cover deletion-only semantic manifest preservation so an undispatched semantic stamp survives a deletion-only or failed incremental change (#4922, thanks @azizur100389).
- **AST cache schema bumped to 36** for the Rust call-resolution fixes (#4944, #4945), the case-preserving cache keys (#4937), and the C++ extractor fixes (#4951, #4946, #4920, #4921); warm caches re-run the affected extractions.
## 0.9.100 (2026-11-01)
- Fix: **ids** a type and a function whose names differ only in case (`Foo` the class, `foo` the function) get distinct node ids instead of colliding (which dropped one node and minted a bogus self-loop) (#4904, #4908, thanks @bercedev).
- Fix: **php** a `Scope::MEMBER` access in a class-level initializer (a const value, a property default, or a parameter/promoted-constructor default) emits a `references_constant` edge; `self::`/`static::`/`parent::` are skipped and unknown scopes mint no stub (#4648, #4895, thanks @Jitendarmahara).
- Fix: **hooks** `git rev-parse` output is decoded as UTF-8, so a linked worktree under a non-ASCII path resolves correctly on Windows instead of mojibake (#4903, thanks @LukeTheoJohnson).
- Fix: **analyze** on a code-only graph the isolated-node question reason says "possible missing edges" rather than referencing documentation gaps that cannot apply (#4887, thanks @oleksii-tumanov).
- Perf: **resolve** reference edges are indexed by source once, so JS/TS import resolution no longer re-walks every edge per import (output unchanged) (#4909, #4913, thanks @Deepjyoti-Sarmah).
- Docs: **skill** the skill now says when a graph is worth building, across all generated hosts, while preserving the "if the user invoked /graphify, do it as asked" invariant (#4829, #4906, thanks @TanmayShah29).
- Fix: **deps** the `video` extra caps PyAV below 19 (`av>=11,<19`), because PyAV 19 removed the `metadata_errors` argument that faster-whisper passes unconditionally when opening audio; without the cap a fresh install on Python 3.12+ failed to transcribe (#4842, thanks @SyedFahad7).
- Fix: **r** `setClass`/`setRefClass` S4/R5 inheritance declared with `contains=` now emits an inherits edge (previously only R6Class's `inherit=` was recognised) (#4902, thanks @ayushcodes10).
- Fix: **elixir** a bare function call resolves to a function in the caller's own module before other modules, instead of binding to the last-walked same-named definition (#4900, thanks @ayushcodes10).
- Fix: **dart** a mixin `on A, B` clause resolves every superclass constraint, not just the first (#4899, thanks @ayushcodes10).
- Fix: **fortran** a derived type's `extends(base)` emits an inherits edge, bringing Fortran in line with the other OOP extractors (#4897, thanks @ayushcodes10).
- Fix: **scala** an `extension (x: T) def m` is scoped to its receiver type `T` (a `method` edge to `T`) instead of leaking to file scope (#2044, #4856, thanks @divakantpandey).
- Fix: **terraform** a node carries its original scope so ids stay stable when a cached project directory is moved, instead of re-deriving the scope from the new path (#4858, #4861, thanks @yUm1k4).
- Fix: **extract (JVM)** Java and Kotlin imports, `extends`/`implements` and member calls resolve across files and across the two languages when a written FQN names exactly one sourced type (#4874, #4879, thanks @Deepjyoti-Sarmah).
- Fix: **export** a path/explain/wiki rendering lists every parallel relation between two nodes (via `edge_datas`), and a raw `--no-cluster` write marks the graph `multigraph` so parallel edges survive reload (#4794, thanks @ensell-yes).
- Fix: **export** a partial or failed backup is reported as no backup and retried on the next run, instead of being recorded as a false success (#3769, #4834, thanks @barlowa124).
- Fix: **affected** `graphify affected` (and `query --seed`) resolve the same `path::Symbol` and dotted reference forms `explain` accepts, reusing explain's resolver, and exit non-zero (3 ambiguous / 4 not-found) on a seed that does not resolve (#4792, #4797, thanks @dupeisen).
- Fix: **install** `graphify uninstall` removes every platform's user-scope skill (13 were left behind) and the kilo global command; and `graphify kilo uninstall` removes the kilo skill's `references/` sidecar (#4782, #4789, thanks @bercedev).
- Feat: **llm** the Claude backend caches its (stable, large) system prompt with `cache_control`, counting the cached tokens back into `input_tokens`, and `GRAPHIFY_CLAUDE_PROMPT_CACHE=0` disables it for gateways that reject `cache_control` (#4835, #4855, #4880, thanks @Jvxoq and @1akashkalita).
- Fix: **prompt** the node-id format description in the extraction prompt matches what `ids.py` actually produces (word characters kept, non-ASCII letters/digits preserved, ASCII lowercased) instead of the stale "`[a-z0-9_]` only" wording (#4432, #4799, thanks @dupeisen).
- Docs: **how-it-works** the supported-language count is updated (about 40: 33 tree-sitter grammars plus 7 built-in parsers) and Pass 3 is described as running the configured LLM backend, not Claude only (#4873, thanks @SyedFahad7).
## 0.9.99 (2026-10-30)
- Feat: **path** when several routes tie on length, `graphify path` and the MCP `shortest_path` tool report the most conservative one: among all shortest paths, the route whose weakest hop is weakest is chosen, and the summary notes it was the weakest of N equal-length routes. Previously an arbitrary equal-length route was returned, so the confidence could overstate how sure the connection is. This is the second half of #4881 (the first half, keeping a collapsed edge's weaker evidence in `also_seen`, shipped in 0.9.98 via #4891, thanks @SyedFahad7).
+25 -2
View File
@@ -253,7 +253,9 @@ Codex users also need `multi_agent = true` under `[features]` in `~/.codex/confi
`--platform agents` (alias `--platform skills`) targets the generic cross-framework [Agent-Skills](https://github.com/anthropics/skills) locations: the spec's user-global `~/.agents/skills/` (read by `npx skills` and spec-compliant frameworks) for a global install, and `./.agents/skills/` for a project (`--project`) install. The bare `graphify install` stays single-platform (Claude Code) by design: use the named `agents` platform when you want the skill discoverable by any framework that reads `.agents/skills`.
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session indexed-read denial come from that same policy, so Pi matches Claude Code's hook behavior; guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
Claude Code's `graphify install --project --strict` makes Read and dedicated Grep share one denial per session unless a recent graph query has oriented the agent (default 30 minutes). A Grep over a directory needs no indexed-file match; a Grep pinned to a single file is denied only when the graph indexes that file, as with Read. External and graph-output Grep targets produce neither a deny nor a nudge, in soft mode as well as strict mode, matching Read's scope. A graph marked `needs_update` never triggers a Grep denial. Bash searches and Glob stay advisory. `GRAPHIFY_HOOK_STRICT=1` enables the policy without reinstalling; `GRAPHIFY_HOOK_STRICT=0` disables it even when installed with `--strict`. Existing strict installs need a reinstall to add the search hook's `--strict` flag, or the environment override. Soft nudges are capped per session (`GRAPHIFY_HOOK_NUDGE_CAP`, default 5). After a context compaction, a `SessionStart` hook (matcher `compact`) resets that budget, the subagents' budgets and the strict denial, since the compacted context no longer holds the earlier nudges.
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session denial shared by indexed Read and dedicated Grep come from that same policy, so Pi matches Claude Code's hook behavior; Bash and file listing remain advisory. Guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
> Codex uses `$graphify` instead of `/graphify`.
@@ -303,7 +305,7 @@ Run `graphify <platform> install` once in your project, for example `graphify cl
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions, preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files.
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path.
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools, or via `cat`, `head`, `tail`, `sed -n` and similar readers in Bash) and nudges your assistant toward the graph path.
- **Instruction-file platforms** (Codex, OpenCode, Cursor, etc.): persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance.
`GRAPH_REPORT.md` is still available for broad architecture review.
@@ -385,6 +387,12 @@ See the [full command reference](#full-command-reference) below.
graphify honors `.gitignore` and supports `--exclude` patterns and a project `.graphifyignore`. Details: **[Configuration](https://docs.graphify.com/reference/configuration)**.
`graphify extract` reports paths skipped by ignore rules, with up to three sorted examples relative to
the scan root. Each pruned directory counts once; its contents are not enumerated. Default noise
directories such as `node_modules` are excluded from this summary. If source is missing, review the
ignore rules. `--no-gitignore` bypasses VCS ignore rules only; `.graphifyignore` and `--exclude`
remain effective.
## Project configuration
@@ -404,6 +412,20 @@ viz_node_limit=0
The declaration flows through classification, extractor selection, grammar and resolution, imports, `graphify watch`, and the AST cache (a file re-parsed under a different language never reuses the old entry), and the same `.graphifyrc` is read by `extract`, `update`, the hooks, the MCP server, and the `/graphify` skill. A typo is reported once on stderr and the scan continues with the defaults. How declarations interact with caching, incremental rebuilds, and import resolution: **[Configuration](https://docs.graphify.com/reference/configuration)**.
**Query defaults.** Set `query_budget` to a positive integer and `query_depth` to an integer from 1 to 6:
```ini
query_budget=4000
query_depth=3
```
For `graphify query`, explicit `--budget N` / `--budget=N` and `--depth N` / `--depth=N` override these settings independently. Without a project setting or explicit option, the defaults remain budget 2000 and depth 2. These keys do not change the MCP server's defaults.
Settings come from the project owning the selected `--graph`, even when the command runs from another directory. An existing absolute directory in the graph's sibling `.graphify_root` marker identifies that project. Otherwise a matching relative `GRAPHIFY_OUT` suffix identifies it; absolute, empty, traversal-containing or nonmatching output paths fall back to the graph file's directory. Relative markers are ignored.
The query command always reads that project's `.graphifyrc`. An invalid recognized setting or an unreadable file produces one stderr warning and discards all project settings for that query; explicit options still apply. The settings parser stays strict for its other callers. Existing explicit budget values retain their behavior; persisted `query_budget` values must be positive.
---
## Team setup
@@ -422,6 +444,7 @@ Beyond your AI assistant, query `graph.json` straight from the CLI with `graphif
Backends, API keys, hook behavior, and tuning are controlled by environment variables. Full table: **[Configuration](https://docs.graphify.com/reference/configuration)**.
- **Claude API prompt caching**: `GRAPHIFY_CLAUDE_PROMPT_CACHE` controls system-prompt caching for `--backend claude`. Unset or blank keeps caching enabled; `1`, `true`, `yes`, or `on` explicitly enables it, and `0`, `false`, `no`, or `off` disables it (case-insensitive, surrounding whitespace ignored). Invalid values raise an error before sending a request. For example, run `GRAPHIFY_CLAUDE_PROMPT_CACHE=0 graphify extract . --backend claude` when an Anthropic-compatible endpoint rejects `cache_control`. Disabling sends the original plain-text system prompt. The setting applies equally to official Anthropic and custom `ANTHROPIC_BASE_URL` / `ANTHROPIC_MODEL` endpoints, including deep mode; it does not affect Bedrock, Claude CLI, or Graphify's local extraction cache. Enabling requests caching but cannot guarantee cache hits: the endpoint/model must support it and the prompt must meet its minimum length. Unsupported caching errors are not silently retried without caching.
- **Claude CLI model**: `GRAPHIFY_CLAUDE_CLI_MODEL` overrides the model for the `claude-cli` backend (default: Opus). `haiku` or `sonnet` are usually enough for community naming; the semantic extraction pass benefits from a larger model.
---
+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. |
+6 -6
View File
@@ -5,15 +5,15 @@
graphify processes your files in three passes:
**Pass 1 — Code structure (free, no API calls)**
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. 25 languages supported. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. About 40 languages are supported: 33 are parsed with tree-sitter grammars and 7 (Dart, Apex, COBOL, Razor, Blade, Pascal and Robot Framework) use built-in parsers. A few languages need an optional extra, e.g. `pip install "graphifyy[sql]"`; graphify tells you which extra to install if one is missing. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
Code files are not sent to the LLM semantic extractor in the normal pipeline. If a corpus contains only code files, Pass 3 is skipped entirely; semantic extraction is reserved for docs, papers, images, and transcripts.
**Pass 2 — Video and audio (local, no API calls)**
Video and audio files are transcribed with faster-whisper. To focus the transcript on your domain, the transcription prompt is seeded with your top god nodes (the most-connected concepts in your code graph so far). Transcripts are cached — re-runs skip already-processed files.
**Pass 3 — Docs, papers, images (Claude subagents, costs tokens)**
Claude runs in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
**Pass 3 — Docs, papers, images (LLM subagents, costs tokens)**
Your assistant's subagents (or, with `graphify extract --backend`, a model such as Gemini, Kimi, OpenAI, DeepSeek or a local Ollama model) run in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
Before Pass 3, optional converters turn supported pointer/binary formats into
Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
@@ -27,7 +27,7 @@ Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
Communities are found using the [Leiden algorithm](https://www.nature.com/articles/s41598-019-41695-z) — a graph-clustering method that groups nodes by edge density. Nodes with many connections between them end up in the same community.
**No embeddings needed.** The semantic similarity edges that Claude extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
**No embeddings needed.** The semantic similarity edges that the model extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
---
@@ -38,7 +38,7 @@ Every relationship is tagged with one of three labels:
| Tag | Meaning |
|-----|---------|
| `EXTRACTED` | Found directly in the source (e.g. a function call, an import) |
| `INFERRED` | A reasonable inference Claude made, with a `confidence_score` (0.0–1.0) |
| `INFERRED` | A reasonable inference the model made, with a `confidence_score` (0.0–1.0) |
| `AMBIGUOUS` | Uncertain — flagged in the report for manual review |
EXTRACTED edges always have confidence 1.0. INFERRED edges use a discrete rubric:
@@ -70,7 +70,7 @@ Each `worked/` folder in the repo has the raw input files and actual output (`GR
## Parallel extraction
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel Claude subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel LLM subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
---
+6 -1
View File
@@ -933,7 +933,10 @@ def _run_cli() -> None:
print(" --context C explicit edge-context filter (repeatable)")
print(" --seed X start at node X (id, label or file path; repeatable)")
print(" instead of the question's keyword matches")
print(" --budget N cap output at N tokens (default 2000)")
print(" --budget N, --budget=N cap output at N tokens (default 2000)")
print(" --depth N, --depth=N traversal depth 1-6 (default 2)")
print(" absent options use the selected graph project's .graphifyrc")
print(" query_budget / query_depth. Explicit options override project values.")
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
print(" query, path and explain exit 0 with an answer, 3 when a name is ambiguous")
print(" (the candidates are listed), 4 when no node matches")
@@ -979,6 +982,8 @@ def _run_cli() -> None:
print(" and OPENAI_MODEL to the model name your server serves")
print(" claude also reaches custom Anthropic-compatible endpoints (LiteLLM")
print(" proxy, gateways): set ANTHROPIC_BASE_URL and ANTHROPIC_MODEL")
print(" GRAPHIFY_CLAUDE_PROMPT_CACHE=0 disables Claude system-prompt caching")
print(" (default: enabled; set 1 to explicitly enable)")
print(" --model M override backend default model")
print(" --mode deep aggressive INFERRED-edge semantic extraction")
print(" --force full re-scan and re-dispatch: skip the incremental")
+80 -19
View File
@@ -171,6 +171,36 @@ def _prefer_file_node(
return None
def resolve_reference_forms(graph: nx.Graph, query: str) -> str | None:
"""Resolve the reference forms `explain` accepts but `resolve_seed` did not.
`explain` resolves a `path::Symbol` reference (#3485) and a dotted Python
name (`pkg.mod.func` / `pkg.mod:func`, #4366) to a single node; `affected` and
`query --seed` rejected both with "No unique node match" even when `explain`
resolved the very same string. Following the README's own advice ("use the
precise ID returned by the graph") therefore forced a caller through
`explain` first just to obtain an id (#4792).
Only the two path-qualified forms are handled here — they carry their own
disambiguating context, so a match is never a guess. A bare name keeps going
through `resolve_seed`'s existing tiers, where an exact-name tie must stay
unresolved rather than be broken by graph-iteration order.
Returns the unique node id, or None to fall through to the ordinary tiers.
"""
from graphify.serve import _find_node_tiers
source_exact, exact, _prefix, _substring = _find_node_tiers(graph, query)
for tier in (source_exact, exact):
if len(tier) == 1:
return str(tier[0])
if tier:
# Several nodes in the winning tier is ambiguity, not precedence;
# do not fall back to a looser tier and pick one arbitrarily.
break
return None
def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str | None:
# A trailing path separator must not change a source-file match — serve's
# _find_node tokenizes the path (which drops it), so strip it here for parity
@@ -178,6 +208,11 @@ def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str |
query = query.rstrip("/\\") or query
if query in graph:
return query
# `path::Symbol` and dotted Python names resolve exactly as `explain` does
# (#4792); checked before the label tiers, which cannot express them.
qualified = resolve_reference_forms(graph, query)
if qualified is not None:
return qualified
query_lower = _normalize_label(query)
exact_label_matches = [
str(node_id)
@@ -283,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
@@ -353,6 +392,27 @@ def affected_nodes(
return hits
def resolve_seed_outcome(
graph: nx.Graph, query: str, root: Path | None = None
) -> tuple[str | None, list[str]]:
"""Resolve a seed and report why it failed, so the CLI can set an exit code.
`affected` printed "No unique node match" and still exited 0, so a script
could not branch on the outcome the README documents (3 = ambiguous,
4 = no match) while `explain` already follows it (#4792). Returns
``(node_id, [])`` on success, ``(None, rivals)`` when the query is the
ambiguous name of several nodes, and ``(None, [])`` when nothing matched.
"""
seed = resolve_seed(graph, query, root)
if seed is not None:
return seed, []
from graphify.serve import find_node_ambiguity
normalized = query.rstrip("/\\") or query
rivals = find_node_ambiguity(graph, normalized)
return None, [str(node_id) for node_id in rivals]
def format_affected(
graph: nx.Graph,
query: str,
@@ -360,9 +420,11 @@ def format_affected(
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
depth: int = 2,
root: Path | None = None,
seed: str | None = None,
) -> str:
relation_list = tuple(relations)
seed = resolve_seed(graph, query, root)
if seed is None:
seed = resolve_seed(graph, query, root)
if seed is None:
return f"No unique node match for {query}"
@@ -395,7 +457,8 @@ def load_graph(path: Path) -> nx.Graph:
from networkx.readwrite import json_graph
try:
raw = json.loads(path.read_text(encoding="utf-8"))
from graphify.paths import consumed, read_graph_json
raw = read_graph_json(path)
except (json.JSONDecodeError, OSError) as exc:
raise RuntimeError(
f"Cannot read graph file {path}: {exc}. "
@@ -410,7 +473,5 @@ def load_graph(path: Path) -> nx.Graph:
# (__main__.py) already normalizes this (#738; same class as #1198).
if "links" not in raw and "edges" in raw:
raw = dict(raw, links=raw["edges"])
try:
return json_graph.node_link_graph(raw, edges="links")
except TypeError:
return json_graph.node_link_graph(raw)
raw = dict(raw, nodes=consumed(raw["nodes"]), links=consumed(raw["links"]))
return json_graph.node_link_graph(raw, edges="links")
+26 -14
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
from pathlib import Path
import networkx as nx
from graphify.build import edge_data
from graphify.build import edge_datas
# Builtin/mock names that can appear as annotation-derived nodes in pre-existing
# graphs. Excluded from god-node ranking so they don't displace real abstractions
@@ -410,18 +410,22 @@ def _cross_community_surprises(
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
result = []
for (u, v), score in top_edges:
data = edge_data(G, u, v)
result.append({
"source": G.nodes[u].get("label", u),
"target": G.nodes[v].get("label", v),
"source_files": [
G.nodes[u].get("source_file", ""),
G.nodes[v].get("source_file", ""),
],
"confidence": data.get("confidence", "EXTRACTED"),
"relation": data.get("relation", ""),
"note": f"Bridges graph structure (betweenness={score:.3f})",
})
for data in edge_datas(G, u, v):
result.append({
"source": G.nodes[u].get("label", u),
"target": G.nodes[v].get("label", v),
"source_files": [
G.nodes[u].get("source_file", ""),
G.nodes[v].get("source_file", ""),
],
"confidence": data.get("confidence", "EXTRACTED"),
"relation": data.get("relation", ""),
"note": f"Bridges graph structure (betweenness={score:.3f})",
})
if len(result) >= top_n:
break
if len(result) >= top_n:
break
return result
# Build node → community map
@@ -579,11 +583,19 @@ def suggest_questions(
and G.nodes[n].get("file_type") != "rationale"
]
if isolated:
has_semantic_layer = any(
G.nodes[n].get("file_type") in ("document", "paper", "image")
for n in G.nodes()
)
reason = (
"possible documentation gaps or missing edges" if has_semantic_layer
else "possible missing edges"
)
labels = [G.nodes[n].get("label", n) for n in isolated[:3]]
questions.append({
"type": "isolated_nodes",
"question": f"What connects {', '.join(f'`{l}`' for l in labels)} to the rest of the system?",
"why": f"{len(isolated)} weakly-connected nodes found - possible documentation gaps or missing edges.",
"why": f"{len(isolated)} weakly-connected nodes found - {reason}.",
})
# 5. Low-cohesion communities → structural questions
+310 -24
View File
@@ -71,6 +71,7 @@ def _lost_saved_semantic_nodes(
new_nodes: list,
deleted_sources: set[str] | None = None,
folded: dict[str, str] | None = None,
dedup_remap: dict[str, str] | None = None,
) -> list[dict]:
"""Saved semantic nodes whose ids are absent from the new graph.
@@ -85,6 +86,11 @@ def _lost_saved_semantic_nodes(
``folded`` (when given) maps each saved node id that build_from_json merged
into an AST twin to that twin's id, so a caller comparing node counts can
discount it.
``dedup_remap`` is the ``{merged-away id: survivor id}`` map entity dedup
produced this run (#4940). A saved id it folded into a survivor that is in
the new graph is one node, not a lost one. A survivor that is itself gone
excuses nothing: the content went with it.
"""
deleted = {
norm
@@ -145,19 +151,56 @@ def _lost_saved_semantic_nodes(
continue
if isinstance(node_id, str) and _renamed_present(node_id):
continue
if dedup_remap:
survivor = dedup_remap.get(node_id)
if isinstance(survivor, str) and _renamed_present(survivor):
continue
sf_val = node.get("source_file")
source = _norm_source_file(sf_val) if isinstance(sf_val, str) else None
lbl = str(node.get("label", "")).strip()
if source and lbl:
loc_key = (source, lbl)
if loc_key in new_ast_loc_nodes and loc_key not in ast_loc_collisions:
if (
not _has_independent_semantic_evidence(node)
and loc_key in new_ast_loc_nodes
and loc_key not in ast_loc_collisions
):
if folded is not None:
folded[str(node_id)] = new_ast_loc_nodes[loc_key]
continue
# A document that names a file stamps the file's name as label but its
# own path as source_file; Pass 2b folds it into the one AST file node
# that label names. Two or more matches stay unmerged there.
file_twins = [nid for nid, sf in new_ast_file_nodes if _is_file_node_label(lbl, sf)] if lbl else []
# Full-code rebuilds can relabel an AST file node with a path-qualified
# suffix when several files share a basename. The exact (source_file,
# label) key then disappears even though Pass 2 legitimately folded
# an evidence-free same-source file mention. Match by exact source
# identity, not bare filename, to avoid either silent data loss or a
# spurious fail-closed refusal on an unrelated identically named file.
if source and lbl and not _has_independent_semantic_evidence(node):
same_source_twins = {
nid for nid, sf in new_ast_file_nodes
if _norm_source_file(sf) == source
and _is_file_node_label(lbl, sf)
}
if len(same_source_twins) == 1:
if folded is not None:
folded[str(node_id)] = next(iter(same_source_twins))
continue
# Only a mention of SOME OTHER file is eligible for label-only
# folding. If the semantic node's label names its OWN source file,
# it is a file-self record; it must not fold into a different source's
# AST file just because the basename happens to match.
# Only an evidence-free mention is eligible for Pass 2b's label-only
# fold. Rich semantic records from unrelated source files are distinct
# provenance, even if their label happens to be a real file name.
# Mirror build_from_json exactly; otherwise the shrink guard would
# silently exempt a lost record that the builder no longer folds.
file_twins = (
[nid for nid, sf in new_ast_file_nodes if _is_file_node_label(lbl, sf)]
if (
lbl
and not _has_independent_semantic_evidence(node)
and not _is_file_node_label(lbl, source)
) else []
)
if len(file_twins) == 1:
if folded is not None:
folded[str(node_id)] = file_twins[0]
@@ -168,6 +211,24 @@ def _lost_saved_semantic_nodes(
return lost
def _dedup_shrink_allowance(saved_ids: set, new_ids: set, dedup_remap: dict[str, str]) -> int:
"""How many fewer nodes the graph may have because dedup merged saved ids (#4940).
Merging N saved ids into one survivor removes N - 1 nodes when the survivor
is new this run, and N when it is itself a saved id (that one stays in the
count of the old graph). Only merges whose survivor is in the new graph
count: a missing survivor is a loss, not a merge.
"""
losers_by_survivor: dict[str, int] = {}
for loser, survivor in dedup_remap.items():
if loser in saved_ids and survivor in new_ids:
losers_by_survivor[survivor] = losers_by_survivor.get(survivor, 0) + 1
return sum(
count if survivor in saved_ids else count - 1
for survivor, count in losers_by_survivor.items()
)
# Relations that say only "these two symbols appear together", with no claim about
# HOW. An extractor that finds a specific fact for a pair — a call, an import, an
# inheritance — routinely emits one of these for the same pair as well, so when the
@@ -381,14 +442,22 @@ def finalize_raw_graph_endpoints(data: dict) -> None:
_fold_edge_aliases(edge)
declared = {n.get("id") for n in nodes if isinstance(n, dict)}
norm_to_id = {_normalize_id(nid): nid for nid in declared if isinstance(nid, str)}
node_by_id = {
n.get("id"): n for n in nodes
if isinstance(n, dict) and isinstance(n.get("id"), str)
}
# Alias index (#4670): the same old-stem spellings build_from_json resolves
# against, so an endpoint written in a pre-migration spelling still lands on
# the node it names. Only fills gaps ΓÇö never overrides a real node id.
for alias_key, canonical_id in _alias_index(
# the node it names. Only fills gaps — never overrides a real node id.
#
# Kept apart from norm_to_id, gated below, for the same reason
# build_from_json keeps it apart: the alias uniqueness check only
# protects against two same-stem files in one language, never a
# same-named node whose real identity is in another language (#4941).
alias_to_id = _alias_index(
(n.get("id"), n) for n in nodes
if isinstance(n, dict) and isinstance(n.get("id"), str)
).items():
norm_to_id.setdefault(alias_key, canonical_id)
)
# Re-point every endpoint that has a canonical form BEFORE stubbing, so an
# import that names a real file is not frozen onto a stub minted for its
@@ -403,7 +472,17 @@ def finalize_raw_graph_endpoints(data: dict) -> None:
endpoint = e.get(field)
if isinstance(endpoint, str) and endpoint in declared:
continue
canonical = norm_to_id.get(_normalize_id(endpoint)) if isinstance(endpoint, str) else None
if not isinstance(endpoint, str):
continue
norm = _normalize_id(endpoint)
canonical = norm_to_id.get(norm)
if canonical is None:
alias_target = alias_to_id.get(norm)
if alias_target is not None and _alias_lang_compatible(
e.get("source_file"),
(node_by_id.get(alias_target) or {}).get("source_file"),
):
canonical = alias_target
if canonical is not None:
e[field] = canonical
@@ -604,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)
@@ -644,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.
@@ -664,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"
@@ -816,6 +901,25 @@ def _is_file_node_label(label: "str | None", source_file: "str | None") -> bool:
return "/" in lbl and (sf == lbl or sf.endswith("/" + lbl))
def _has_independent_semantic_evidence(node: dict) -> bool:
"""Do not label-fold a semantic record with evidence of its own.
A file mention can legitimately be folded into an AST file-self node,
but such a fold discards the semantic record's independent explanation
and attribution. Keep these records distinct unless the same-source
(source_file, label) twin rule already matched them.
Only genuine provenance counts. `metadata` and `captured_at` are attached
to ordinary INFERRED mention ghosts by extract.py, so treating them as
evidence would stop those ghosts folding and let duplicates proliferate
on real graphs (#4896).
"""
return any(
node.get(field) not in (None, "", [], {})
for field in ("rationale", "source_url", "author", "contributor")
)
def _shortest_unique_suffix(sf: str, all_sfs: "set[str]") -> str:
"""Shortest trailing path suffix (basename + k parent dirs) of *sf* that is
unique among *all_sfs*. `a/b/index.ts` vs `c/b/index.ts` -> `a/b/index.ts`;
@@ -1218,6 +1322,27 @@ def _alias_index(nodes: "Iterable[tuple[str, dict]]") -> dict[str, str]:
}
def _alias_lang_compatible(edge_source_file: object, alias_source_file: object) -> bool:
"""True unless the edge's own file and the alias target's file are both in
a KNOWN, DIFFERENT language family (#4941).
The uniqueness check in :func:`_alias_index` only protects against
ambiguity between same-stem files, never against a same-named node whose
real identity is in another language entirely: a Dart `PunchType` enum
reference and an unrelated `PunchType.java` file both collapse to the
bare old-stem alias "punchtype", and since only the Java file ever
registers it, the alias commits unconditionally and binds the Dart
reference onto the Java file. Permissive when either side's family is
unknown (no source_file, or an extension outside the known map), so a
legitimate same-language or provenance-less alias still resolves exactly
as before.
"""
from graphify.extract import _lang_family
edge_family = _lang_family(edge_source_file)
alias_family = _lang_family(alias_source_file)
return edge_family is None or alias_family is None or edge_family == alias_family
def _semantic_id_remap(nodes: list, root: str | None) -> dict:
"""Re-derive non-AST node ids from ``source_file`` using the canonical
full-path stem, so a cached/LLM fragment carrying a pre-migration short id
@@ -1315,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.
@@ -1327,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):
@@ -1349,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))
@@ -1464,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
@@ -1699,6 +1865,11 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
if key in _loc_nodes and _loc_nodes[key] != nid:
if not dedup and G.nodes[_loc_nodes[key]].get("_origin") != "ast":
continue
# #4896: an independent semantic explanation is not a disposable
# AST twin even when it names the SAME physical source file.
# Preserve the original semantic id, rationale and source attribution.
if _has_independent_semantic_evidence(attrs):
continue
_noloc_nodes[key] = nid
elif key not in _loc_nodes:
# Spec-conformant method ghost omitting class segment / leading dot
@@ -1742,13 +1913,22 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
ast_id for ast_id, ast_sf in _ast_file_nodes
if _is_file_node_label(label, ast_sf)
}
if len(matches) == 1:
if (
len(matches) == 1
and not _has_independent_semantic_evidence(attrs)
and not _is_file_node_label(label, attrs.get("source_file"))
):
_ghost_remap[nid] = next(iter(matches))
# Remove ghost nodes from the graph; edges will be re-pointed via norm_to_id.
for ghost_id in _ghost_remap:
G.remove_node(ghost_id)
node_set.discard(ghost_id)
if _ghost_remap:
# These folds are intentional (#1145, #3344, #3705), so the write
# guards must not read them as lost nodes. Report them on the same
# {merged-away id: survivor id} channel entity dedup uses (#4940).
G.graph.setdefault("_dedup_remap", {}).update(_ghost_remap)
# Normalized ID map: lets edges survive when the LLM generates IDs with
# slightly different casing or punctuation than the AST extractor.
@@ -1790,10 +1970,27 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
#
# The index itself lives in _alias_index so the raw (--no-cluster) write
# path resolves endpoints identically (#4670).
for alias_key, canonical_id in _alias_index(
(nid, G.nodes[nid]) for nid in node_set
).items():
norm_to_id.setdefault(alias_key, canonical_id)
#
# Kept apart from norm_to_id, not merged into it: the uniqueness check in
# _alias_index only protects against two same-stem files in the SAME
# language racing for one alias, never against a same-named node whose
# real identity is in another language (#4941). Gating the alias lookup
# itself, below, catches that case without touching the unconditional
# normalized-id and ghost-remap entries norm_to_id already carries.
alias_to_id = _alias_index((nid, G.nodes[nid]) for nid in node_set)
def _resolve_endpoint(raw_id: str, edge_source_file: object) -> str:
norm = _normalize_id(raw_id)
resolved = norm_to_id.get(norm)
if resolved is not None:
return resolved
alias_target = alias_to_id.get(norm)
if alias_target is not None and _alias_lang_compatible(
edge_source_file, G.nodes[alias_target].get("source_file")
):
return alias_target
return raw_id
# Iterate edges in a deterministic order. The graph is undirected and stores
# direction in _src/_tgt; when two edges collapse onto the same node pair the
# last write wins, so an unstable iteration order flips _src/_tgt run-to-run
@@ -1829,9 +2026,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
continue
# Remap mismatched IDs via normalization before dropping the edge.
if src not in node_set:
src = norm_to_id.get(_normalize_id(src), src)
src = _resolve_endpoint(src, edge.get("source_file"))
if tgt not in node_set:
tgt = norm_to_id.get(_normalize_id(tgt), tgt)
tgt = _resolve_endpoint(tgt, edge.get("source_file"))
if src not in node_set or tgt not in node_set:
# An import/re-export whose target is not a declared node points at
# an external module (stdlib / third-party / another repo). Mint a
@@ -2149,6 +2346,7 @@ def build(
combined["output_tokens"] += ext.get("output_tokens", 0)
_root = str(Path(root).resolve()) if root else None
_dedup_collapsed = 0
_dedup_remap: dict[str, str] = {}
if dedup and combined["nodes"]:
# Numeric ids must be str before dedup, which keys on them and would
# raise TypeError in _pick_winner's regex search (#2326). build_from_json
@@ -2178,6 +2376,7 @@ def build(
# survivor rewiring the edges get (#2805).
hyperedges=combined.get("hyperedges"),
protected_ids=protected_ids,
remap_out=_dedup_remap,
)
_dedup_collapsed = _before_dedup - len(combined["nodes"])
G = build_from_json(combined, directed=directed, root=_root, dedup=dedup)
@@ -2185,6 +2384,10 @@ def build(
# Popped before to_json so it is not stored in graph.json.
if _dedup_collapsed:
G.graph["_dedup_collapsed"] = _dedup_collapsed
# Which ids dedup folded into which survivor, for the #479 write guard
# (#4940). Popped by to_json, so it is not stored in graph.json.
if _dedup_remap:
G.graph.setdefault("_dedup_remap", {}).update(_dedup_remap)
return G
@@ -2203,6 +2406,20 @@ def take_shrink_accounting(G) -> tuple[int, int]:
return collapsed, pruned
def take_dedup_remap(G) -> dict[str, str]:
"""Read and remove the ``{merged-away id: survivor id}`` map (#4940).
``build`` stashes it on ``G.graph`` when entity dedup merged nodes.
``to_json`` calls this to excuse a saved id the merge folded into a twin,
and it also drops the key so it is never persisted into graph.json.
"""
attrs = getattr(G, "graph", None)
if not isinstance(attrs, dict):
return {}
remap = attrs.pop("_dedup_remap", None)
return dict(remap) if isinstance(remap, dict) else {}
def _norm_label(label: str | None) -> str:
"""Canonical dedup key — Unicode-aware, preserves CJK/word characters."""
if not isinstance(label, str):
@@ -2267,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
@@ -2295,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
@@ -2307,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)),
)
@@ -2888,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
@@ -2981,12 +3241,20 @@ def build_merge(
# guard (#1951), and refusing it here would reintroduce the #1116
# false-refuse for legitimate edits that remove symbols from a file.
if had_graph and not dedup:
# Ghost folds build_from_json made on purpose (#1145, #3344, #3705).
# Read, not popped: to_json reads the same map and strips it.
_folds = G.graph.get("_dedup_remap") or {}
def _in_new_graph(n: dict) -> bool:
nid = n.get("id")
if nid is None or not _hashable(nid):
return True # untrackable identity — never count as lost
if nid in G:
return True
# A fold into a survivor still in the graph is one node, not a
# loss; a survivor that is gone excuses nothing (#4955).
if _folds.get(nid) in G:
return True
# Doc-twin heal (#1799): build_from_json merges a markdown
# quick-scan's bare doc node into its semantic `<id>_doc` twin for
# the same file — a legitimate collapse, not a loss.
@@ -3025,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
+141 -26
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 = 31 # Go credits a call in a package-level `var` initialiser (and its closures) to the file node (#4867); a Go method value passed as an argument is linked as an `indirect_call` (#4868); a Go receiver's field whose struct is declared in a sibling file of the same package is typed so its member calls resolve (#4866); and a Python dispatch table's `module.func` values resolve to the referenced functions as `indirect_call`s (#4773), so cached Go and Python extractions re-run; prior (30): File and per-declaration ids are kept distinct so a top-level declaration sharing the file's name is not dropped (#4854); a SystemVerilog `function new(...)` constructor gets its own node, `method` edge and parameter refs (#4848); a Go `var x = T{}`/`var x = &T{}` types `x` as `T` for receiver resolution like `x := T{}` (#4843); a PowerShell `using module`/`using assembly` name drops its file extension (#4847); a Solidity free-function `using {a, b} for T` set emits `uses` edges (#4846); a CommonLisp forward-referenced superclass binds to its local node instead of a sourceless stub (#4845); and Pascal `inherited`/`inline` form component blocks are recognised so later `object` blocks keep their parent (#4844), so cached extractions across those languages re-run; prior (29): OCaml `and`-chained module/class bindings are all walked (only the first was, so later bindings were silently dropped, #4822), and a SystemVerilog class `task` method is modeled like a `function` one with its own node and parameter refs while its task-locals no longer leak as class fields (#4774), so cached OCaml and Verilog/SystemVerilog extractions re-run; prior (28): Markdown ATX headings parse per CommonMark (closing `#` runs dropped, 0-3 space indent, hash-only lines mint no node, #4790) and fenced code blocks are tracked by CommonMark rules so headings inside fences stop leaking (#4787); YAML keys carry their written spelling and real line and `on`/`off`/`yes`/`no` keys no longer fold to booleans (#4784); rationale labels redact more credential shapes before caching (#4647); Razor `@implements` interface edges are extracted (#4820); aliased Terraform providers get their own node and `provider =` refs resolve (#4819); COBOL paragraphs after a nested `END PROGRAM` reattach to the enclosing program (#4824); Blade `wire:click` binds the bare method name (#4823); a Pascal record is a type with its own methods (#4825); VB.NET operator declarations are extracted as members with their bodies walked (#4821); and a Fortran call resolves to the subroutine it names (#4795), so cached Markdown/YAML/rationale/Razor/Terraform/COBOL/Blade/Pascal/VB.NET/Fortran extractions re-run; prior (27): VB.NET external namespace/type stubs now carry a `source_file` sentinel (#4725); Python member calls resolve through injected fields and method-result types (#4726); a Rust `use` is scoped to the crate it names (#4699), so cached VB.NET/Python/Rust extractions re-run; prior (26): Zig no longer crosses a call between a method and a same-named free function (#4755), and a Dart unnamed `extension on T` is detected (#4741), so cached Zig and Dart extractions re-run; prior (25): Python/Go/C++/Rust explicit type aliases (and Rust `union` items) are extracted as type nodes so references resolve instead of minting sourceless stubs (#4578/#4579/#4580/#4581); each C# method overload gets its own node bound by arity (#4584); a package.json dependency's manifest entry links to its ref node (#4569), so cached extractions re-run; prior (24): Objective-C `NS_CLOSED_ENUM` declarations are extracted as enums like `NS_ENUM` (#4705), and a `CREATE TABLE` whose column default the SQL grammar rejects (MySQL `DEFAULT current_timestamp()`) is recovered from its ERROR node (#4613), so cached ObjC and SQL extractions re-run; prior (23): `.yaml`/`.yml` files are structurally extracted (keys as nodes, config-vs-data gated) and reclassified from document to code (#2214), so cached YAML re-extracts; prior (22): SQL labels drop T-SQL brackets and routine bodies emit `reads_from`/`writes_to` (#4635), and a `GO` batch separator ends a statement (#4651), so cached `.sql` extractions re-run; prior (21): a CommonJS `const X = require('./m')` binding no longer mints a module-scope node that shadows the class the required file exports, so `new X()` resolves to the required declaration (#4621); prior (20): Obsidian `[[wikilink]]` targets that start with the scan root's own folder names now resolve to the real page (#4559), so cached markdown extractions re-run; prior (19): Dart `typedef` declarations are extracted as aliases (not variables of type `typedef`); C++ Metal/CUDA GPU qualifiers no longer mint sourceless god nodes (#4550); a `.h` header containing `extern "C"` routes to the C++ extractor; prior (18): Kotlin `typealias` (#4553), C# `delegate` (#4552), and Swift `macro` declarations (#4551) are now extracted so references stop minting sourceless stubs; Rust `use` rooted at a `mod` declaredLine 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 = {}
@@ -499,14 +502,22 @@ def _flush_stat_index() -> None:
def _normalize_path(path: Path) -> Path:
"""Normalize path for consistent cache keys across Windows path spellings."""
"""Normalize a path for cache identity without folding case.
Windows spellings can differ in separators and in the optional
extended-length prefix. Case is not equivalent on every volume a Windows
process can reach, so the key keeps the caller's case. Use
paths.os_long_path() for the path handed to the filesystem.
"""
import sys
if sys.platform != "win32":
return path
s = str(path)
if s.startswith("\\\\?\\"):
if s.startswith("\\\\?\\UNC\\"):
s = "\\\\" + s[8:] # \\?\UNC\server\share -> \\server\share
elif s.startswith("\\\\?\\"):
s = s[4:] # strip extended-length prefix \\?\
return Path(os.path.normcase(s))
return Path(os.path.normpath(s))
def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = None) -> str:
@@ -525,19 +536,30 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
The path handed to the filesystem comes from os_long_path(); the cache key
preserves case because case sensitivity belongs to the volume, not the
platform (#4925).
"""
global _stat_index_dirty
p = _normalize_path(Path(path))
root = _normalize_path(Path(root))
if not p.is_file():
raise IsADirectoryError(f"file_hash requires a file, got: {p}")
raw_path = Path(path)
raw_root = Path(root)
src = Path(_os_long_path(raw_path))
root_src = Path(_os_long_path(raw_root))
if not src.is_file():
raise IsADirectoryError(f"file_hash requires a file, got: {src}")
# The stat index is a cache artifact, so it must follow the cache location
# (cache_root), not the key-anchor root — otherwise it leaves a stray
# graphify-out/cache/stat-index.json inside the analyzed source tree even when
# the AST cache itself is redirected to CWD (#1774 completion).
_ensure_stat_index(root, cache_root=cache_root)
resolved = p.resolve()
#
# The index root, key and salt use the normalized spelling. The \\?\ form
# from os_long_path() is for I/O only: as the root it made load_cached()'s
# plain cache_root look like a second root (#3989), and no key was relative
# to it, so every key was written absolute (#2199).
_ensure_stat_index(_normalize_path(raw_root), cache_root=cache_root)
resolved = _normalize_path(src.resolve())
abs_key = str(resolved)
# The salt is the path component that enters the digest (relative to root, or
# the absolute-path fallback). The stat-index memo MUST be keyed by it too:
@@ -546,17 +568,17 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
# path served whichever was computed first — making file_hash order-dependent
# and poisoning the persisted stat-index across runs (#1989). Store one digest
# per salt so alternating roots don't force re-reads.
resolved_root = root.resolve()
resolved_root = _normalize_path(root_src.resolve())
try:
resolved_rel = resolved.relative_to(resolved_root)
except ValueError:
# Preserve the existing fallback for a target outside the corpus. An
# in-root symlink to such a target is excluded by collect_files(), but
# direct cache callers still rely on the resolved external identity.
salt = resolved.as_posix().lower()
salt = resolved.as_posix()
else:
walked = Path(os.path.abspath(p))
walked_root = Path(os.path.abspath(root))
walked = Path(os.path.abspath(raw_path))
walked_root = Path(os.path.abspath(raw_root))
try:
walked_rel = walked.relative_to(walked_root)
except ValueError:
@@ -567,18 +589,18 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
walked_rel = None
for parent in walked.parents:
try:
if parent.resolve() == resolved_root:
if _normalize_path(parent.resolve()) == resolved_root:
walked_rel = walked.relative_to(parent)
break
except OSError:
continue
if walked_rel is None:
walked_rel = resolved_rel
salt = walked_rel.as_posix().lower()
salt = walked_rel.as_posix()
st: "os.stat_result | None" = None
try:
st = p.stat()
st = src.stat()
if _stat_sig_fresh(_stat_index.get(abs_key), st):
hashes = _stat_index[abs_key].get("hashes")
if isinstance(hashes, dict):
@@ -593,8 +615,8 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
# Captured BEFORE the read so the stamp can never post-date content that
# changed while we were reading it (see _stat_sig_fresh).
observed_at_ns = time.time_ns()
raw = p.read_bytes()
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
raw = src.read_bytes()
content = _body_content(raw) if src.suffix.lower() == ".md" else raw
h = hashlib.sha256()
h.update(content)
h.update(b"\x00")
@@ -628,13 +650,14 @@ def cached_word_count(path: Path, root: Path, compute, cache_root: "Path | None"
correct, just not accelerated.
"""
global _stat_index_dirty
p = _normalize_path(Path(path))
root = _normalize_path(Path(root))
_ensure_stat_index(root, cache_root=cache_root)
abs_key = str(p.resolve())
raw_path = Path(path)
raw_root = Path(root)
src = Path(_os_long_path(raw_path))
_ensure_stat_index(_normalize_path(raw_root), cache_root=cache_root)
abs_key = str(_normalize_path(src.resolve()))
st: "os.stat_result | None" = None
try:
st = p.stat()
st = src.stat()
entry = _stat_index.get(abs_key)
if _stat_sig_fresh(entry, st) and "word_count" in entry:
return entry["word_count"]
@@ -644,7 +667,7 @@ def cached_word_count(path: Path, root: Path, compute, cache_root: "Path | None"
# Captured BEFORE compute() reads the file, for the same reason file_hash
# stamps before its read (see _stat_sig_fresh).
observed_at_ns = time.time_ns()
wc = compute(Path(path))
wc = compute(raw_path)
if st is not None:
_stat_entry_for(abs_key, st, observed_at_ns)["word_count"] = wc
@@ -1826,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("."),
+721 -111
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -138,6 +138,7 @@ def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
)
for src, tgt, attrs in edge_rows:
stable.add_edge(src, tgt, **attrs)
del edge_rows # `stable` holds the edges now
native_result = _native_leiden(stable, resolution)
if native_result is not None:
+41 -4
View File
@@ -973,9 +973,9 @@ def _is_reference_stub(node: dict) -> bool:
def _namespace_reference_stub_collisions(
nodes: list[dict], edges: list[dict], hyperedges: list[dict] | None,
root: Path | None,
root: Path | None, *, preserve_saved_semantics: bool = False,
) -> tuple[list[dict], list[dict]]:
"""Keep marked cross-document reference stubs distinct (#4738).
"""Keep semantic references distinct from another file's defining node.
Semantic extraction marks a node it emitted solely for a referenced entity
with ``metadata.graphify_reference_stub``. Preserve every marked node under
@@ -986,6 +986,10 @@ def _namespace_reference_stub_collisions(
The marker distinguishes reference stubs from two independent documents
that happen to share an ID. Path specificity cannot make that distinction:
it regresses genuine nested-path definitions.
With preserve_saved_semantics, AST-only updates retain saved semantic
evidence even when it predates the reference-stub marker. A scan root is
required to distinguish source files; full builds keep their definer rules.
"""
def key(source_file: object) -> str:
return _rank_path(source_file, root) if isinstance(source_file, str) else ""
@@ -1001,7 +1005,21 @@ def _namespace_reference_stub_collisions(
for nid, members in by_id.items():
if len({key(node.get("source_file")) for node in members}) < 2:
continue
stubs = [node for node in members if _is_reference_stub(node)]
ast_sources = {
key(node.get("source_file")) for node in members
if node.get("_origin") == "ast"
}
stubs = [
node for node in members
if _is_reference_stub(node) or (
preserve_saved_semantics
and root is not None
and node.get("_origin") == "semantic"
and key(node.get("source_file"))
and ast_sources
and key(node.get("source_file")) not in ast_sources
)
]
if not stubs:
continue
source_keys = {key(node.get("source_file")) for node in stubs}
@@ -1017,7 +1035,18 @@ def _namespace_reference_stub_collisions(
if len(set(candidates.values())) != len(candidates):
continue
if any(candidate in taken for candidate in candidates.values()):
continue
if not preserve_saved_semantics:
continue
reserved = taken | set(candidates.values())
for source_key in sorted(candidates):
base = candidates[source_key]
candidate = base
suffix = 2
while candidate in taken or (candidate != base and candidate in reserved):
candidate = f"{base}__{suffix}"
suffix += 1
candidates[source_key] = candidate
reserved.add(candidate)
renames.update(((nid, source_key), candidate)
for source_key, candidate in candidates.items())
taken.update(candidates.values())
@@ -1034,6 +1063,8 @@ def _namespace_reference_stub_collisions(
for item in collection:
if not isinstance(item, dict):
continue
if preserve_saved_semantics and item.get("_origin") == "ast":
continue
source_key = key(item.get("source_file"))
for endpoint in ("source", "target"):
value = item.get(endpoint)
@@ -1099,6 +1130,7 @@ def deduplicate_entities(
root: str | Path | None = None,
hyperedges: "list[dict] | None" = None,
protected_ids: "set[str] | None" = None,
remap_out: "dict[str, str] | None" = None,
) -> tuple[list[dict], list[dict]]:
"""Deduplicate near-identical entities in a knowledge graph.
@@ -1106,6 +1138,9 @@ def deduplicate_entities(
nodes: list of node dicts with at minimum {"id": str, "label": str}
edges: list of edge dicts with {"source": str, "target": str, ...}
communities: mapping of node_id -> community_id (from cluster())
remap_out: if given, filled with ``{merged-away id: surviving id}`` for
every node this call dropped. Lets a caller tell a node that was
folded into a twin from one that was lost (#4940).
dedup_llm_backend: if set, use LLM to resolve ambiguous pairs
root: scan root; ID-collision ranking judges source paths relative to
it so path form and checkout location cannot flip the survivor (#2532)
@@ -1538,6 +1573,8 @@ def deduplicate_entities(
if not remap:
return unique_nodes, edges
if remap_out is not None:
remap_out.update(remap)
total = len(remap)
msg = f"[graphify] Deduplicated {total} node(s)"
# Both counters are reported when non-zero. Previous form nested the fuzzy
+117 -42
View File
@@ -56,6 +56,13 @@ _BINARY_MEDIA_EXTENSIONS = (IMAGE_EXTENSIONS - {'.svg'}) | VIDEO_EXTENSIONS
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
FILE_COUNT_UPPER = 500 # files - above this, warn about token cost
# #2942: a large *fraction* of the corpus having no supported extractor (not
# just a small, expected sliver of e.g. lockfiles or binaries) means the
# resulting graph looks complete but structurally represents only part of the
# codebase. Gated on an absolute floor too, so a tiny repo with one stray
# unsupported file does not trip this.
UNCLASSIFIED_WARN_MIN_FILES = 20
UNCLASSIFIED_WARN_FRACTION = 0.2
# Resource caps for parsing untrusted office/PDF files (F2). A corpus is
# attacker-controllable (graphify runs on cloned/shared folders), and .docx/.xlsx
@@ -1038,7 +1045,8 @@ def is_resolution_input(path: "Path | str") -> bool:
_JS_SNAPSHOT_TEST_ROOTS = frozenset({"__tests__", "__test__"})
# Platforms whose project-scope skills dir is one level below the hidden dir
# (install.py: pi -> .pi/agent/skills, kilo -> .config/kilo/skills).
# (install.py: kilo -> .config/kilo/skills; pi wrote .pi/agent/skills before
# #5011 and projects installed then still carry it).
_NESTED_SKILL_HOLDERS = frozenset({(".pi", "agent"), (".config", "kilo")})
# Single files `graphify install` writes whole into a project (#4057): the
@@ -2012,6 +2020,7 @@ def ignored_predicate(
if line:
patterns.append((root, line))
explicit_patterns.append((root, line))
linked_boundaries: dict[Path, bool] = {}
cache: dict[Path, bool] = {}
explicit_cache: dict[Path, bool] = {}
# root's own ignore file is the last entry of _load_graphifyignore's chain.
@@ -2032,6 +2041,13 @@ def ignored_predicate(
if _is_noise_dir(part, parent):
return True
parent = parent / part
if parent not in linked_boundaries:
main_root = _linked_worktree_main_root(parent)
linked_boundaries[parent] = (
main_root is not None and _resolves_under_root(main_root, root)
)
if linked_boundaries[parent]:
return True
# Load ignore files along this path's own lineage — detect()'s walk
# would have loaded exactly these before reaching the file (#1206).
ancestor = root
@@ -2405,12 +2421,33 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
f"Consider running on a subfolder."
)
# #2942: a few unclassified files (lockfiles, binaries, stray config) are
# routine and already reported above by count. A large SHARE of the files
# actually seen having no supported extractor at all is a different,
# louder signal: the graph may look complete while structurally missing
# a large part of the codebase (e.g. a repo whose business logic lives in
# XML, or another language graphify does not parse).
unclassified_warning: str | None = None
_seen_total = total_files + len(unclassified)
if (
len(unclassified) >= UNCLASSIFIED_WARN_MIN_FILES
and _seen_total
and len(unclassified) / _seen_total >= UNCLASSIFIED_WARN_FRACTION
):
unclassified_warning = (
f"{len(unclassified)} of {_seen_total} files seen "
f"({round(len(unclassified) / _seen_total * 100)}%) have no supported "
f"extractor and are missing from this graph entirely. It may look "
f"complete while representing only part of the codebase."
)
return {
"files": {k.value: v for k, v in files.items()},
"total_files": total_files,
"total_words": total_words,
"needs_graph": needs_graph,
"warning": warning,
"unclassified_warning": unclassified_warning,
"skipped_sensitive": skipped_sensitive,
"unclassified": sorted(unclassified),
"walk_errors": walk_errors,
@@ -3020,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(
@@ -3125,6 +3170,60 @@ def classify_manifest_files(
return new_files, unchanged_files
def classify_manifest_deletions(
manifest: dict,
scanned: Iterable[str],
*,
root: Path | None = None,
) -> tuple[list[str], list[str]]:
"""Split manifest rows that left the scan into (deleted, excluded).
A row whose file is gone from DISK is a genuine deletion (its cached nodes
are ghosts); a row whose file still exists but is out of the current scan was
EXCLUDED by a changed ignore rule and must not be reported as deleted
(#1908). Mirrors the watch-side excluded-vs-deleted distinction (#1795).
``scanned`` must name every row the caller expects to see, including sources
that carry manifest rows without being part of the scan corpus
(``detect()["resolution_inputs"]``, #4740), or those rows read as excluded on
every run.
"""
try:
root_res: Path | None = Path(root).resolve() if root is not None else None
except (OSError, RuntimeError):
root_res = Path(root) if root is not None else None
def _in_root(path_str: str) -> bool:
if root_res is None:
return True
p = Path(path_str)
try:
p.relative_to(root_res)
return True
except ValueError:
pass
try:
p.resolve().relative_to(root_res)
return True
except (ValueError, OSError, RuntimeError):
return False
current_files = {_nfc(f) for f in scanned}
deleted_files: list[str] = []
excluded_files: list[str] = []
for f in manifest:
if not _in_root(f):
continue
if _nfc(f) in current_files:
continue
try:
alive = Path(f).exists()
except OSError:
alive = False
(excluded_files if alive else deleted_files).append(f)
return deleted_files, excluded_files
def detect_incremental(
root: Path,
manifest_path: str = _MANIFEST_PATH,
@@ -3195,44 +3294,20 @@ def detect_incremental(
# nodes are ghosts); a row whose file still exists but is out of the
# current scan was EXCLUDED (ignore rules / --exclude changed) and must
# not be reported as deleted. Mirrors the watch-side excluded-vs-deleted
# distinction (#1795).
try:
root_res: Path | None = Path(root).resolve() if root is not None else None
except (OSError, RuntimeError):
root_res = Path(root) if root is not None else None
def _in_root(path_str: str) -> bool:
if root_res is None:
return True
p = Path(path_str)
try:
p.relative_to(root_res)
return True
except ValueError:
pass
try:
p.resolve().relative_to(root_res)
return True
except (ValueError, OSError, RuntimeError):
return False
current_files = {_nfc(f) for flist in full["files"].values() for f in flist}
# Resolution inputs carry manifest rows but are deliberately kept out of
# detect()'s corpus. Without this they read as rows that "left the scan" and
# would be reported as excluded on every run (#4740).
current_files |= {_nfc(f) for f in full.get("resolution_inputs", [])}
deleted_files: list[str] = []
excluded_files: list[str] = []
for f in manifest:
if not _in_root(f):
continue
if _nfc(f) in current_files:
continue
try:
alive = Path(f).exists()
except OSError:
alive = False
(excluded_files if alive else deleted_files).append(f)
# distinction (#1795). Resolution inputs carry manifest rows while being
# deliberately kept out of detect()'s corpus, so they are named here too;
# without that they would read as rows that left the scan on every run
# (#4740).
deleted_files, excluded_files = classify_manifest_deletions(
manifest,
[
f
for flist in full["files"].values()
for f in flist
]
+ list(full.get("resolution_inputs", [])),
root=root,
)
new_total = sum(len(v) for v in new_files.values())
full["incremental"] = True
+58 -16
View File
@@ -75,18 +75,25 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
backup_dir = out / today
graph_src = out / "graph.json"
# Skip re-copying if today's backup already has identical graph.json content.
# If content differs (graph changed since the last backup today), overwrite
# the backup in place — one folder per day, always the latest pre-overwrite state.
if backup_dir.exists() and (backup_dir / "graph.json").exists():
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
if src_hash == bak_hash:
return backup_dir # identical content, nothing to do
try:
# Skip re-copying if today's backup already holds every artifact with an
# identical graph.json. graph.json alone is not proof of completeness: a
# snapshot missing a sidecar (an earlier copy attempt failed part-way)
# must fall through and retry the copy instead of reporting itself
# complete forever (#3769). If content differs, overwrite the backup in
# place — one folder per day, always the latest pre-overwrite state.
if backup_dir.exists() and (backup_dir / "graph.json").exists():
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
if src_hash == bak_hash and all(
(backup_dir / name).exists()
for name in _BACKUP_ARTIFACTS
if (out / name).exists()
):
return backup_dir # identical content, nothing to do
backup_dir.mkdir(parents=True, exist_ok=True)
copied = 0
failed: list[str] = []
for name in _BACKUP_ARTIFACTS:
src = out / name
if src.exists():
@@ -94,12 +101,21 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
shutil.copy2(src, backup_dir / name)
copied += 1
except Exception:
pass
failed.append(name)
if failed:
# A partial snapshot reported as a successful backup lets a stale
# graph.json survive the next overwrite unnoticed (#3769). Best-effort
# is unchanged: warn, report no backup, do not block the write.
print(
f"[graphify] warning: backup incomplete - could not copy "
f"{', '.join(failed)} -> {backup_dir.name}/ - continuing with overwrite",
file=sys.stderr,
)
return None
if copied:
print(f"[graphify] backed up {reason} graph ({copied} files) -> {backup_dir.name}/")
return backup_dir
except Exception as exc:
import sys
print(f"[graphify] warning: backup failed ({exc}) - continuing with overwrite", file=sys.stderr)
return None
@@ -287,8 +303,14 @@ def existing_graph_node_count(path: "str | Path"):
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None, community_labels: dict[int, str] | None = None, original_links: "list[dict] | None" = None) -> bool:
# Drop #3774 accounting before any write. Extract pops these first; every
# other caller of to_json (the documented build_merge persist path) does not.
from graphify.build import take_shrink_accounting
from graphify.build import take_dedup_remap, take_shrink_accounting
# The guard below reads it; it is removed here so node_link_data cannot
# write it into graph.json (#4940).
dedup_remap = take_dedup_remap(G)
take_shrink_accounting(G)
# Sources build_merge replaced or pruned this run: their old semantic ids
# are not lost. Popped so it is never written into graph.json.
replaced_sources = set(G.graph.pop("_replaced_sources", None) or ())
# Safety check: refuse to silently shrink an existing graph (#479)
existing_path = Path(output_path)
if not force and existing_path.exists():
@@ -315,7 +337,10 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
else:
try:
existing_data = json.loads(raw)
del raw
existing_nodes = existing_data.get("nodes", [])
# Only the node list is compared; let the links go now.
del existing_data
if not isinstance(existing_nodes, list):
existing_nodes = []
existing_n = len(existing_nodes)
@@ -335,13 +360,15 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
)
return False
new_n = G.number_of_nodes()
from graphify.build import _lost_saved_semantic_nodes
from graphify.build import _dedup_shrink_allowance, _lost_saved_semantic_nodes
new_node_list = [
{"id": node_id, **{key: value for key, value in attrs.items() if key != "id"}}
for node_id, attrs in G.nodes(data=True)
]
folded: dict[str, str] = {}
missing = _lost_saved_semantic_nodes(existing_nodes, new_node_list, set(), folded)
missing = _lost_saved_semantic_nodes(
existing_nodes, new_node_list, replaced_sources, folded, dedup_remap=dedup_remap,
)
if missing:
import sys as _sys
ids = ", ".join(str(node.get("id")) for node in missing)
@@ -356,6 +383,11 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
# A twin new to this run does not offset some other node's loss.
existing_ids = {n.get("id") for n in existing_nodes if isinstance(n, dict)}
merged = sum(twin in existing_ids for twin in folded.values())
# Ids entity dedup folded into a survivor are not lost either (#4940).
if dedup_remap:
merged += _dedup_shrink_allowance(
existing_ids, set(G.nodes), dedup_remap,
)
if new_n < existing_n - merged:
import sys as _sys
print(
@@ -369,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()}
@@ -442,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", {}):
@@ -464,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:
+1612 -74
View File
File diff suppressed because it is too large. Load diff
+64 -5
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import sys
from contextvars import ContextVar
from pathlib import Path
from graphify.ids import make_id
@@ -15,15 +16,33 @@ from graphify.ids import make_id
# function-local `import graphify.extract` + getattr(..., None) was a package ->
# parent dependency that also failed silently if the module global were renamed
# (#3666). None outside extract().
_ACTIVE_SCAN_ROOT: "Path | None" = None
#
# A ContextVar rather than a module global: extraction runs concurrently
# (ThreadPoolExecutor in tests, process pools in production), and a plain
# global lets overlapping save/restore pairs interleave — the second call
# saves the first one's root and restores it last, leaving the ambient root
# set after extract() returns (#4602). ContextVar gives every thread (and
# async task) its own value, so save/restore pairs nest correctly without a
# lock.
#
# Semantic note: because the value is context-local, a root set on one
# thread is NOT visible to worker threads spawned mid-extraction. Every
# real call path sets and reads the root inside the same pool worker
# (_safe_extract_with_xaml_root runs inside the worker; the scan root also
# travels to workers as an explicit `root` parameter, not via this
# global), so no production path crosses the boundary. If a future
# extractor needs cross-thread visibility, propagate explicitly with
# contextvars.copy_context() at the dispatch site.
_ACTIVE_SCAN_ROOT: "ContextVar[Path | None]" = ContextVar(
"_ACTIVE_SCAN_ROOT", default=None
)
def set_active_scan_root(root: "Path | None") -> "Path | None":
"""Set the in-flight scan root, returning the previous value so the caller
can restore it — extraction nests (a XAML shard re-enters extract())."""
global _ACTIVE_SCAN_ROOT
previous = _ACTIVE_SCAN_ROOT
_ACTIVE_SCAN_ROOT = root
previous = _ACTIVE_SCAN_ROOT.get()
_ACTIVE_SCAN_ROOT.set(root)
return previous
@@ -32,7 +51,7 @@ def active_scan_root() -> "Path | None":
A direct ``extract_markdown()`` / ``extract_xaml()`` call (no surrounding
``extract()``) sees None and the root-dependent behavior stays off."""
return _ACTIVE_SCAN_ROOT
return _ACTIVE_SCAN_ROOT.get()
# Language built-in globals that AST may classify as call targets when used as
# constructors or coercion functions (e.g. String(x), Number(x), Boolean(x)).
@@ -79,6 +98,46 @@ _LANGUAGE_BUILTIN_GLOBALS: frozenset[str] = frozenset({
"View", "Color", "Font",
})
# Python's own builtin namespace, deliberately kept separate from
# ``_LANGUAGE_BUILTIN_GLOBALS``. That set is consulted at extraction time for a
# bare call, where dropping the raw call is correct for a true builtin but also
# throws away the evidence needed to resolve a legitimate imported class that
# merely shares a builtin's name (#4989). This set is only consulted after a
# cross-file candidate has been found, and only to require a direct import
# binding before accepting it: in Python a bare name resolves to the builtin
# unless the module binds it itself, so `raise NotImplementedError` in a file
# that never imports anything must not link to a package class named
# ``NotImplementedError``. Fixed rather than derived from ``dir(builtins)`` so
# extraction stays deterministic across interpreter versions.
_PYTHON_BUILTIN_NAMES: frozenset[str] = frozenset({
"ArithmeticError", "AssertionError", "AttributeError", "BaseException",
"BaseExceptionGroup", "BlockingIOError", "BrokenPipeError", "BufferError",
"BytesWarning", "ChildProcessError", "ConnectionAbortedError", "ConnectionError",
"ConnectionRefusedError", "ConnectionResetError", "DeprecationWarning", "EOFError",
"Ellipsis", "EncodingWarning", "EnvironmentError", "Exception", "ExceptionGroup",
"False", "FileExistsError", "FileNotFoundError", "FloatingPointError",
"FutureWarning", "GeneratorExit", "IOError", "ImportError", "ImportWarning",
"IndentationError", "IndexError", "InterruptedError", "IsADirectoryError",
"KeyError", "KeyboardInterrupt", "LookupError", "MemoryError",
"ModuleNotFoundError", "NameError", "None", "NotADirectoryError", "NotImplemented",
"NotImplementedError", "OSError", "OverflowError", "PendingDeprecationWarning",
"PermissionError", "ProcessLookupError", "RecursionError", "ReferenceError",
"ResourceWarning", "RuntimeError", "RuntimeWarning", "StopAsyncIteration",
"StopIteration", "SyntaxError", "SyntaxWarning", "SystemError", "SystemExit",
"TabError", "TimeoutError", "True", "TypeError", "UnboundLocalError",
"UnicodeDecodeError", "UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError",
"UnicodeWarning", "UserWarning", "ValueError", "Warning", "ZeroDivisionError",
"abs", "aiter", "all", "anext", "any", "ascii", "bin", "bool", "breakpoint",
"bytearray", "bytes", "callable", "chr", "classmethod", "compile", "complex",
"copyright", "credits", "delattr", "dict", "dir", "divmod", "enumerate", "eval",
"exec", "exit", "filter", "float", "format", "frozenset", "getattr", "globals",
"hasattr", "hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass",
"iter", "len", "license", "list", "locals", "map", "max", "memoryview", "min",
"next", "object", "oct", "open", "ord", "pow", "print", "property", "quit", "range",
"repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod",
"str", "sum", "super", "tuple", "type", "vars", "zip",
})
def _make_id(*parts: str) -> str:
return make_id(*parts)
+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, []):
+37 -27
View File
@@ -203,35 +203,45 @@ def extract_dart(path: Path) -> dict:
header_end = len(rest)
header = rest[:header_end]
base_class = None
generics = None
mixins_list = []
interfaces_list = []
# Parse extends or on
extends_m = re.search(r"^\s*(?:extends|on)\s+([a-zA-Z0-9_.]+)", header)
def _consume_generic_args(text: str) -> tuple[str | None, str]:
if not text.strip().startswith("<"):
return None, text
start_idx = text.find("<")
depth = 1
i = start_idx + 1
while i < len(text) and depth > 0:
if text[i] == "<":
depth += 1
elif text[i] == ">":
depth -= 1
if depth == 0:
return text[start_idx + 1 : i], text[i + 1:]
i += 1
return None, text
# Parse extends or on. A mixin's `on` clause may list several
# superclass constraints, comma-separated (`mixin Foo on A, B {}`);
# `extends` never does, since Dart classes have single inheritance.
base_entries: list[tuple[str, str | None]] = []
extends_m = re.search(r"^\s*(extends|on)\s+([a-zA-Z0-9_.]+)", header)
if extends_m:
base_class = extends_m.group(1)
rest_header = header[extends_m.end():]
if rest_header.strip().startswith("<"):
start_idx = rest_header.find("<")
depth = 1
i = start_idx + 1
while i < len(rest_header) and depth > 0:
if rest_header[i] == "<":
depth += 1
elif rest_header[i] == ">":
depth -= 1
if depth == 0:
generics = rest_header[start_idx + 1 : i]
break
i += 1
if generics is not None:
header = rest_header[i + 1:]
else:
header = rest_header
else:
header = rest_header
is_on = extends_m.group(1) == "on"
base_class = extends_m.group(2)
header = header[extends_m.end():]
generics, header = _consume_generic_args(header)
base_entries.append((base_class, generics))
if is_on:
while True:
comma_m = re.match(r"\s*,\s*([a-zA-Z0-9_.]+)", header)
if not comma_m:
break
header = header[comma_m.end():]
extra_generics, header = _consume_generic_args(header)
base_entries.append((comma_m.group(1), extra_generics))
# Parse with
with_m = re.search(r"^\s*with\s+", header)
@@ -251,8 +261,8 @@ def extract_dart(path: Path) -> dict:
if impl_m:
interfaces_list = _split_types(header[impl_m.end():])
# Map extends inheritance relation
if base_class:
# Map extends/on inheritance relation(s)
for base_class, generics in base_entries:
base_nid = _make_id(base_class)
add_node(base_nid, base_class, source_file=None)
add_edge(class_nid, base_nid, "inherits", line=class_line)
+24 -7
View File
@@ -327,9 +327,13 @@ def extract_elixir(path: Path) -> dict:
enclosing[func_nid] = parent_module_nid
if parent_module_nid:
add_edge(parent_module_nid, func_nid, "method", line)
module_defs.setdefault((parent_module_nid, func_name), func_nid)
else:
add_edge(file_nid, func_nid, "contains", line)
# Keyed by the def's own container (module, or the file for a
# top-level def) so a bare call can be resolved to the def that is
# actually in scope for its caller, never to an unrelated
# same-named def elsewhere in the file (see walk_calls below).
module_defs.setdefault((container, func_name), func_nid)
if do_block_node:
function_bodies.append((func_nid, do_block_node))
else:
@@ -359,11 +363,6 @@ def extract_elixir(path: Path) -> dict:
walk(root)
label_to_nid: dict[str, str] = {}
for n in nodes:
normalised = n["label"].strip("()").lstrip(".")
label_to_nid[normalised] = n["id"]
module_nid_by_name = {name: nid for nid, name in module_names.items()}
_MODULE_REF = re.compile(r"(__MODULE__|[A-Z]\w*)(\.[A-Z]\w*)*")
@@ -434,8 +433,26 @@ def extract_elixir(path: Path) -> dict:
if receiver_module is not None:
mod_nid = module_nid_by_name.get(receiver_module)
tgt_nid = module_defs.get((mod_nid, callee_name)) if mod_nid else None
elif is_member_call:
tgt_nid = None
else:
tgt_nid = None if is_member_call else label_to_nid.get(callee_name)
# A bare call only ever reaches a def that is actually in
# scope for this caller: its own module (or the file, for a
# top-level caller) first, then each module brought into
# scope by `import`/`use`. Without this a same-named def in
# an unrelated sibling module in the same file silently won
# over the caller's own def, since both shared one flat
# name -> id table.
own_container = enclosing.get(caller_nid) or file_nid
tgt_nid = module_defs.get((own_container, callee_name))
if tgt_nid is None:
for scope_name in _call_scope_for(caller_nid):
scope_nid = module_nid_by_name.get(scope_name)
if scope_nid is None:
continue
tgt_nid = module_defs.get((scope_nid, callee_name))
if tgt_nid is not None:
break
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
File diff suppressed because it is too large. Load diff
+13
View File
@@ -314,6 +314,19 @@ def extract_fortran(path: Path) -> dict:
line = node.start_point[0] + 1
add_node(type_nid, type_name, line)
add_edge(scope_nid, type_nid, "defines", line)
# `type, extends(base) :: derived` is Fortran's derived-type
# inheritance syntax (the `type :: name` bare form has no base).
# Without this, every extends() clause was silently dropped and
# Fortran OOP hierarchies never got an inherits edge, unlike every
# other OOP language extractor.
base_spec = next((c for c in stmt.children if c.type == "base_type_specifier"), None)
if base_spec is not None:
base_name_node = next((c for c in base_spec.children if c.type == "identifier"), None)
if base_name_node is not None:
base_name = _read_text(base_name_node, source).lower()
base_nid = ensure_named_node(base_name, line)
if base_nid != type_nid:
add_edge(type_nid, base_nid, "inherits", line)
# Type-bound procedures in the `contains` section bind the
# derived type to the module procedures that implement its
# methods. Without this the binding was dropped and the type
+181 -63
View File
@@ -12,6 +12,7 @@ from graphify.extractors.base import (
_read_source_bytes,
_read_text,
)
from graphify.extractors.resolution import _go_import_path_for_file
_GO_PREDECLARED_TYPES = frozenset({
@@ -49,6 +50,13 @@ _GO_PREDECLARED_FUNCS = frozenset({
"recover",
})
# The tree-sitter-go nodes a type argument parses as (`new(T)`, `make([]pkg.T, n)`);
# an ordinary argument is an expression and never one of these.
_GO_TYPE_NODES = frozenset({
"type_identifier", "qualified_type", "pointer_type", "generic_type", "slice_type",
"array_type", "map_type", "channel_type", "parenthesized_type",
})
def _go_alias_re_exports(alias_node, source: bytes) -> bool:
"""Whether `type A = pkg.A` (or `pkg.A[...]`) re-exports another package's type
under its own name. Such an alias denotes that very type and declares no new
@@ -168,12 +176,22 @@ def _go_strip_generic_args(type_text: str) -> str:
def _go_single_type_name(node, source: bytes) -> str | None:
"""The one declared type a Go type expression names, or None.
Only `Greeter` and `*Greeter` qualify. A slice, map or channel element is not the
receiver of `x.M()`, and a `qualified_type` (`pkg.Greeter`) names a type no bare
local name can stand for.
`Greeter`, `*Greeter`, `pkg.Greeter` and `*pkg.Greeter` qualify, and generic
arguments do not change the receiver's base type. A slice, map or channel
element is not the receiver of `x.M()`. A qualified type keeps its package
qualifier as written (`pkg.Greeter`): no bare local name can stand for it, so
the resolver binds it only through the file's import of `pkg`.
"""
if node is not None and node.type == "pointer_type":
node = next((c for c in node.children if c.is_named), None)
while node is not None and node.type in ("pointer_type", "parenthesized_type", "generic_type"):
node = node.child_by_field_name("type") or next(
(c for c in node.children if c.is_named), None,
)
if node is not None and node.type == "qualified_type":
package = node.child_by_field_name("package")
name_node = node.child_by_field_name("name")
if package is None or name_node is None:
return None
return f"{_read_text(package, source)}.{_read_text(name_node, source)}"
if node is None or node.type != "type_identifier":
return None
name = _read_text(node, source)
@@ -198,46 +216,56 @@ def _go_inferred_composite_bindings(names, values, source: bytes):
yield _read_text(name_node, source), type_name
def _go_receiver_type_table(root, source: bytes) -> dict[str, str]:
"""Collect ``name -> TypeName`` for every Go receiver whose type is written down.
def _go_receiver_type_table(
root, source: bytes, *, package_only: bool = False,
) -> dict[str, str | None]:
"""Collect declared or composite-literal receiver types, preserving unknown bindings.
Five sources: a struct field, a parameter (which covers the method receiver
`func (s *Server)`), `var x T`, `x := T{}` / `x := &T{}`, and `var x = T{}` /
`var x = &T{}` (the same composite-literal inference, spelled with `var`
instead of `:=`). Flat over the subtree it is given, first binding wins —
run over one function it is that function's own scope, and over the file it
is the fallback for a struct field. Children are pushed reversed so the
walk yields document order and "first" means first in the source.
Unknown local bindings shadow package variables. Package-only tables exclude
fields and function bodies so unrelated scopes cannot supply a receiver type.
"""
table: dict[str, str] = {}
table: dict[str, str | None] = {}
stack = [root]
while stack:
n = stack.pop()
t = n.type
if t in ("field_declaration", "parameter_declaration", "var_spec"):
type_name = _go_single_type_name(n.child_by_field_name("type"), source)
if type_name:
for c in n.children:
if c.type in ("field_identifier", "identifier"):
table.setdefault(_read_text(c, source), type_name)
elif t == "var_spec":
if t == "block" or (t == "func_literal" and n != root):
continue
if package_only and t in (
"function_declaration", "method_declaration", "func_literal", "type_declaration",
):
continue
if t in (
"field_declaration", "parameter_declaration",
"variadic_parameter_declaration", "var_spec",
):
names = [c for c in n.children if c.type in ("field_identifier", "identifier")]
type_name = (None if t == "variadic_parameter_declaration"
else _go_single_type_name(n.child_by_field_name("type"), source))
inferred = {}
if t == "var_spec" and not type_name:
value = n.child_by_field_name("value")
if value is not None:
names = [c for c in n.children if c.type == "identifier"]
values = [c for c in value.children if c.is_named]
for name_text, inferred in _go_inferred_composite_bindings(
names, values, source
):
table.setdefault(name_text, inferred)
inferred = dict(_go_inferred_composite_bindings(
names, [c for c in value.children if c.is_named], source,
))
for name_node in names:
name = _read_text(name_node, source)
table.setdefault(name, type_name or inferred.get(name))
elif t == "short_var_declaration":
left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
if left is not None and right is not None:
names = [c for c in left.children if c.type == "identifier"]
values = [c for c in right.children if c.is_named]
for name_text, inferred in _go_inferred_composite_bindings(
names, values, source
):
table.setdefault(name_text, inferred)
inferred = dict(_go_inferred_composite_bindings(names, values, source))
for name_node in names:
name = _read_text(name_node, source)
table.setdefault(name, inferred.get(name))
elif t == "range_clause" and any(c.type == ":=" for c in n.children):
left = n.child_by_field_name("left")
for name_node in left.named_children if left is not None else ():
if name_node.type == "identifier":
table.setdefault(_read_text(name_node, source), None)
stack.extend(reversed(n.children))
return table
@@ -302,15 +330,17 @@ def extract_go(path: Path) -> dict:
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
# `(caller nid, body, receiver variable name, receiver type, own-scope types)` — the
# receiver name is what makes `s.logger.Log()` readable as a call on the `logger` field
# rather than on `s`, and the scope types are the bindings the file-flat table can get
# wrong: every function in a file is free to name a parameter `s` after its own type.
function_bodies: list[tuple[str, object, str | None, str | None, dict[str, str]]] = []
# The receiver name identifies `s.field` as an owned field; scope bindings keep
# parameters and locals distinct from package variables, even with unknown types.
function_bodies: list[tuple[str, object, str | None, str | None, dict[str, str | None]]] = []
# Fed to the `_callable` / `_callable_class` stamp below (#2438): the indirect-call
# guard and the cross-repo member-call pass both read them off the node.
callable_nids: set[str] = set()
callable_class_nids: set[str] = set()
# Go interfaces are satisfied implicitly, so nothing else in the output tells an
# interface's method requirements from a struct's methods; `graphify.go_dispatch`
# reads this stamp to know which owners are interfaces.
interface_nids: set[str] = set()
# local package name (including aliases) -> written Go import path
go_imported_pkgs: dict[str, str] = {}
@@ -417,6 +447,33 @@ def extract_go(path: Path) -> dict:
if tgt != func_nid:
add_edge(func_nid, tgt, "references", line, context=ctx)
def emit_go_package_var_type_refs(var_decl) -> None:
# The types a package-level `var` names, in its declared type (`var x T`), a
# composite literal (`pkg.T{}`, `&T{}`) or a type argument (`new(*pkg.T)`,
# `make(map[K]V)`), are referenced by the file, which owns the initialiser
# (#2360). Without this a file holding only a dependency-injection set
# (`wire.Bind(new(Iface), new(*Impl))`) referenced nothing. A closure body is
# function code and is left to the call walk.
stack = [var_decl]
while stack:
n = stack.pop()
if n.type == "func_literal":
continue
type_nodes = []
if n.type in ("var_spec", "composite_literal"):
type_nodes.append(n.child_by_field_name("type"))
elif n.type == "argument_list":
type_nodes.extend(c for c in n.children if c.type in _GO_TYPE_NODES)
for type_node in type_nodes:
refs: list[tuple[str, str]] = []
_go_collect_type_refs(type_node, source, False, refs)
for ref_name, role in refs:
ctx = "generic_arg" if role == "generic_arg" else "variable_type"
line = type_node.start_point[0] + 1
add_edge(file_nid, ensure_named_node(ref_name, line), "references",
line, context=ctx)
stack.extend(c for c in n.children if c not in type_nodes)
# Node IDs are casefolded (ids.py), so `Run` and `run` declared in one file
# produce the same id and add_node silently dropped the second — the unexported
# half vanished from the graph and its call sites bound by bare name to a
@@ -647,6 +704,7 @@ def extract_go(path: Path) -> dict:
add_edge(type_nid, tgt, "references",
field.start_point[0] + 1, context=ctx)
elif type_body.type == "interface_type":
interface_nids.add(type_nid)
for elem in type_body.children:
if elem.type == "method_elem":
# A method requirement declared in the interface body
@@ -707,6 +765,7 @@ def extract_go(path: Path) -> dict:
# closure, are credited to the file, the owner a module-level call already
# gets elsewhere. Without this they were never walked and the callee lost the
# caller (#2360).
emit_go_package_var_type_refs(node)
function_bodies.append(
(file_nid, node, None, None, _go_receiver_type_table(node, source)))
return
@@ -748,29 +807,51 @@ def extract_go(path: Path) -> dict:
walk(root)
# A type carries both markers, as in the tree-sitter engine: `_callable_class` is
# the narrowing, not a separate kind.
# the narrowing, not a separate kind. A type also carries its import path from go.mod:
# a `pkg.T` receiver binds only to a `T` declared at the path the caller imports `pkg`
# from, and on an incremental rebuild an unchanged declaring file reaches the resolver
# only as its nodes.
package_path = _go_import_path_for_file(path.absolute(), path.absolute().parent)
for n in nodes:
if n["id"] in callable_nids or n["id"] in callable_class_nids:
n["_callable"] = True
if n["id"] in callable_class_nids:
n["_callable_class"] = True
if package_path:
n["_go_package_path"] = package_path
if n["id"] in interface_nids:
n["metadata"] = {"language": "go", "kind": "interface"}
# The field types of the structs this file declares ride on the file node, keyed by
# struct id, so a method in a sibling file can type `s.field` (#3368). Not on the
# struct node: every file holding a method of the struct emits that id too, so an
# incremental rebuild of a method file would shadow the declaring file's copy.
struct_fields = {
type_symbol_nid(name): dict(sorted(fields.items()))
for name, fields in _go_struct_field_types(root, source).items()
}
# A `pkg.T` field is stored as `<import path>.T`: the method file reading it may not
# import `pkg` at all, so the qualifier is settled by this file's imports.
struct_fields: dict[str, dict[str, str]] = {}
for name, fields in _go_struct_field_types(root, source).items():
typed: dict[str, str] = {}
for field, type_name in fields.items():
alias, dot, bare = type_name.partition(".")
if not dot:
typed[field] = type_name
elif alias in go_imported_pkgs:
typed[field] = f"{go_imported_pkgs[alias]}.{bare}"
if typed:
struct_fields[type_symbol_nid(name)] = dict(sorted(typed.items()))
if struct_fields:
file_node = next(n for n in nodes if n["id"] == file_nid)
file_node["_go_fields"] = dict(sorted(struct_fields.items()))
type_table = _go_receiver_type_table(root, source)
package_types = _go_receiver_type_table(root, source, package_only=True)
local_type_names = {n["label"] for n in nodes if n["id"] in callable_class_nids}
method_nids = {e["target"] for e in edges if e["relation"] == "method"}
label_to_nid: dict[str, str] = {}
for n in nodes:
if n["id"] in method_nids:
continue
raw = n["label"]
normalised = raw.strip("()").lstrip(".")
label_to_nid[normalised] = n["id"]
@@ -779,9 +860,17 @@ def extract_go(path: Path) -> dict:
raw_calls: list[dict] = []
def walk_calls(node, caller_nid: str, self_name: str | None,
self_type: str | None, scope_types: dict[str, str]) -> None:
self_type: str | None, scope_types: dict[str, str | None]) -> None:
if node.type in ("function_declaration", "method_declaration"):
return
if node.type in (
"block", "if_statement", "for_statement", "expression_switch_statement",
"type_switch_statement", "select_statement", "expression_case", "type_case",
"communication_case", "default_case", "func_literal",
):
scope_types = scope_types.copy()
if node.type == "func_literal":
scope_types.update(_go_receiver_type_table(node, source))
if node.type == "call_expression":
func_node = node.child_by_field_name("function")
callee_name: str | None = None
@@ -808,17 +897,29 @@ def extract_go(path: Path) -> dict:
import_path = go_imported_pkgs[receiver_name]
elif operand is not None and operand.type == "identifier":
member_receiver = receiver_name
if self_name and receiver_name == self_name:
member_receiver_type = self_type
else:
member_receiver_type = scope_types.get(receiver_name)
member_receiver_type = scope_types.get(receiver_name)
if receiver_name not in scope_types and receiver_name in local_type_names:
member_receiver_type = receiver_name
elif operand is not None and operand.type == "parenthesized_expression":
expression = operand
while (expression.type == "parenthesized_expression"
and expression.named_children):
expression = expression.named_children[0]
if (expression.type == "unary_expression"
and _read_text(expression, source).startswith("*")):
expression = expression.child_by_field_name("operand")
name = _read_text(expression, source) if expression is not None else ""
if name in local_type_names and name not in scope_types:
member_receiver = name
member_receiver_type = name
elif operand is not None and operand.type == "selector_expression":
# `s.logger.Log()` names the receiver by the field only when `s` is
# this method's own receiver; any other head could be a package or
# a variable whose type the flat table does not know.
inner = operand.child_by_field_name("operand")
if (self_name and inner is not None and inner.type == "identifier"
and _read_text(inner, source) == self_name):
and _read_text(inner, source) == self_name
and scope_types.get(self_name) == self_type):
member_receiver = _read_text(
operand.child_by_field_name("field"), source)
field_owner = self_type
@@ -831,8 +932,9 @@ def extract_go(path: Path) -> dict:
# of raw_calls, so the cross-file pass cannot bind it either.
callee_name = None
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
# Never resolve an imported selector through a bare local name.
tgt_nid = None if import_path else label_to_nid.get(callee_name)
# 成员调用必须按接收者类型解析;裸名不能证明方法属于该接收者。
tgt_nid = (None if import_path or is_member_call
else label_to_nid.get(callee_name))
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
@@ -860,13 +962,10 @@ def extract_go(path: Path) -> dict:
# `is_member_call` plus `receiver` without checking the language,
# so a Go name placed there binds to their types in a mixed corpus.
"member_receiver": member_receiver,
# The enclosing function's own receiver and parameters/locals, whose
# declarations are in scope here; the flat table is the fallback for
# a struct field, and must not answer a name this scope rebinds.
"receiver_type": member_receiver_type,
# The struct whose field `member_receiver` is, for `s.field.M()`:
# the struct may be declared in another file of the package, where
# this file's flat table cannot see its fields.
"receiver_bound": not field_owner and member_receiver in scope_types,
# Field ownership remains explicit when the struct is declared
# in a sibling file of the package.
"field_owner": field_owner,
"import_path": import_path,
"source_file": str_path,
@@ -876,17 +975,33 @@ def extract_go(path: Path) -> dict:
# `r.Get("/p", s.Handle)`) is how Go registers a handler or callback. It is
# not a call here, so it never reached the branch above and the method had
# no caller. Record it for the member-call resolver as an indirect call
# through the receiver's declared type (#1566).
# through the receiver's declared type (#1566). `s.field.Handle` is typed
# through the field, as a direct `s.field.M()` is, only when `s` is this
# method's own receiver.
args = node.child_by_field_name("arguments")
for arg in args.children if args is not None else ():
if arg.type != "selector_expression":
continue
operand = arg.child_by_field_name("operand")
field = arg.child_by_field_name("field")
if operand is None or field is None or operand.type != "identifier":
if operand is None or field is None:
continue
name = _read_text(operand, source)
if name in go_imported_pkgs:
arg_field_owner: str | None = None
if operand.type == "identifier":
name = _read_text(operand, source)
if name in go_imported_pkgs:
continue
arg_receiver_type = scope_types.get(name)
elif operand.type == "selector_expression":
inner = operand.child_by_field_name("operand")
if not (self_name and inner is not None and inner.type == "identifier"
and _read_text(inner, source) == self_name
and scope_types.get(self_name) == self_type):
continue
name = _read_text(operand.child_by_field_name("field"), source)
arg_receiver_type = None
arg_field_owner = self_type
else:
continue
raw_calls.append({
"caller_nid": caller_nid,
@@ -897,14 +1012,17 @@ def extract_go(path: Path) -> dict:
"language": "go",
"receiver": None,
"member_receiver": name,
"receiver_type": self_type if self_name and name == self_name
else scope_types.get(name),
"receiver_type": arg_receiver_type,
"receiver_bound": name in scope_types if not arg_field_owner else False,
"field_owner": arg_field_owner,
"import_path": None,
"source_file": str_path,
"source_location": f"L{arg.start_point[0] + 1}",
})
for child in node.children:
walk_calls(child, caller_nid, self_name, self_type, scope_types)
if child.type in ("short_var_declaration", "var_spec", "range_clause"):
scope_types.update(_go_receiver_type_table(child, source))
for caller_nid, body_node, self_name, self_type, scope_types in function_bodies:
walk_calls(body_node, caller_nid, self_name, self_type, scope_types)
@@ -921,5 +1039,5 @@ def extract_go(path: Path) -> dict:
"edges": clean_edges,
"raw_calls": raw_calls,
"go_imports": dict(go_imported_pkgs),
"go_type_table": {"path": str_path, "table": type_table},
"go_type_table": {"path": str_path, "table": type_table, "package_vars": package_types},
}
+195 -48
View File
@@ -26,16 +26,29 @@ _MD_INLINE_LINK_RE = re.compile(
r')\)')
_MD_REF_DEF_RE = re.compile(
r'^\s{0,3}\[[^\]]+\]:\s*(?:<([^<>\n]+)>(?=\s*(?:["\'(]|$))|<?([^\s>]+)>?)')
r'^\s{0,3}\[([^\]]+)\]:\s*(?:<([^<>\n]+)>(?=\s*(?:["\'(]|$))|<?([^\s>]+)>?)')
# Reference-style link uses: [text][label] or [label][]. The label resolves to
# a separate definition (`[label]: target`), so the use — not the definition —
# carries the citation evidence for its section (#4804).
_MD_REF_LINK_RE = re.compile(r'(?<!\!)\[([^\]]*)\]\[([^\]]*)\]')
_MD_WIKILINK_RE = re.compile(r'(?<!\!)\[\[([^\]|#]+?)(?:\\?\|[^\]]*|#[^\]]*)?\]\]')
# Document extensions a Markdown link may point at for a `references` edge, and
# the extensions the Obsidian wikilink index covers.
_MD_LINKABLE_EXTS = {".md", ".mdx", ".qmd", ".markdown", ".rst", ".txt"}
# Source files can be linked as citations and resolved to references edges (#4804).
_MD_CITEABLE_EXTS = _MD_LINKABLE_EXTS | CODE_EXTENSIONS
# Inline code spans, single or double backtick delimited. Fenced blocks are
# skipped before this runs, so a span here is prose citing a symbol by name.
_MD_CODE_SPAN_RE = re.compile(r'(?<!`)(`+)(?!`)(.+?)(?<!`)\1(?!`)')
# A code span naming a file path (e.g. `graphify/build.py`, `setup.py`).
_MD_FILE_SPAN_RE = re.compile(r'^([A-Za-z0-9_./\-]+\.([A-Za-z0-9]+))$')
# The two mention grammars a code span can carry. A path-qualified mention
# (``src/pkg/mod.py::Widget::render``) names the defining file and a
# ``::``-separated symbol chain, exactly as pytest node ids and cite-lint
@@ -48,6 +61,15 @@ _MD_PATH_MENTION_RE = re.compile(
_MD_BARE_MENTION_RE = re.compile(
r'^(?:[A-Za-z_]\w*\.)*([A-Za-z_]\w*)(?:\(\))?$'
)
# The namespace/member chain the other languages' docs write: ``App\Services\Mailer``
# (PHP namespaces) and ``Mailer::send()`` (PHP, Rust, C++ type-qualified members).
# Each segment is a plain identifier; the separators are ``\`` and ``::`` (#4610).
_MD_NS_MENTION_RE = re.compile(
r'^[A-Za-z_]\w*(?:(?:::|\\)[A-Za-z_]\w*)+(?:\(\))?$'
)
# ``Foo::CONST`` names a constant and ``Foo::class`` a keyword: neither has a
# node to land on, so the chain is not a mention.
_MD_NS_NON_SYMBOL_RE = re.compile(r'^(?:class|[A-Z][A-Z0-9_]*)$')
# An ATX heading (CommonMark): up to three spaces of indent (four is an indented
# code block), 1-6 `#`, then whitespace and the text. An optional closing run of
@@ -300,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``.
@@ -344,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
@@ -377,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:
@@ -394,19 +425,37 @@ def _code_span_mention(span: str) -> "tuple[str | None, list[str]] | None":
m = _MD_PATH_MENTION_RE.match(text)
if m:
return m.group(1), m.group(2).split("::")
if not text.endswith("()"):
fm = _MD_FILE_SPAN_RE.match(text)
if fm and "." + fm.group(2).lower() in CODE_EXTENSIONS:
return text, []
m = _MD_BARE_MENTION_RE.match(text)
if not m:
return None
if "." in text:
# ``a.b.Name`` is a qualified symbol; ``setup.py`` and ``README.md``
# are files. A dotted span whose last segment is a code or document
# extension is the latter. Other file-like spans (``pyproject.toml``)
# classify as a mention and are rejected at resolution, where the
# qualifier ``pyproject`` matches no callable's file or owner.
if "." + m.group(1) in CODE_EXTENSIONS or "." + m.group(1) in DOC_EXTENSIONS:
if m:
if "." in text:
# ``a.b.Name`` is a qualified symbol; ``setup.py`` is a source-file
# citation handled by _MD_FILE_SPAN_RE above (and re-caught here for a
# non-ASCII path). A document name (``README.md``) is not a mention:
# only code files are evidence for a bare mention. Other file-like
# spans (``pyproject.toml``) classify as a mention and are rejected at
# resolution, where the qualifier ``pyproject`` matches no callable.
if "." + m.group(1) in CODE_EXTENSIONS:
return text, []
if "." + m.group(1) in DOC_EXTENSIONS:
return None
return None, text.rstrip("()").split(".")
return None, [m.group(1)]
# ``App\Services\Mailer`` and ``Mailer::send()``: a namespace/member chain,
# split on ``\`` and ``::`` the way the dotted form splits on ``.``. A span
# that is only a namespace root (``App\``) is dropped: it names no symbol.
m = _MD_NS_MENTION_RE.match(text)
if m:
is_call = text.endswith("()")
body = text[:-2] if is_call else text
parts = re.split(r"::|\\", body)
if not is_call and body.endswith("::" + parts[-1]) and _MD_NS_NON_SYMBOL_RE.match(parts[-1]):
return None
return None, text.rstrip("()").split(".")
return None, [m.group(1)]
return None, parts
return None
def extract_markdown(path: Path) -> dict:
@@ -433,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
@@ -446,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
@@ -487,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(),
@@ -498,6 +552,12 @@ def extract_markdown(path: Path) -> dict:
raw_call["path"] = cited_path
if len(names) > 1:
raw_call["qualifiers"] = names[:-1]
if cited_path is None and _MD_NS_MENTION_RE.match(span.strip()):
# A `\`/`::` chain carries its namespace root as a qualifier the way
# a dotted mention does, but a PSR-4 root (`App\`) maps to the scan
# directory and has no path segment: the resolver may drop leading
# qualifiers a candidate cannot account for (#4610).
raw_call["ns_qualified"] = True
raw_calls.append(raw_call)
def add_node(nid: str, label: str, line: int, file_type: str = "document",
@@ -525,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
@@ -581,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.
@@ -619,14 +739,41 @@ def extract_markdown(path: Path) -> dict:
add_edge(parent, h_nid, "contains", line_num)
heading_stack.append((level, h_nid))
# Links in the heading itself belong to this heading.
for m in _MD_INLINE_LINK_RE.finditer(title):
add_link(m.group(1) or m.group(2), line_num, owner=h_nid)
for m in _MD_REF_LINK_RE.finditer(title):
_text, _label = m.group(1), m.group(2)
_label = _label or _text
if _label in ref_defs:
add_link(ref_defs[_label], line_num, owner=h_nid)
for m in _MD_WIKILINK_RE.finditer(title):
add_link(m.group(1), line_num, owner=h_nid, wikilink=True)
# A code span in the heading itself is that heading's mention.
for m in _MD_CODE_SPAN_RE.finditer(title):
add_mention(h_nid, m.group(2), line_num)
continue
# Body prose: a code span cites a symbol on behalf of the enclosing
# heading (the page when the text precedes the first heading).
# Body prose: links and code spans belong to the enclosing heading
# (the page when the text precedes the first heading).
owner = heading_stack[-1][1] if heading_stack else file_nid
for m in _MD_INLINE_LINK_RE.finditer(line_text):
add_link(m.group(1) or m.group(2), line_num, owner=owner)
for m in _MD_REF_LINK_RE.finditer(line_text):
_text, _label = m.group(1), m.group(2)
_label = _label or _text
if _label in ref_defs:
add_link(ref_defs[_label], line_num, owner=owner)
for m in _MD_WIKILINK_RE.finditer(line_text):
add_link(m.group(1), line_num, owner=owner, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
# A definition is not a use. A document definition keeps its
# page-level link edge; a source-file definition creates no
# citation at all — only its uses carry section evidence (#4804).
_url = ref_def.group(2) or ref_def.group(3)
if _url and not _is_code_file_link(_url, source_dir):
add_link(_url, line_num, owner=file_nid)
for m in _MD_CODE_SPAN_RE.finditer(line_text):
add_mention(owner, m.group(2), line_num)
+4 -1
View File
@@ -230,7 +230,10 @@ def extract_r(path: Path) -> dict:
key_node = argument.child_by_field_name("name")
value = argument_value(argument)
key = _read_text(key_node, source) if key_node is not None else ""
if key == "inherit" and value is not None:
# R6Class spells its superclass argument `inherit`; setClass and
# setRefClass both spell the same thing `contains` instead, so a
# `contains = "Base"` S4/R5 class silently lost its inheritance edge.
if key in {"inherit", "contains"} and value is not None:
base_name = string_or_identifier(value).split("$")[-1]
if base_name:
base_id = classes.get(base_name, _make_id("r", "class", base_name))
+483 -90
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":
@@ -1268,6 +1274,7 @@ def _apply_symbol_resolution_facts(
root: Path,
facts: _SymbolResolutionFacts,
resolution_context_nodes: list[dict] | None = None,
raw_calls: list[dict] | None = None,
) -> None:
"""Apply language-provided import/export/use facts to graph edges."""
if not (
@@ -1280,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}
@@ -1388,6 +1398,13 @@ def _apply_symbol_resolution_facts(
continue
declared.setdefault((node_path, normalize_id(bare)), node["id"])
node_by_id = {node.get("id"): node for node in nodes}
refs_by_source: dict[Path, list[dict]] = {}
for edge in edges:
if edge.get("relation") != "references":
continue
edge_source = _js_source_path(str(edge.get("source_file") or ""), root)
if edge_source is not None:
refs_by_source.setdefault(edge_source, []).append(edge)
for fact in facts.imports:
if effective_suffix(fact.file_path).lower() not in (
".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"
@@ -1403,11 +1420,7 @@ def _apply_symbol_resolution_facts(
)
if not target_nid:
continue
for edge in edges:
if _js_source_path(str(edge.get("source_file") or ""), root) != source_path:
continue
if edge.get("relation") != "references":
continue
for edge in refs_by_source.get(source_path, ()):
if edge.get("target") == target_nid:
continue
node = node_by_id.get(edge.get("target"))
@@ -1630,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.
@@ -1687,6 +1718,55 @@ def _apply_symbol_resolution_facts(
import_fact.file_path,
)
if raw_calls and any(
fact.imported_name == "default"
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
for fact in facts.imports
):
default_imports = {
(_resolve_cached(fact.file_path), fact.local_name): _resolve_cached(fact.target_path)
for fact in facts.imports
if fact.imported_name == "default"
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
}
member_nodes: dict[tuple[Path, str, str], set[str]] = {}
fresh_paths = {_resolve_cached(path) for path in paths}
for node in nodes + [
node for node in resolution_context_nodes or []
if _js_source_path(str(node.get("source_file", "")), root) not in fresh_paths
]:
if not node.get("_callable"):
continue
source_path = _js_source_path(str(node.get("source_file", "")), root)
if source_path is None:
continue
key = (source_path, str(node.get("label", "")), str(node.get("source_location", "")))
member_nodes.setdefault(key, set()).add(str(node["id"]))
default_members: dict[Path, dict[str, tuple[str, str]]] = {}
for call in raw_calls:
if (not call.get("is_member_call") or call.get("_js_receiver_shadowed")
or call.get("_js_construct") or call.get("ts_this_field")):
continue
source_path = _js_source_path(str(call.get("source_file", "")), root)
if source_path is None:
continue
target_path = default_imports.get((source_path, str(call.get("receiver") or "")))
if target_path is None:
continue
if target_path not in default_members:
default_members[target_path] = _js_default_object_members(target_path)
member = default_members[target_path].get(str(call.get("callee") or ""))
if member is None:
continue
targets = member_nodes.get((target_path, *member), set())
if len(targets) != 1:
continue
add_edge(
call["caller_nid"], next(iter(targets)), "calls", "call",
int(str(call["source_location"]).removeprefix("L")),
Path(call["source_file"]), target_file=str(target_path),
)
# The structural extractor names the imported symbol on the immediate barrel,
# which defines nothing, so its edge dangles and build mints an external stub
# beside the edge the loop above added to the defining symbol (#4486). Drop
@@ -1815,6 +1895,48 @@ def _apply_symbol_resolution_facts(
# survives, and the file id is exactly what the #2231 remap
# canonicalizes — or drop it when no file node id is available.
owned = {str(n.get("id")) for n in nodes}
def _collision_aware(source_id: str, file_path: Path, line: int) -> str:
"""The declaration node a top-level ``def``'s call actually belongs to.
``make_id`` strips the underscore edges off each part, so ``_main`` and
``main`` mint one plain id. The engine salts the colliding pair apart
(#3302) and leaves only the unique public spelling — ``main()`` — on the
plain id, while a ``def`` collected by name here can only carry the plain
id. So every call inside ``_main`` was being credited to ``main`` (#4994).
The declarations sharing that plain id sit on distinct lines, so the one
enclosing the call line is the caller. Anything the line cannot settle
(no candidates, or several) keeps ``source_id`` unchanged, which is what
this pass did before.
"""
if not any(other.startswith(source_id + "_") for other in owned):
return source_id
candidates = [n for n in nodes if n.get("id") == source_id or (
isinstance(n.get("id"), str)
and n["id"].startswith(source_id + "_")
# Only an underscore-collision salt (`_underscore_salted_nid`, a
# 6-char sha1 hex) is a sibling spelling of the same def. A plain
# alphanumeric suffix is a child node id (`classid_methodname`), so
# matching it would wrongly steal a class member's edge (e.g. a
# type-annotated field's reference) onto a preceding method.
and re.fullmatch(r"[0-9a-f]{6}", n["id"][len(source_id) + 1:]) is not None
and _js_source_path(str(n.get("source_file") or ""), root) == file_path
)]
if len(candidates) < 2:
return source_id
def _start(node: dict) -> int:
try:
return int(str(node.get("source_location") or "").removeprefix("L"))
except ValueError:
return 0
enclosing = [n for n in candidates if _start(n) <= line]
if not enclosing:
return source_id
return str(max(enclosing, key=_start)["id"])
for use_fact in facts.uses:
file_path = _resolve_cached(use_fact.file_path)
target_id = None
@@ -1832,7 +1954,7 @@ def _apply_symbol_resolution_facts(
target_id = symbol_nodes.get((file_path, use_fact.local_name))
if target_id is None:
continue
source_id = use_fact.source_id
source_id = _collision_aware(use_fact.source_id, file_path, use_fact.line)
# Structural walking can omit named-function-local declarations while
# materializing callback-local ones. Only actual node ownership decides
# whether a type relationship has a represented source declaration.
@@ -1908,6 +2030,14 @@ def _js_module_specifier(node, source: bytes) -> str | None:
if child.type == "string":
source_node = child
break
# TS `import x = require("./m")`: the module string sits inside
# import_require_clause, not as a direct child of import_statement
# (same dig as `_import_js` in extract.py).
if child.type == "import_require_clause":
source_node = next(
(sub for sub in child.children if sub.type == "string"), None
)
break
if source_node is None:
return None
raw = _read_text(source_node, source).strip()
@@ -2017,7 +2147,8 @@ def _js_default_export_name(node, source: bytes) -> str | None:
`export default abstract class Foo {}` (name on the `declaration` field) and
`export default Foo` (an identifier on the `value` field). Anonymous defaults
(`export default class {}`, `export default {...}`) have no resolvable symbol
and return None.
and return None; the members of an anonymous default object are resolved
separately by :func:`_js_default_object_members`.
"""
if not any(child.type == "default" for child in node.children):
return None
@@ -2030,6 +2161,47 @@ def _js_default_export_name(node, source: bytes) -> str | None:
return _read_text(value, source)
return None
def _js_default_object_members(path: Path) -> dict[str, tuple[str, str]]:
"""Static methods of a direct default-exported object that resolve to an
existing node. Only members we can bind to a real node are returned."""
parsed = _parse_js_tree(path)
if parsed is None:
return {}
source, root_node = parsed
for node in root_node.named_children:
if node.type != "export_statement" or not any(
child.type == "default" for child in node.children
):
continue
value = node.child_by_field_name("value")
if value is None or value.type != "object":
continue
members: dict[str, tuple[str, str]] = {}
seen: set[str] = set()
for prop in value.named_children:
if prop.type == "comment":
continue
key = prop.child_by_field_name("name") or prop.child_by_field_name("key")
# A spread or computed key can override any method, so do not add an
# edge on the strength of a same-named node alone.
if key is None or key.type not in ("property_identifier", "string"):
return {}
raw_name = _read_text(key, source)
if "\\" in raw_name:
return {}
name = raw_name[1:-1] if key.type == "string" else raw_name
if name in seen:
members.pop(name, None)
continue
seen.add(name)
if prop.type == "method_definition" and not any(
child.type in ("get", "set") for child in prop.children
):
members[name] = (f"{raw_name}()", f"L{prop.start_point[0] + 1}")
return members
return {}
def _js_top_level_function_bodies(path: Path, root_node, source: bytes) -> list[tuple[str, object]]:
bodies: list[tuple[str, object]] = []
stem = _file_stem(path)
@@ -2263,12 +2435,174 @@ def _ts_walk_class_members(class_node, source: bytes, path: Path, class_nid: str
_SymbolUseFact(path, class_nid, name, "references", ctx, m_line)
)
def _js_require_call_and_specifier(value_node, source: bytes):
"""Return ``(call_node, raw_specifier)`` for a literal ``require('...')``
(or ``require('...').x``), else ``None``.
Name-checks the callee the same way ``_require_imports_js`` / ``_js_value_is_require``
do, so a ``factory()`` call is never treated as an import (#4634).
"""
if value_node is None:
return None
node = value_node
if node.type == "member_expression":
node = node.child_by_field_name("object")
if node is None:
return None
if node.type != "call_expression":
return None
fn = node.child_by_field_name("function")
if fn is None or fn.type != "identifier" or _read_text(fn, source) != "require":
return None
args = node.child_by_field_name("arguments")
if args is None:
return None
raw = None
for arg in args.children:
if arg.type == "string":
raw = _read_text(arg, source).strip("'\"` ")
break
if not raw:
return None
return node, raw
def _js_cjs_require_bindings(declarator, source: bytes) -> list[tuple[str, str]]:
"""``(local_name, imported_name)`` for a whole-module ``require`` declarator.
Only ``const/let/var X = require('./m')`` (not ``require('./m').y`` or
``const { X } = require('./m')``). Those other forms already get structural
``imports`` edges from ``_require_imports_js``; minting SymbolImportFacts for
them would also resolve call-uses through the symbol pass and regress the
EXTRACTED ``confidence_score`` path for destructured requires (#4688 / #4634).
Whole-module bindings are recorded as default imports, matching ESM
``import X from './m'``.
"""
value = declarator.child_by_field_name("value")
if value is None or value.type != "call_expression":
return []
req = _js_require_call_and_specifier(value, source)
if req is None:
return []
name_node = declarator.child_by_field_name("name")
if name_node is None or name_node.type != "identifier":
return []
local = _read_text(name_node, source)
if not local:
return []
return [(local, "default")]
def _js_cjs_default_export_local(right, source: bytes) -> str | None:
"""Local name of a ``module.exports = <expr>`` RHS, if resolvable.
Walks through chained assignments (``module.exports = exports = Foo``) to the
final RHS — an intermediate ``exports = …`` left is not the exported binding.
"""
node = right
while node is not None and node.type == "assignment_expression":
node = node.child_by_field_name("right")
if node is None:
return None
if node.type == "identifier":
return _read_text(node, source) or None
if node.type in (
"class", "class_declaration", "function", "function_declaration",
"generator_function", "generator_function_declaration",
):
name_node = node.child_by_field_name("name")
if name_node is not None:
return _read_text(name_node, source) or None
return None
def _js_cjs_export_facts(node, source: bytes, path: Path) -> list[_SymbolExportFact]:
"""Export facts for CommonJS ``module.exports`` / ``exports.X`` assignments.
Whole-module ``module.exports = Name`` is recorded as a default export so a
``const X = require('./m')`` import resolves through the same alias path as
ESM ``import X from './m'`` (#4688). Named property assignments
(``exports.Foo = …`` / ``module.exports.Foo = …``) become named exports.
Bare ``exports = Name`` is intentionally ignored: in CommonJS that only
rebinds the local ``exports`` binding and does not change what ``require()``
returns (unlike ``module.exports = Name``).
"""
if node.type != "expression_statement":
return []
assign = next((c for c in node.children if c.type == "assignment_expression"), None)
if assign is None:
return []
left = assign.child_by_field_name("left")
right = assign.child_by_field_name("right")
if left is None or right is None:
return []
line = node.start_point[0] + 1
left_str = _read_text(left, source)
out: list[_SymbolExportFact] = []
if left_str == "module.exports":
local = _js_cjs_default_export_local(right, source)
if local:
out.append(
_SymbolExportFact(path, "default", line, local_name=local)
)
# Also expose the binding under its own name so a same-named
# ``require`` without a default walk still finds it, and so
# ``module.exports = Generator`` remains visible as ``Generator``.
if local != "default":
out.append(
_SymbolExportFact(path, local, line, local_name=local)
)
elif right.type == "object":
for prop in right.children:
if prop.type == "shorthand_property_identifier":
name = _read_text(prop, source)
if name:
out.append(
_SymbolExportFact(path, name, line, local_name=name)
)
elif prop.type == "pair":
key = prop.child_by_field_name("key")
val = prop.child_by_field_name("value")
if key is None:
continue
exported = _read_text(key, source)
local_name = None
if val is not None and val.type == "identifier":
local_name = _read_text(val, source) or None
if exported:
out.append(
_SymbolExportFact(
path, exported, line, local_name=local_name or exported
)
)
return out
if left.type != "member_expression":
return []
# exports.Foo = ... / module.exports.Foo = ...
obj = left.child_by_field_name("object")
prop = left.child_by_field_name("property")
if obj is None or prop is None:
return []
exported = _read_text(prop, source)
if not exported:
return []
obj_str = _read_text(obj, source)
if obj_str not in ("exports", "module.exports"):
return []
local = _js_cjs_default_export_local(right, source) or exported
out.append(_SymbolExportFact(path, exported, line, local_name=local))
return out
# Node types the whole-tree passes of _collect_js_symbol_resolution_facts
# filter on.
_JS_FACT_NODE_TYPES = frozenset({
"export_statement",
"import_statement",
"lexical_declaration",
"variable_declaration",
"expression_statement",
"class_declaration",
"abstract_class_declaration",
"interface_declaration",
@@ -2283,10 +2617,11 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
if not js_paths:
return
trees: dict[Path, tuple[bytes, object, list]] = {}
# One parse per file, dropped before the next: holding every file's source and syntax tree
# across the passes held the whole corpus (1.9 GB on Next.js). Class-member uses still follow
# all call uses, so every fact list keeps its order.
member_facts = _SymbolResolutionFacts()
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = _parse_js_tree(path)
if parsed is None:
continue
@@ -2295,7 +2630,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
node for node in _walk_js_tree(root_node)
if node.type in _JS_FACT_NODE_TYPES
]
trees[resolved_path] = (source, root_node, indexed)
for node in indexed:
if node.type == "export_statement":
@@ -2304,6 +2638,44 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
_SymbolDeclarationFact(path, name, node.start_point[0] + 1)
)
if node.type == "expression_statement":
facts.exports.extend(_js_cjs_export_facts(node, source, path))
continue
if node.type in ("lexical_declaration", "variable_declaration"):
# CommonJS `const/let/var X = require('./m')` is an import alias,
# not a local declaration. Without a SymbolImportFact here,
# `class A extends X` has nothing to resolve through after #4634
# stopped minting a shadow binding node (#4688).
for child in node.children:
if child.type != "variable_declarator":
continue
bindings = _js_cjs_require_bindings(child, source)
if not bindings:
continue
req = _js_require_call_and_specifier(
child.child_by_field_name("value"), source
)
if req is None:
continue
_call, raw_module = req
target_path = _resolve_js_module_path(raw_module, path.parent)
if target_path is None:
continue
target_path = _resolve_cached(target_path)
line = node.start_point[0] + 1
for local_name, imported_name in bindings:
facts.imports.append(
_SymbolImportFact(
path,
local_name,
target_path,
imported_name,
line,
)
)
continue
if node.type != "import_statement":
continue
raw_module = _js_module_specifier(node, source)
@@ -2334,6 +2706,27 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
node.start_point[0] + 1,
)
)
# TS `import X = require("./m")` — same default-import shape as
# `const X = require("./m")` (#4688).
for child in node.children:
if child.type != "import_require_clause":
continue
local_node = next(
(c for c in child.children if c.type == "identifier"), None
)
if local_node is None:
continue
local_name = _read_text(local_node, source)
if local_name:
facts.imports.append(
_SymbolImportFact(
path,
local_name,
target_path,
"default",
node.start_point[0] + 1,
)
)
for node in indexed:
for alias, target in _js_lexical_aliases(node, source):
@@ -2341,13 +2734,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
_SymbolAliasFact(path, alias, target, node.start_point[0] + 1)
)
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = trees.get(resolved_path)
if parsed is None:
continue
source, _root_node, indexed = parsed
for node in indexed:
if node.type != "export_statement":
continue
@@ -2437,12 +2823,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
)
)
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = trees.get(resolved_path)
if parsed is None:
continue
source, root_node, _indexed = parsed
for source_id, body in _js_top_level_function_bodies(path, root_node, source):
for node in _walk_js_tree(body):
imported_name = _js_call_identifier(node, source)
@@ -2459,12 +2839,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
)
)
for path in js_paths:
resolved_path = _resolve_cached(path)
parsed = trees.get(resolved_path)
if parsed is None:
continue
source, _root_node, indexed = parsed
stem = _file_stem(path)
for node in indexed:
if node.type not in (
@@ -2480,7 +2854,8 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
if not class_name:
continue
class_nid = _make_id(stem, class_name)
_ts_walk_class_members(node, source, path, class_nid, facts)
_ts_walk_class_members(node, source, path, class_nid, member_facts)
facts.uses.extend(member_facts.uses)
@functools.lru_cache(maxsize=2048)
def _parse_python_tree_cached(path_str: str, _mtime_ns: int, _size: int):
@@ -2829,6 +3204,12 @@ def _resolve_python_namespace_dir(module_name: str, current_path: Path, root: Pa
return None
def _python_top_level_function_bodies(path: Path, root_node, source: bytes) -> list[tuple[str, object]]:
"""``(plain caller id, body)`` for every top-level ``def`` in the module.
Deliberately the *unsalted* id: ``_apply_symbol_resolution_facts`` resolves
the caller against the final graph, where the underscore-collision spread
(#3302) is baked into the ids.
"""
bodies: list[tuple[str, object]] = []
stem = _file_stem(path)
for node in root_node.children:
@@ -2859,13 +3240,12 @@ def _collect_python_symbol_resolution_facts(
if not py_paths:
return
trees: dict[Path, tuple[bytes, object]] = {}
# One parse per file, dropped before the next (the same reason as the JS facts above).
for path in py_paths:
parsed = _parse_python_tree(path)
if parsed is None:
continue
source, root_node = parsed
trees[_resolve_cached(path)] = parsed
for node in _walk_python_tree(root_node):
if node.type != "import_from_statement":
@@ -2932,11 +3312,6 @@ def _collect_python_symbol_resolution_facts(
)
)
for path in py_paths:
parsed = trees.get(_resolve_cached(path))
if parsed is None:
continue
source, root_node = parsed
for source_id, body in _python_top_level_function_bodies(path, root_node, source):
for node in _walk_python_tree(body):
imported_name = _python_call_identifier(node, source)
@@ -2960,6 +3335,7 @@ def _augment_symbol_resolution_edges(
root: Path,
ambiguous_python_modules: set[str] | None = None,
resolution_context_nodes: list[dict] | None = None,
raw_calls: list[dict] | None = None,
) -> None:
facts = _SymbolResolutionFacts()
_collect_js_symbol_resolution_facts(paths, facts)
@@ -2971,7 +3347,10 @@ def _augment_symbol_resolution_edges(
_apply_symbol_resolution_facts(
paths, nodes, edges, root, facts,
resolution_context_nodes=resolution_context_nodes,
raw_calls=raw_calls,
)
elif raw_calls:
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts, raw_calls=raw_calls)
else:
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts)
@@ -3042,6 +3421,13 @@ def _resolve_cross_file_imports(
node_by_id = {node["id"]: node for node in all_nodes if node.get("id")} if all_nodes else {}
repointed_from: set[str] = set()
TYPE_REPOINT_RELATIONS = frozenset({"references", "inherits", "implements", "extends"})
# The #3252 repoint below only ever touches an edge whose source_file belongs
# to the importing file. Index the edges by source_file once, when the first
# file needs it, instead of scanning all of them per file (files x edges,
# #4980). Each entry keeps the edge's position in all_edges, so a file's
# edges are visited in the same order as before.
edges_by_source: dict[object, list[tuple[int, dict]]] = {}
edges_indexed = False
for file_result, path in zip(per_file, paths):
str_path = str(path)
@@ -3219,9 +3605,15 @@ def _resolve_cross_file_imports(
# Repoint AST type-reference and inheritance edges from sourceless stubs
# to the exact imported target definition (#3252).
if all_edges and import_targets:
for edge in all_edges:
if edge.get("source_file") not in file_srcs:
continue
if not edges_indexed:
for position, edge in enumerate(all_edges):
edges_by_source.setdefault(edge.get("source_file"), []).append((position, edge))
edges_indexed = True
file_edges = sorted(
(entry for src in file_srcs for entry in edges_by_source.get(src, ())),
key=lambda entry: entry[0],
)
for _, edge in file_edges:
if edge.get("relation") not in TYPE_REPOINT_RELATIONS:
continue
tgt = edge.get("target")
@@ -3520,9 +3912,9 @@ def _resolve_cross_file_java_imports(
language = Language(tsjava.language())
parser = Parser(language)
# Pre-pass: declared package per source_file string (and parsed trees for
# pass 2, so each file is only parsed once).
parsed: dict[str, tuple[bytes, object]] = {}
# Pre-pass: declared package per source_file string and each file's imports,
# so pass 2 needs no syntax tree: holding every tree held the whole corpus.
imports_by_path: dict[str, list[tuple[str, str, int]]] = {}
pkg_by_src: dict[str, str] = {}
for path, file_result in zip(paths, per_file):
try:
@@ -3530,7 +3922,7 @@ def _resolve_cross_file_java_imports(
tree = parser.parse(source)
except Exception:
continue
parsed[str(path)] = (source, tree)
imports_by_path[str(path)] = _java_import_rows(tree.root_node, source)
pkg = ""
for child in tree.root_node.children:
if child.type == "package_declaration":
@@ -3577,55 +3969,56 @@ def _resolve_cross_file_java_imports(
seen_pairs: set[tuple[str, str]] = set()
for path in paths:
file_nid = _make_id(str(path))
entry = parsed.get(str(path))
if entry is None:
continue
source, tree = entry
def walk(n) -> None:
if n.type == "import_declaration":
raw = _read_text(n, source).strip()
body = raw[len("import"):].strip().rstrip(";").strip()
if body.startswith("static "):
body = body[len("static "):].strip()
if body.endswith(".*"):
return
parts = body.split(".")
if not parts:
return
last = parts[-1]
imp_pkg = ".".join(parts[:-1])
if last and last[0].islower() and len(parts) >= 2:
last = parts[-2]
imp_pkg = ".".join(parts[:-2])
at_line = n.start_point[0] + 1
for tgt_nid, tgt_pkg in name_to_ids.get(last, []):
if tgt_nid == file_nid:
continue
if not _pkg_matches(imp_pkg, tgt_pkg):
continue
key = (file_nid, tgt_nid)
if key in seen_pairs:
continue
seen_pairs.add(key)
new_edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str(path),
"source_location": f"L{at_line}",
"weight": 1.0,
})
for child in n.children:
walk(child)
walk(tree.root_node)
for last, imp_pkg, at_line in imports_by_path.get(str(path), ()):
for tgt_nid, tgt_pkg in name_to_ids.get(last, []):
if tgt_nid == file_nid:
continue
if not _pkg_matches(imp_pkg, tgt_pkg):
continue
key = (file_nid, tgt_nid)
if key in seen_pairs:
continue
seen_pairs.add(key)
new_edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str(path),
"source_location": f"L{at_line}",
"weight": 1.0,
})
return new_edges
def _java_import_rows(root_node, source: bytes) -> list[tuple[str, str, int]]:
"""Each non-wildcard import in a Java tree as (name, package, line), in source order."""
rows: list[tuple[str, str, int]] = []
def walk(n) -> None:
if n.type == "import_declaration":
raw = _read_text(n, source).strip()
body = raw[len("import"):].strip().rstrip(";").strip()
if body.startswith("static "):
body = body[len("static "):].strip()
if body.endswith(".*"):
return
parts = body.split(".")
last = parts[-1]
imp_pkg = ".".join(parts[:-1])
if last and last[0].islower() and len(parts) >= 2:
last = parts[-2]
imp_pkg = ".".join(parts[:-2])
rows.append((last, imp_pkg, n.start_point[0] + 1))
for child in n.children:
walk(child)
walk(root_node)
return rows
def _go_import_path_for_file(
source_file: str | Path,
root: Path,
+136 -5
View File
@@ -201,6 +201,48 @@ _RUST_PRIMITIVE_TYPES: frozenset[str] = frozenset({
})
# Macros whose arguments are ordinary Rust expressions. A DSL macro (`table!`,
# `quote!`, `html!`, nom combinators) also writes `name(...)` but means
# something else by it, so only these are scanned for calls.
_RUST_EXPRESSION_MACROS = frozenset({
"assert", "assert_eq", "assert_ne", "debug_assert", "debug_assert_eq",
"debug_assert_ne", "dbg", "eprint", "eprintln", "format", "format_args",
"panic", "print", "println", "todo", "unimplemented", "unreachable", "vec",
"write", "writeln", "debug", "error", "info", "trace", "warn",
})
def _rust_macro_arg_calls(token_tree) -> list[tuple[str, int]]:
"""Bare `f(...)` calls written inside a macro's arguments.
Tree-sitter keeps macro arguments as a flat token tree, so `println!("{}", f(x))`
has no call_expression: it is an `identifier` followed by a `(` token tree.
A name after `.` or `::` is a method or path call and is left out, as is a
name followed by `!` (a nested macro, which is its own macro_invocation).
"""
found: list[tuple[str, int]] = []
stack = [token_tree]
while stack:
tree = stack.pop()
children = tree.children
for i, child in enumerate(children):
if child.type == "token_tree":
stack.append(child)
continue
if child.type != "identifier" or i + 1 >= len(children):
continue
nxt = children[i + 1]
if nxt.type != "token_tree" or not nxt.children or nxt.children[0].type != "(":
continue
if i > 0 and children[i - 1].type in (".", "::", "fn", "$", "#"):
continue
name = child.text.decode("utf-8", errors="replace") if child.text else ""
if name:
found.append((name, child.start_point[0] + 1))
found.sort(key=lambda item: item[1])
return found
def _rust_qualifier_type(path_node, source: bytes) -> str | None:
"""The type a `Type::f()` call is qualified by, or None for a module path.
@@ -286,6 +328,17 @@ def extract_rust(path: Path) -> dict:
# are resolved through their own registry rather than the function/type
# label_to_nid to avoid cross-binding.
macro_nids_by_name: dict[str, str] = {}
# `mod m { .. }` blocks declared in this file, so a `m::f()` call can bind
# in-file; `mod m;` declares a module that lives in another file.
inline_mods: set[str] = set()
_mod_stack = [root]
while _mod_stack:
_n = _mod_stack.pop()
if _n.type == "mod_item" and _n.child_by_field_name("body") is not None:
_name = _n.child_by_field_name("name")
if _name is not None:
inline_mods.add(_read_text(_name, source))
_mod_stack.extend(_n.children)
# (bare impl type, method name) -> the method nodes this file's `impl` blocks
# define, so an in-file `Type::f()` / `self.f()` binds to a method of that type.
@@ -851,6 +904,7 @@ def extract_rust(path: Path) -> dict:
seen_call_pairs: set[tuple[str, str]] = set()
raw_calls: list[dict] = []
macro_arg_edges: list[dict] = []
def walk_calls(
node,
@@ -884,10 +938,48 @@ def extract_rust(path: Path) -> dict:
"source_location": f"L{line}",
"weight": 1.0,
})
# Fall through to the generic child recursion below rather than
# returning, preserving the prior traversal of the invocation's
# subtree (its arguments are a raw token tree, so this neither adds
# nor drops any nested edges relative to before).
# A call inside the arguments is only a token pattern, not a parsed
# call: bind it in-file as INFERRED, or hand it to the cross-file pass.
args = next((c for c in node.children if c.type == "token_tree"), None)
invoked = macro_node.child_by_field_name("name") if (
macro_node is not None and macro_node.type == "scoped_identifier") else macro_node
if args is None or invoked is None or (
_read_text(invoked, source) not in _RUST_EXPRESSION_MACROS):
args = None
for callee_name, line in _rust_macro_arg_calls(args) if args is not None else ():
if (
callee_name[:1].isupper()
or callee_name in _LANGUAGE_BUILTIN_GLOBALS
or callee_name in _RUST_BUILTIN_TYPES
or callee_name.lower() in _RUST_TRAIT_METHOD_BLOCKLIST
):
continue
tgt_nid = label_to_nid.get(callee_name)
if tgt_nid in type_nids:
continue
if tgt_nid:
if tgt_nid != caller_nid:
macro_arg_edges.append({
"source": caller_nid,
"target": tgt_nid,
"relation": "calls",
"context": "macro_argument_call",
"confidence": "INFERRED",
"confidence_score": 0.85,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
continue
raw_calls.append({
"caller_nid": caller_nid,
"callee": callee_name,
"is_member_call": False,
"source_file": str_path,
"source_location": f"L{line}",
})
# Fall through to the generic child recursion below; the token tree
# holds no call_expression, so nothing is counted twice.
if node.type == "call_expression":
func_node = node.child_by_field_name("function")
callee_name: str | None = None
@@ -938,6 +1030,16 @@ def extract_rust(path: Path) -> dict:
tgt_nid = named if named in type_nids else None
elif is_member_call:
tgt_nid = method_label_to_nid.get(callee_name)
elif is_scoped_call:
# `m::f()` names module m. It is in this file only for
# `self::f()` or an inline `mod m { .. }` declared here; any
# other module lives in another file, so the bare-name match
# would bind `crate::b::helper()` to this file's own helper.
path_node = func_node.child_by_field_name("path") if func_node else None
qual = _read_text(path_node, source) if path_node is not None else ""
head = qual.split("::")[-1].strip()
tgt_nid = label_to_nid.get(callee_name) if (
qual == "self" or head in inline_mods) else None
else:
tgt_nid = label_to_nid.get(callee_name)
if tgt_nid and tgt_nid != caller_nid:
@@ -956,7 +1058,29 @@ def extract_rust(path: Path) -> dict:
"source_location": f"L{line}",
"weight": 1.0,
})
elif not is_scoped_call and callee_name.lower() not in _RUST_TRAIT_METHOD_BLOCKLIST:
elif is_scoped_call:
# A module-qualified call (`crate::m::f()`, `m::f()`, `super::m::f()`)
# goes to the cross-file pass with its qualifier, which binds it only
# when the qualifier matches the candidate's module path and exactly
# one candidate survives. Bare last-segment lookup stays off (#908).
qual_node = func_node.child_by_field_name("path")
qualifier = _read_text(qual_node, source) if qual_node else ""
# `use std::fs; fs::read()` names std's fs, never a local `fs.rs`.
first_seg = qualifier.split("::", 1)[0].split("<", 1)[0].strip()
roots = use_roots.get(first_seg, {"crate"})
if not roots <= {"crate", "super", "self"}:
qualifier = ""
if qualifier:
raw_calls.append({
"caller_nid": caller_nid,
"callee": callee_name,
"is_member_call": False,
"is_scoped_call": True,
"scope_qualifier": qualifier,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
elif callee_name.lower() not in _RUST_TRAIT_METHOD_BLOCKLIST:
rc_entry = {
"caller_nid": caller_nid,
"callee": callee_name,
@@ -974,6 +1098,13 @@ def extract_rust(path: Path) -> dict:
for caller_nid, body_node, impl_type, impl_key in function_bodies:
walk_calls(body_node, caller_nid, impl_type, impl_key)
# Added last: a parsed call to the same target in the same function keeps
# its EXTRACTED edge instead of being deduped behind the token-pattern one.
for edge in macro_arg_edges:
pair = (edge["source"], edge["target"])
if pair not in seen_call_pairs:
seen_call_pairs.add(pair)
edges.append(edge)
for node in nodes:
if not node["source_file"] and node["label"] in use_roots:
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -79,13 +79,17 @@ def _scope_id(directory: str) -> str:
def prepare_terraform(result: dict, path: Path, root: Path) -> None:
"""Make cached directory-scoped IDs portable before the common merge passes."""
"""Make cached directory-scoped IDs portable before the common merge passes.
Consume the internal scope metadata even when the file is outside root.
"""
directory = path.parent.resolve()
old = result.pop("_terraform_scope", _scope_id(directory.as_posix()))
try:
relative = directory.relative_to(root).as_posix()
except ValueError:
return
old, new = _scope_id(directory.as_posix()), _scope_id(relative)
new = _scope_id(relative)
for node in result.get("nodes", []):
nid = node["id"]
if nid.startswith(old + "_"):
@@ -508,4 +512,4 @@ def extract_terraform(path: Path) -> dict:
nodes_by_id[owner]["attributes"] = attrs
_collect_refs(blk_body, owner, "references")
return {"nodes": nodes, "edges": edges}
return {"nodes": nodes, "edges": edges, "_terraform_scope": scope}
+58 -6
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.
@@ -119,7 +164,11 @@ def _mapping_pairs(node: Any) -> list[tuple[str, Any, Any]]:
for key_node, value_node in node.value:
if key_node.tag == _MERGE_TAG:
sources = value_node.value if isinstance(value_node, yaml.SequenceNode) else [value_node]
for src in sources:
# Per the YAML merge spec, an earlier map in a ``<<: [a, b]`` sequence
# overrides a later one. Because the dict below is last-write-wins, feed
# the sources in reverse so the earliest keeps the final value/line —
# matching PyYAML's ``flatten_mapping`` (which reverses the submerge).
for src in reversed(sources):
if isinstance(src, yaml.MappingNode):
merged.extend(_mapping_pairs(src))
elif isinstance(key_node, yaml.ScalarNode):
@@ -135,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
@@ -152,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
+129
View File
@@ -0,0 +1,129 @@
"""Member-level interface dispatch for Go.
`d.provider.GetWithDataSource()` where `provider` is a `pluginContextProvider`
resolves to the interface's own `.GetWithDataSource()` requirement, because that
is what the call site names. The concrete `Provider.GetWithDataSource()` is a
separate node, and nothing joins the two, so a directed walk stops at the
interface — the Go twin of the C# gap #3003 closed.
C# and Swift feed `graphify.interface_dispatch` with the `implements` edges
their extractors read off a declaration. Go has no such declaration: a type
implements an interface by having its methods. So this pass infers the pairs
from method sets and hands them to the shared mechanism, which does the rest
(per-method `dispatches_to` at INFERRED, 0.85 / 0.75 / 0.65 by implementer
count, the single-owner guard). The inferred `implements` pairs only feed the
mechanism; they are not added to the graph.
A named type T implements interface I here when T's methods (value and
pointer receivers alike: the extractor hangs both off T's node) include every
method name I requires. Names only: method nodes carry no signature, and Go has
no overloads to tell apart. The guards:
- Both ends are declared in a `.go` file, as in the C# and Swift passes.
- An interface with no methods (`interface{}`, `any`) or only a type set is
skipped: every type satisfies the first, and the second is a generics
constraint, not something a call goes through.
- An interface that embeds another is used only when every embedded interface
is declared in the corpus, with its methods counted in. `io.Reader` and
other external interfaces have unknown methods, so such an interface is
skipped rather than matched on part of its method set.
- An unexported method name (`run()`) can only be implemented in the
interface's own package, so only types in the same directory count.
- An interface matched by more than `_MAX_IMPLICIT_IMPLEMENTERS` types is
skipped. Name-only matching makes a lone common name (`Close`, `String`)
match unrelated types, and past this many the edges say little. The builtin
`error` and `fmt.Stringer` are not in the corpus, so they never match; a
local redeclaration of either is matched like any other interface.
Struct embedding is not followed: a type whose method comes from an embedded
field does not own that method node, so it is not matched.
"""
from __future__ import annotations
from pathlib import PurePath
from graphify.interface_dispatch import (
declared_in,
method_label,
resolve_interface_dispatch,
)
_GO_SUFFIXES = (".go",)
# Past this many structural implementers an interface is skipped, not truncated:
# which ten to keep would be arbitrary.
_MAX_IMPLICIT_IMPLEMENTERS = 10
def _is_go_interface(node: dict | None) -> bool:
meta = (node or {}).get("metadata")
return isinstance(meta, dict) and meta.get("language") == "go" and meta.get("kind") == "interface"
def resolve_go_interface_dispatch(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link each Go interface method to the methods of every type that satisfies the interface."""
interfaces = {n.get("id"): n for n in all_nodes if _is_go_interface(n) and declared_in(n, _GO_SUFFIXES)}
if not interfaces:
return
node_by_id = {n.get("id"): n for n in all_nodes}
method_names: dict[str, set[str]] = {}
embeds: dict[str, set[str]] = {}
type_set_constrained: set[str] = set()
for e in all_edges:
rel, source = e.get("relation"), e.get("source")
if rel == "method":
mnode = node_by_id.get(e.get("target"))
if mnode is not None and declared_in(mnode, _GO_SUFFIXES) and method_label(mnode):
method_names.setdefault(source, set()).add(method_label(mnode))
elif source in interfaces and rel == "embeds":
embeds.setdefault(source, set()).add(e.get("target"))
elif source in interfaces and rel == "references" and e.get("context") == "type_constraint":
type_set_constrained.add(source)
def required(iface: str, visiting: frozenset[str] = frozenset()) -> set[str] | None:
# None: the method set is not fully known (an embedded interface outside
# the corpus, or an embedding cycle, which Go rejects anyway).
names = set(method_names.get(iface, ()))
for embedded in embeds.get(iface, ()):
if embedded not in interfaces or embedded in visiting:
return None
inner = required(embedded, visiting | {iface})
if inner is None:
return None
names |= inner
return names
candidates = {
owner: names for owner, names in method_names.items()
if owner not in interfaces and declared_in(node_by_id.get(owner), _GO_SUFFIXES)
}
inferred: list[dict] = []
for iface, iface_node in interfaces.items():
if iface in type_set_constrained or not method_names.get(iface):
continue
needed = required(iface)
if not needed:
continue
package = PurePath(str(iface_node.get("source_file"))).parent
same_package_only = any(not name[:1].isupper() for name in needed)
impls = [
owner for owner, names in candidates.items()
if needed <= names
and (not same_package_only
or PurePath(str(node_by_id[owner].get("source_file"))).parent == package)
]
if 0 < len(impls) <= _MAX_IMPLICIT_IMPLEMENTERS:
inferred.extend({"source": impl, "target": iface, "relation": "implements"} for impl in impls)
if not inferred:
return
# The shared resolver reads `implements` from the edge list it is given and
# appends its `dispatches_to` edges to that list; keep only the latter.
edges = all_edges + inferred
resolve_interface_dispatch(per_file, all_nodes, edges, suffixes=_GO_SUFFIXES)
all_edges.extend(edges[len(all_edges) + len(inferred):])
+4 -4
View File
@@ -405,8 +405,8 @@ def _detached_launch(rebuild_body: str) -> str:
# absolute while --git-common-dir is the relative ".git", and a raw compare would
# false-positive on the PRIMARY checkout and wrongly skip it.
_WORKTREE_GUARD = """\
_GFY_GITDIR=$(cd "$(git rev-parse --git-dir 2>/dev/null)" 2>/dev/null && pwd)
_GFY_COMMONDIR=$(cd "$(git rev-parse --git-common-dir 2>/dev/null)" 2>/dev/null && pwd)
_GFY_GITDIR=$(CDPATH= cd "$(git rev-parse --git-dir 2>/dev/null)" 2>/dev/null && pwd)
_GFY_COMMONDIR=$(CDPATH= cd "$(git rev-parse --git-common-dir 2>/dev/null)" 2>/dev/null && pwd)
if [ -n "$_GFY_COMMONDIR" ] && [ "$_GFY_GITDIR" != "$_GFY_COMMONDIR" ]; then
exit 0
fi
@@ -776,7 +776,7 @@ def _rev_parse_path(root: Path, flag: str) -> Path | None:
try:
res = _sp.run(
["git", "-C", str(root), "rev-parse", flag],
capture_output=True, text=True,
capture_output=True, text=True, encoding="utf-8",
)
except (OSError, FileNotFoundError):
return None
@@ -838,7 +838,7 @@ def _hooks_dir(root: Path) -> Path:
try:
res = _sp.run(
["git", "-C", str(root), "rev-parse", "--git-path", "hooks"],
capture_output=True, text=True,
capture_output=True, text=True, encoding="utf-8",
)
if res.returncode != 0:
# git failing here is a real signal (corrupt .git/config, tampering,
+16 -2
View File
@@ -108,6 +108,7 @@ class DeclIdRegistry:
}
self._by_name: dict[tuple[str, str], set[str]] = {}
self._salted: set[str] = set()
self._spelled: dict[str, str] = {}
def resolve(self, nid: str, name: str, kind: str, taken) -> str:
key = (kind, nid)
@@ -117,6 +118,7 @@ class DeclIdRegistry:
if nid not in taken and owner is None:
self._owners[nid] = key
self._assigned[key] = nid
self._spelled[nid] = name
self._by_name.setdefault((kind, normalize_id(name)), set()).add(nid)
return nid
assigned = self._assigned.get(key)
@@ -125,9 +127,12 @@ class DeclIdRegistry:
# An id already used by a real declaration is a duplicate reference to
# that declaration (prototype owner, same name re-declared); reuse it
# instead of minting a second node. Only a salted id, whose owner stole
# the spelling from this declaration, forces a counter-salt (#4854).
# the spelling from this declaration, forces a counter-salt (#4854). A
# different kind only counts as a duplicate when spelled the same (TS
# `class Foo` + `namespace Foo`): `class Foo` + `function foo` are two (#4904).
if (nid in taken and owner is not None and owner[0] != "file"
and nid not in self._salted):
and nid not in self._salted
and (owner[0] == kind or self._spelled.get(nid) == name)):
return nid
base = make_id(nid, decl_salt(name))
candidate = base
@@ -138,11 +143,20 @@ class DeclIdRegistry:
self._owners[candidate] = key
self._assigned[key] = candidate
self._salted.add(candidate)
self._spelled[candidate] = name
self._by_name.setdefault((kind, normalize_id(name)), set()).add(candidate)
return candidate
def lookup(self, name: str, kinds=("type", "fn", "var", "ns", "alias")) -> str | None:
norm = normalize_id(name)
# A declaration spelled exactly like the reference wins over one that
# only normalizes alike: once #4904 keeps `Session` and `session()`
# apart, `Session s;` names the declaration spelled `Session`, whatever
# its kind. Without an exact spelling the kind order decides, as before.
exact = {i for kind in kinds for i in self._by_name.get((kind, norm), ())
if self._spelled.get(i) == name}
if len(exact) == 1:
return next(iter(exact))
for kind in kinds:
ids = self._by_name.get((kind, norm))
if ids:
+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
+182 -42
View File
@@ -237,6 +237,14 @@ def _platform_skill_destination(platform_name: str, *, project: bool = False, pr
return (project_dir or Path(".")) / ".agents" / "skills" / "graphify" / "SKILL.md"
return Path.home() / ".config" / "agents" / "skills" / "graphify" / "SKILL.md"
if platform_name == "pi":
# Pi reads project skills from ./.pi/skills; ~/.pi/agent/skills is the
# user-scope path only. Writing the $HOME shape into a project left the
# skill where Pi never looks, with no error (#5011).
if project:
return (project_dir or Path(".")) / ".pi" / "skills" / "graphify" / "SKILL.md"
return Path.home() / _PLATFORM_CONFIG["pi"]["skill_dst"]
if platform_name == "agents":
# The generic Agent-Skills target: project ./.agents/skills, global the
# spec's user-global ~/.agents/skills (read by `npx skills` and compliant
@@ -438,29 +446,111 @@ def _project_scope_root(path: Path, project_dir: Path) -> Path:
except ValueError:
return path
return project_dir / rel.parts[0] if rel.parts else path
def _is_graphify_skill_registration(section: "list[str]") -> bool:
"""Whether a `# graphify` section is the registration graphify writes.
Every version of the registration has had the bullet naming the graphify
skill and the `/graphify` trigger, which a hand-written section has no
reason to repeat.
"""
return any(
line.strip().startswith("- **graphify** (`") and "Trigger: `/graphify`" in line
for line in section
)
def _skill_registration_sections(content: str) -> "list[list[str]]":
"""The body of each exact `# graphify` section, bounded as
_remove_marker_section bounds it: up to the next H1."""
lines = content.split("\n")
sections = []
for start, line in enumerate(lines):
if line.strip() == _SKILL_REGISTRATION_MARKER:
end = next(
(j for j in range(start + 1, len(lines)) if lines[j].startswith("# ")),
len(lines),
)
sections.append(lines[start + 1:end])
return sections
def _remove_skill_registration(target: Path, prefix: str, *, only_graphify_written: bool = False) -> None:
"""Remove the skill registration _register_always_on_block wrote into *target*.
*only_graphify_written* is for the user's global CLAUDE.md / CODEBUDDY.md,
which every `graphify uninstall` visits, also for users who never installed
the skill there. Only a `# graphify` section carrying graphify's
registration bullet goes; a hand-written `# graphify` section stays, and a
file holding both is left as is, with a hint, rather than guessed at.
Degrades instead of raising, as the install side does (#3474): a CLAUDE.md
that nix/home-manager links into a read-only store must not abort an
uninstall halfway, with later platforms not yet cleaned.
"""
try:
if not target.exists():
return
# A file without the heading is never decoded or rewritten, so an
# unrelated non-UTF-8 file draws no warning.
if _SKILL_REGISTRATION_MARKER.encode("utf-8") not in target.read_bytes():
return
content, newline = _read_keep_newline(target)
# A BOM would hide a heading on the first line; it is written back as found.
bom = "" if content.startswith("") else ""
content = content[len(bom):]
if only_graphify_written:
written = [_is_graphify_skill_registration(s) for s in _skill_registration_sections(content)]
if not any(written):
return
if not all(written):
print(
f"{prefix}left as is: {_shown_path(target)} also has a "
f"`{_SKILL_REGISTRATION_MARKER}` section graphify did not write",
file=sys.stderr,
)
print(
f" hint: remove graphify's own `{_SKILL_REGISTRATION_MARKER}` block "
"(the one naming the graphify skill) by hand",
file=sys.stderr,
)
return
# Match the exact H1 `# graphify` registration heading, never a substring of a
# user's `## graphify`/`### graphify` (#2062). Section runs to the next H1.
# _SKILL_REGISTRATION_MARKER is the single source of truth for this heading,
# shared with _register_always_on_block so an insert and its removal always
# agree on what they're matching (#3668).
cleaned = _remove_marker_section(content, _SKILL_REGISTRATION_MARKER, boundary_prefix="# ")
if cleaned is None:
return
# A symlink stays: writing through it cleans the file it points to.
if cleaned or target.is_symlink():
# The file's own line ending is restored, so the rest of its content is
# never re-translated on write (#3668/#4360).
_write_keep_newline(target, bom + cleaned + "\n", newline)
print(f"{prefix}graphify skill registration removed from {_shown_path(target)}")
else:
target.unlink()
print(f"{prefix}deleted {target}")
except (OSError, UnicodeDecodeError) as exc:
print(f"{prefix}skipped: {exc.__class__.__name__}: {exc}", file=sys.stderr)
print(
f" hint: remove the `{_SKILL_REGISTRATION_MARKER}` block from {target} "
"manually to finish the uninstall",
file=sys.stderr,
)
def _remove_claude_skill_registration(project_dir: Path) -> None:
"""Remove the project-scoped Claude skill registration file/section."""
claude_md = project_dir / ".claude" / "CLAUDE.md"
if not claude_md.exists():
return
content, newline = _read_keep_newline(claude_md)
# Match the exact H1 `# graphify` registration heading, never a substring of a
# user's `## graphify`/`### graphify` (#2062). Section runs to the next H1.
# _SKILL_REGISTRATION_MARKER is the single source of truth for this heading,
# shared with _register_always_on_block so an insert and its removal always
# agree on what they're matching (#3668).
cleaned = _remove_marker_section(content, _SKILL_REGISTRATION_MARKER, boundary_prefix="# ")
if cleaned is None:
return
# A symlink stays: writing through it cleans the file it points to.
if cleaned or claude_md.is_symlink():
# The file's own line ending is restored, so the rest of its content is
# never re-translated on write (#3668/#4360).
_write_keep_newline(claude_md, cleaned + "\n", newline)
print(f" CLAUDE.md -> graphify skill registration removed from {_shown_path(claude_md)}")
else:
claude_md.unlink()
print(f" CLAUDE.md -> deleted {claude_md}")
_remove_skill_registration(project_dir / ".claude" / "CLAUDE.md", " CLAUDE.md -> ")
def _claude_global_registration() -> "tuple[Path, str]":
"""The CLAUDE.md a global (non-project) Claude install registers the skill in,
and the skill path that registration names: the same choice install() makes.
CLAUDE_CONFIG_DIR relocates both, as it does the skill copy (#527, #2694).
"""
config = os.environ.get("CLAUDE_CONFIG_DIR")
if config:
config_dir = Path(config)
return config_dir / "CLAUDE.md", str(config_dir / "skills" / "graphify" / "SKILL.md")
return Path.home() / ".claude" / "CLAUDE.md", "~/.claude/skills/graphify/SKILL.md"
def _codebuddy_global_registration() -> Path:
"""The CODEBUDDY.md `install --platform codebuddy` registers the skill in."""
return Path.home() / ".codebuddy" / "CODEBUDDY.md"
def _print_project_git_add_hint(paths: list[Path]) -> None:
unique: list[str] = []
for path in paths:
@@ -488,9 +578,9 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li
content search through its dedicated Grep tool, not Bash (#1986) — a
Bash-only matcher never fired on the agent's primary search path.
When ``strict`` is set, the read hook carries ``--strict`` so it blocks the
first raw read per session (Claude Code only). The ``GRAPHIFY_HOOK_STRICT`` env
var can force it on or off at runtime without a reinstall.
When ``strict`` is set, both hooks carry ``--strict`` so Read and dedicated
Grep share one block per session; Bash and Glob remain advisory. The
``GRAPHIFY_HOOK_STRICT`` env var can force it on or off without a reinstall.
Each entry carries a ``timeout`` (#3314): unset, Claude Code defaults a
command hook to 600s, so a single wedged guard (a stuck filesystem, a
@@ -504,12 +594,30 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li
if " " in exe and not exe.startswith('"'):
exe = f'"{exe}"'
read_cmd = f"{exe} hook-guard read" + (" --strict" if strict else "")
search_cmd = f"{exe} hook-guard search" + (" --strict" if strict else "")
return [
{"matcher": "Bash|Grep",
"hooks": [{"type": "command", "command": f"{exe} hook-guard search", "timeout": 10}]},
"hooks": [{"type": "command", "command": search_cmd, "timeout": 10}]},
{"matcher": "Read|Glob",
"hooks": [{"type": "command", "command": read_cmd, "timeout": 10}]},
]
def _claude_sessionstart_hooks(project: bool = False) -> "list[dict]":
"""graphify's Claude Code SessionStart hook: matcher "compact" only.
Claude Code fires SessionStart with source "compact" after an auto or manual
compaction, keeping the session id. The model has lost the earlier nudges by
then, but their per-session budget is spent, so `hook-guard compact` resets
it (and the strict-mode deny marker) and restates the graph in one line.
Same command form and timeout as _claude_pretooluse_hooks; the command
carries "hook-guard", so the install/uninstall filters recognise it.
"""
exe = _resolve_graphify_exe(project=project)
if " " in exe and not exe.startswith('"'):
exe = f'"{exe}"'
return [
{"matcher": "compact",
"hooks": [{"type": "command", "command": f"{exe} hook-guard compact", "timeout": 10}]},
]
# Tokens that only ever appear in a command graphify itself writes: its
# `hook-guard <search|read|gemini>` and `hook-check` subcommands. Legacy
# (pre-#522) installs shipped an inline POSIX bash guard instead, whose command
@@ -1028,8 +1136,9 @@ def _print_install_usage() -> None:
platforms = ", ".join([*_PLATFORM_CONFIG, "gemini", "cursor"])
print("Usage: graphify install [--project] [--strict] [--platform P|P]")
print(f"Platforms: {platforms}")
print(" --strict block the first raw file read per session until one "
"`graphify query` runs (Claude Code project hook only; needs --project)")
print(" --strict block the first raw Read or dedicated Grep per session "
"unless recently oriented with `graphify query` "
"(Claude Code project hooks only; needs --project; Bash/Glob stay advisory)")
_CLAUDE_MD_MARKER = "## graphify"
_CODEBUDDY_MD_MARKER = "## graphify"
_AGENTS_MD_MARKER = "## graphify"
@@ -2186,6 +2295,9 @@ def _kilo_uninstall_global() -> list[str]:
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
refs_dir = skill_dst.parent / "references"
if refs_dir.exists():
shutil.rmtree(refs_dir)
for d in (
skill_dst.parent,
skill_dst.parent.parent,
@@ -2233,8 +2345,9 @@ def claude_install(project_dir: Path | None = None, strict: bool = False, projec
print("Claude Code will now check the knowledge graph before answering")
print("codebase questions and rebuild it after code changes.")
if strict:
print("Strict mode: the first raw file read per session is blocked until")
print("one `graphify query` runs (toggle with GRAPHIFY_HOOK_STRICT=0).")
print("Strict mode: Read and dedicated Grep share one block per session")
print("unless recently oriented with `graphify query`; Bash/Glob stay advisory.")
print("Toggle with GRAPHIFY_HOOK_STRICT=0.")
def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool = False) -> None:
"""Add graphify PreToolUse hook to .claude/settings.json.
@@ -2253,11 +2366,18 @@ def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool
if not isinstance(pre_tool, list):
_refuse_to_modify(settings_path)
session_start = hooks.setdefault("SessionStart", [])
if not isinstance(session_start, list):
_refuse_to_modify(settings_path)
hooks["PreToolUse"] = _strip_graphify_hooks(pre_tool)
hooks["PreToolUse"].extend(_claude_pretooluse_hooks(strict=strict, project=project))
hooks["SessionStart"] = _strip_graphify_hooks(session_start)
hooks["SessionStart"].extend(_claude_sessionstart_hooks(project=project))
_write_settings_with_backup(settings_path, settings)
_mode = " (strict)" if strict else ""
print(f" .claude/settings.json -> PreToolUse hooks registered (Bash|Grep search + Read/Glob){_mode}")
print(" .claude/settings.json -> SessionStart hook registered (compact: resets the nudge budget)")
def _uninstall_claude_hook(project_dir: Path) -> None:
"""Remove the graphify PreToolUse hook from .claude/settings.json and its
local-only sibling .claude/settings.local.json.
@@ -2269,22 +2389,31 @@ def _uninstall_claude_hook(project_dir: Path) -> None:
for name in ("settings.json", "settings.local.json"):
_strip_graphify_hook(claude_dir / name)
def _strip_graphify_hook(settings_path: Path) -> None:
"""Drop graphify PreToolUse hooks from a single Claude settings file, if present."""
"""Drop graphify PreToolUse and SessionStart hooks from a single Claude
settings file, if present."""
if not settings_path.exists():
return
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
if not isinstance(pre_tool, list):
hooks = settings.get("hooks", {})
if not isinstance(hooks, dict):
return
filtered = _strip_graphify_hooks(pre_tool)
if filtered == pre_tool:
removed = []
for event in ("PreToolUse", "SessionStart"):
groups = hooks.get(event, [])
if not isinstance(groups, list):
continue
filtered = _strip_graphify_hooks(groups)
if filtered != groups:
hooks[event] = filtered
removed.append(event)
if not removed:
return
settings["hooks"]["PreToolUse"] = filtered
_write_settings_with_backup(settings_path, settings)
print(f" .claude/{settings_path.name} -> PreToolUse hook removed")
for event in removed:
print(f" .claude/{settings_path.name} -> {event} hook removed")
def _unsafe_purge_reason(out: Path, project_dir: Path) -> str | None:
@@ -2334,12 +2463,14 @@ def uninstall_all(project_dir: Path | None = None, purge: bool = False) -> None:
_antigravity_uninstall(pd)
# AGENTS.md covers: codex, aider, opencode, claw, droid, trae, trae-cn, hermes, copilot
_agents_uninstall(pd)
# Amp also drops a user-scope skill at ~/.config/agents/skills, which the
# AGENTS.md cleanup above does not touch.
_remove_skill_file("amp")
# The generic agents platform's user-scope skill lives at ~/.agents/skills,
# which neither the AGENTS.md cleanup nor amp's removal reaches.
_remove_skill_file("agents")
# `install --platform X` drops a user-scope skill (~/.codex/skills,
# ~/.config/agents/skills for amp, ~/.agents/skills, ...) that the AGENTS.md
# cleanup above does not touch, so remove every platform's.
for platform_name in _PLATFORM_CONFIG:
_remove_skill_file(platform_name)
# Kilo's global command sits outside its skill dir.
for line in _kilo_uninstall_global():
print(f" {line}")
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=pd))
# `graphify install --platform opencode` writes the plugin here (#3398).
_uninstall_opencode_plugin(_opencode_dir(project=False))
@@ -2388,6 +2519,11 @@ def claude_uninstall(project_dir: Path | None = None, *, project: bool = False,
_remove_skill_file("claude", project=True, project_dir=project_dir)
if remove_user_skill:
_remove_skill_file("claude", project=False)
# Without the skill, the global registration names a file that no longer
# exists, and Claude Code reads it in every session.
_remove_skill_registration(
_claude_global_registration()[0], " CLAUDE.md -> ", only_graphify_written=True
)
md_targets = [
project_dir / "CLAUDE.md",
@@ -2510,6 +2646,10 @@ def codebuddy_uninstall(project_dir: Path | None = None, *, project: bool = Fals
_remove_skill_file("codebuddy", project=True, project_dir=project_dir)
if remove_user_skill:
_remove_skill_file("codebuddy", project=False)
# Before the project-file checks below, which return early.
_remove_skill_registration(
_codebuddy_global_registration(), " CODEBUDDY.md -> ", only_graphify_written=True
)
target = project_dir / "CODEBUDDY.md"
if not target.exists():
+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
+124 -14
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."
@@ -552,7 +581,7 @@ solely for such a cross-document reference. Never add this marker to a node
defined by the enclosing source. Never invent, shorten or rewrite a path, and
never omit source_file.
Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
Node ID format: lowercase, word characters only (`[^\\W]` after casefolding, i.e. `[a-z0-9_]` for ASCII input but non-ASCII letters and digits are kept as-is), no dots or slashes.
Format: {stem}_{entity} where stem = full repo-relative path with the extension dropped, every segment joined with _ (e.g. src/auth/session.py -> src_auth_session); entity = symbol name (both normalised). Top-level files use just the filename stem (setup.py -> setup).
Edge direction rule — source is always the ACTOR, target is the ACTED-UPON:
@@ -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": [
@@ -1665,6 +1696,18 @@ def _call_openai_compat(
return result
def _claude_prompt_cache_enabled() -> bool:
"""Keep prompt caching on by default; allow incompatible endpoints to opt out."""
raw = os.environ.get("GRAPHIFY_CLAUDE_PROMPT_CACHE", "").strip().lower()
if raw in ("", "1", "true", "yes", "on"):
return True
if raw in ("0", "false", "no", "off"):
return False
raise ValueError(
"GRAPHIFY_CLAUDE_PROMPT_CACHE must be 1/true/yes/on or 0/false/no/off"
)
def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False, images: list[_ImageRef] | None = None) -> dict:
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
try:
@@ -1672,6 +1715,7 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
except ImportError as exc:
raise ImportError(_backend_pkg_hint("anthropic", "anthropic")) from exc
cache_enabled = _claude_prompt_cache_enabled()
client = anthropic.Anthropic(
api_key=api_key,
base_url=BACKENDS["claude"]["base_url"],
@@ -1681,13 +1725,26 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
resp = client.messages.create(
model=model,
max_tokens=max_tokens,
system=_extraction_system(deep=deep_mode),
# The system prompt is identical on every per-file call, so mark it
# cacheable: later calls bill it as a cache read, not full input (#4835).
system=[{
"type": "text",
"text": _extraction_system(deep=deep_mode),
"cache_control": {"type": "ephemeral"},
}] if cache_enabled else _extraction_system(deep=deep_mode),
messages=[{"role": "user", "content": _anthropic_content(user_message, images or [])}],
)
raw_content = _anthropic_response_text(resp.content)
result = _parse_llm_json(raw_content or "{}")
result["input_tokens"] = (resp.usage.input_tokens or 0) if resp.usage else 0
result["output_tokens"] = (resp.usage.output_tokens or 0) if resp.usage else 0
# Anthropic reports the cached system prompt in its own cache_* fields, not
# in input_tokens; add them back so cost.json still counts the whole prompt.
usage = resp.usage
result["input_tokens"] = (
(usage.input_tokens or 0)
+ (getattr(usage, "cache_read_input_tokens", 0) or 0)
+ (getattr(usage, "cache_creation_input_tokens", 0) or 0)
) if usage else 0
result["output_tokens"] = (usage.output_tokens or 0) if usage else 0
result["model"] = model
# Normalise Anthropic's `stop_reason` to the OpenAI-compat `finish_reason`
# vocabulary so the adaptive-retry layer doesn't have to know which
@@ -2214,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
@@ -2549,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:
@@ -2838,7 +2903,39 @@ def extract_corpus_parallel(
# over session state. Force serial unless the user explicitly opts in.
if backend == "claude-cli" and os.environ.get("GRAPHIFY_CLAUDE_CLI_PARALLEL", "").strip() != "1":
max_concurrency = 1
def _checkpoint_chunk(result: dict, chunk: "list[Path | FileSlice]") -> None:
# A file split into slices is complete only once every slice has returned
# (#4943). Checkpointing each slice as it lands stamped the parent's entry
# complete after its first slice, so an interrupted run served the head of
# the file as the whole file. Its results wait here until the last slice
# succeeds, then go out in one write; a slice that fails keeps it unsaved.
slices_left: dict[Path, int] = {}
for _chunk in chunks:
for _unit in _chunk:
if isinstance(_unit, FileSlice):
slices_left[unit_path(_unit)] = slices_left.get(unit_path(_unit), 0) + 1
held_results: dict[Path, list[tuple[int, dict]]] = {}
def _checkpoint_chunk(idx: int, result: dict, chunk: "list[Path | FileSlice]") -> None:
sliced = [unit_path(u) for u in chunk if isinstance(u, FileSlice)]
for parent in sliced:
slices_left[parent] -= 1
whole = [unit_path(u) for u in chunk if not isinstance(u, FileSlice)]
if whole:
_save_checkpoint(result, whole)
for parent in dict.fromkeys(sliced):
held_results.setdefault(parent, []).append((idx, result))
if slices_left[parent] == 0:
# Chunk order, not completion order, so the entry is the same
# whichever slice returned first (#1632).
held = [r for _, r in sorted(held_results.pop(parent), key=lambda p: p[0])]
combined: dict = {
bucket: [item for r in held for item in r.get(bucket, [])]
for bucket in ("nodes", "edges", "hyperedges")
}
combined["_partial_files"] = _merged_partial_files(*held)
_save_checkpoint(combined, [parent])
def _save_checkpoint(result: dict, allowed: "list[Path]") -> None:
# Persist each chunk's semantic results to the cache as soon as it
# completes. Without this, the semantic cache is only written once, at
# the very end of the run (in __main__), so a run interrupted partway
@@ -2858,7 +2955,6 @@ def extract_corpus_parallel(
# old `.rel` attribute does not exist on FileSlice, so every sliced
# chunk leaked the FileSlice object into the allowlist and the write
# raised TypeError, silently defeating the checkpoint.)
allowed = [unit_path(item) for item in chunk]
# Deep-mode results checkpoint into their own namespace
# (cache/semantic-deep/) so a deep run never overwrites standard
# entries — and a later standard run never serves deep ones (#1894).
@@ -2896,7 +2992,7 @@ def extract_corpus_parallel(
continue
assert result is not None
_merge_into(merged, result)
_checkpoint_chunk(result, chunk)
_checkpoint_chunk(idx, result, chunk)
if callable(on_chunk_done):
on_chunk_done(idx, total, result)
else:
@@ -2922,12 +3018,24 @@ def extract_corpus_parallel(
continue
assert result is not None
results_by_idx[idx] = result
_checkpoint_chunk(result, chunks[idx])
_checkpoint_chunk(idx, result, chunks[idx])
if callable(on_chunk_done):
on_chunk_done(idx, total, result)
for idx in sorted(results_by_idx):
_merge_into(merged, results_by_idx[idx])
# A failed slice leaves its parent with nodes from the other slices, so the
# parent looks covered and the caller's final save would write it complete
# (#4943). Name it partial so that save stamps it and the next run retries.
failed_parents = {
unit_path(u) for chunk in chunks for u in chunk
if isinstance(u, FileSlice) and unit_path(u) in failed_files
}
if failed_parents:
merged["_partial_files"] = sorted(
set(merged.get("_partial_files", []) or []) | {str(p) for p in failed_parents}
)
# Loud failure summary — surface chunk failures at end so they're never
# buried mid-log. Exit 0 preserved for caller compatibility; the
# summary block makes the problem visible.
@@ -3260,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}],
+282 -28
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)
@@ -207,13 +335,33 @@ def resolve_markdown_mentions(
return None, "EXTRACTED", 1.0
return _resolve_chain(by_file[source_file], names), "EXTRACTED", 1.0
callee = names[-1]
if callee in _LANGUAGE_BUILTIN_GLOBALS:
# Only skip a *bare* builtin-named mention (no qualifier). A dotted
# mention like `Repository.open` carries qualifier evidence that proves
# the reference, so it must not be discarded just because `open` is a
# language builtin.
if len(names) == 1 and callee in _LANGUAGE_BUILTIN_GLOBALS:
return None, "INFERRED", 0.95
qualifiers = set(names[:-1])
ns_chain = bool(rc.get("ns_qualified"))
by_name = by_label.get(callee, [])
candidates = [
c for c in by_label.get(callee, [])
c for c in by_name
if qualifiers <= _evidence(c, nodes_by_id, parents)
]
if not candidates and ns_chain:
# A PSR-4 namespace root (`App\`) maps to the scan directory and has
# no path segment, so when no candidate accounts for the whole chain,
# the leading qualifiers a candidate cannot account for are dropped
# (#4610). Only then: a qualifier that does match a candidate keeps
# discriminating (`Mailer::send()` still picks the right `send`).
def _dropped(c: str) -> bool:
evidence = _evidence(c, nodes_by_id, parents)
wanted = list(names[:-1])
while wanted and wanted[0] not in evidence:
wanted.pop(0)
return set(wanted) <= evidence
candidates = [c for c in by_name if _dropped(c)]
return (candidates[0] if len(candidates) == 1 else None), "INFERRED", 0.95
def _method_owner(node_id: str) -> str | None:
@@ -224,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({
@@ -250,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", ""))
@@ -269,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)
+34 -7
View File
@@ -571,6 +571,35 @@ def nfc(s: str) -> str:
return unicodedata.normalize("NFC", s)
def read_graph_json(path) -> dict:
"""A graph file's data with one copy of each string its rows repeat."""
shared: dict[str, str] = {}
def share(row: dict) -> dict:
for field, value in row.items():
if type(value) is str:
row[field] = shared.setdefault(value, value)
return row
return json.loads(Path(path).read_text(encoding="utf-8"), object_hook=share)
def consumed(rows: list):
"""Each row in order, let go as it is taken, so a graph built from them never holds both."""
rows.reverse()
while rows:
yield rows.pop()
def consumed_graph_rows(data: dict) -> dict:
"""``data`` for networkx to build a graph from once, stamped as ``restore_arc_direction`` stamps it."""
for link in data["links"]:
if isinstance(link, dict):
link["_src"] = link.get("_src", link.get("source"))
link["_tgt"] = link.get("_tgt", link.get("target"))
return dict(data, nodes=consumed(data["nodes"]), links=consumed(data["links"]))
def restore_arc_direction(data: dict) -> dict:
"""Stamp each link's stored direction as ``_src``/``_tgt`` before loading.
@@ -606,16 +635,14 @@ def load_node_link_graph(path_or_data):
"""
from networkx.readwrite import json_graph
data = path_or_data
if not isinstance(data, dict):
owned = not isinstance(data, dict)
if owned:
p = Path(data)
from graphify.security import check_graph_file_size_cap # lazy: security imports paths
check_graph_file_size_cap(p)
data = json.loads(p.read_text(encoding="utf-8"))
data = read_graph_json(p)
if isinstance(data, dict) and "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
if isinstance(data, dict):
data = restore_arc_direction(data)
try:
return json_graph.node_link_graph(data, edges="links")
except TypeError: # networkx too old for the edges kwarg; default is "links"
return json_graph.node_link_graph(data)
data = consumed_graph_rows(data) if owned and isinstance(data.get("links"), list) else restore_arc_direction(data)
return json_graph.node_link_graph(data, edges="links")
+18 -1
View File
@@ -5,6 +5,10 @@ One ``key=value`` per line, ``#`` comments, blank lines ignored. Keys:
``viz_node_limit=<int>``
Baked into the generated git hooks (see :mod:`graphify.hooks`).
``query_budget=<positive int>`` and ``query_depth=<int 1-6>``
Project defaults for the public ``graphify query`` command. Explicit query
options override these values; absent settings retain budget 2000, depth 2.
``language.<ext>=<language | .ext>``
Treat files with extension ``<ext>`` as the named language for
classification, extractor dispatch and cross-file resolution (#2961).
@@ -112,7 +116,8 @@ def parse_language_value(value: str) -> str:
def load_graphifyrc(root: Path) -> dict:
"""Parse ``<root>/.graphifyrc``. Returns ``{}`` when absent.
Returned keys: ``viz_node_limit`` (int) and ``languages``
Returned keys: ``viz_node_limit``, ``query_budget``, ``query_depth`` (ints),
and ``languages``
(``{".inc": ".php", ...}``) — each present only when the file sets it.
Unknown keys are ignored so a newer graphify's options do not break an
older one. Malformed lines raise ``ValueError`` naming the line.
@@ -147,6 +152,18 @@ def load_graphifyrc(root: Path) -> dict:
f"Invalid viz_node_limit in {rc_path} at line {line_num}: {val!r}. "
f"Must be a non-negative integer."
) from exc
elif key in {"query_budget", "query_depth"}:
requirement = "a positive integer" if key == "query_budget" else "an integer from 1 to 6"
try:
parsed_val = int(val)
if parsed_val <= 0 or (key == "query_depth" and parsed_val > 6):
raise ValueError(requirement)
cfg[key] = parsed_val
except ValueError as exc:
raise ValueError(
f"Invalid {key} in {rc_path} at line {line_num}: {val!r}. "
f"Must be {requirement}."
) from exc
elif key.startswith("language."):
ext_part = key[len("language."):].strip()
if not ext_part or any(ch.isspace() for ch in ext_part):
+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
+8
View File
@@ -167,6 +167,14 @@ def generate(
f"- Unclassified: {len(unclassified)} file(s) not represented in "
f"the graph (top: {top})"
)
# #2942: the plain count above reads as routine (lockfiles, binaries)
# even when it is most of the corpus. Say plainly, right next to the
# "large enough to be worth graphing" verdict, that this graph may
# look complete while actually missing a structurally significant
# part of the codebase.
unclassified_warning = detection_result.get("unclassified_warning")
if unclassified_warning:
lines.append(f"- WARNING: {unclassified_warning}")
from .analyze import _is_file_node, _is_concept_node, _is_contains_only_ast_node
+237 -20
View File
@@ -13,9 +13,10 @@ import threading
from typing import NamedTuple
import networkx as nx
from networkx.readwrite import json_graph
from graphify.paths import consumed, read_graph_json
from graphify.security import sanitize_label, check_graph_file_size_cap, _CONTROL_CHAR_RE
from graphify.build import _CONFIDENCE_RANK, edge_datas, edge_evidence, has_parallel_links
from graphify.paths import default_graph_json as _default_graph_json
from graphify.paths import default_graph_json as _default_graph_json, _is_test_path
try:
with warnings.catch_warnings():
@@ -52,7 +53,7 @@ def _read_graph(graph_path: str) -> nx.Graph:
raise FileNotFoundError(f"Graph file not found: {resolved}")
check_graph_file_size_cap(resolved)
safe = resolved
data = json.loads(safe.read_text(encoding="utf-8"))
data = read_graph_json(safe)
if "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
# Stash the on-disk logical flag before the load-time override below:
@@ -70,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.",
@@ -78,10 +80,9 @@ def _read_graph(graph_path: str) -> nx.Graph:
)
except Exception:
pass
try:
G = json_graph.node_link_graph(data, edges="links")
except TypeError:
G = json_graph.node_link_graph(data)
G = json_graph.node_link_graph(
dict(data, nodes=consumed(data["nodes"]), links=consumed(data["links"])), edges="links",
)
G.graph["_logical_directed"] = _logical_directed
# node_link_graph drops top-level keys other than data["graph"], so the
# build commit export.to_json writes there is stashed by hand (#3354).
@@ -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):
@@ -566,6 +648,43 @@ class _QueryScores(NamedTuple):
term_order: tuple[str, ...] = ()
# Query seeding prefers source code over tests and docs. A test named after a bug
# repeats the question's words in its own name (``UsernameValidatorsTests``), so it
# wins the exact-label tier and takes the seed slots the source it tests should
# get. Only `query` applies this weight; `path`, `explain` and `_score_nodes`
# callers score exactly as before.
_QUERY_DEMOTE_WEIGHT = 0.3
_QUERY_TEST_WORDS = frozenset({"test", "tests", "testing", "testcase", "unittest"})
_QUERY_DOC_WORDS = frozenset({"doc", "docs", "documentation", "readme"})
_QUERY_DOC_SUFFIXES = (".md", ".rst", ".txt", ".yml", ".yaml", ".toml", ".cfg", ".ini", ".json")
_QUERY_DOC_DIRS = frozenset({"doc", "docs", "example", "examples"})
def _query_path_weight(terms: list[str]):
"""Score multiplier per node for `query`: tests, docs, config files and nodes
without a source file count `_QUERY_DEMOTE_WEIGHT`, unless the question itself
asks about tests (or docs); everything else counts 1.0."""
words = {tok for t in terms for tok in _search_tokens(t)}
keep_tests = bool(words & _QUERY_TEST_WORDS)
keep_docs = bool(words & _QUERY_DOC_WORDS)
def weight(data: dict) -> float:
path = str(data.get("source_file") or "").replace("\\", "/")
parts = path.lower().split("/")
if not keep_tests and (_is_test_path(path) or "testing" in parts[:-1] or parts[-1] == "conftest.py"):
return _QUERY_DEMOTE_WEIGHT
if not keep_docs and (
not path
or data.get("file_type") in ("document", "paper")
or parts[-1].endswith(_QUERY_DOC_SUFFIXES)
or any(p in _QUERY_DOC_DIRS for p in parts[:-1])
):
return _QUERY_DEMOTE_WEIGHT
return 1.0
return weight
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
"""Combined query scorer returning the existing ranked `(score, node_id)` list.
@@ -578,7 +697,7 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
def _score_query(
G: nx.Graph, terms: list[str], *, collect_per_term_seeds: bool
G: nx.Graph, terms: list[str], *, collect_per_term_seeds: bool, path_weight=None
) -> _QueryScores:
"""Single-pass combined scorer that optionally also records the best seed
for each normalized query token.
@@ -654,6 +773,10 @@ def _score_query(
# neither runs (`joined` empty AND not collecting seeds) skip the call;
# this preserves the single-query-time perf where nid_lower was lazy.
nid_lower = nid.lower() if (joined or collect_per_term_seeds) else ""
# `query` passes a per-node multiplier (tests/docs below source); it scales
# the combined score and the per-term singleton alike, so the per-term
# seed guarantee still holds but prefers a source node for each term.
weight = path_weight(data) if path_weight is not None else 1.0
score = 0.0
# Full-query tier: a multi-word query that equals (or prefixes) the whole
# label must dominate the per-token bag-of-words sums below, so `path`/
@@ -670,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"
@@ -738,6 +872,7 @@ def _score_query(
else:
singleton = 0.0
singleton += tier_value + substr_value + source_value + rationale_value + attr_value
singleton *= weight
if singleton > 0:
# Tie-break key mirrors the legacy sort+max(degree):
# (-singleton, -degree, label_len, nid) — the minimum
@@ -749,6 +884,7 @@ def _score_query(
best_by_term[t] = (key, nid)
if tiered:
score += tiered * (matched / n_terms) ** 2
score *= weight
if score > 0:
scored.append((score, nid))
# Sort by score desc; break ties toward the shorter label so a concise exact
@@ -820,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
@@ -870,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.
@@ -880,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
@@ -1122,11 +1265,14 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
return visited, edges_seen
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *, seeds: list[str] | None = None) -> str:
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *, seeds: list[str] | None = None, scores: dict[str, float] | None = None) -> str:
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token).
seeds: exact-match nodes rendered first before the degree-sorted expansion,
so the queried symbol always appears at the top of the output.
scores: `query`'s node scores. When given, the answer is file-first: seeds
and then the other nodes are grouped by file, best-scoring file first.
"""
char_budget = token_budget * 3
lines = []
@@ -1158,10 +1304,35 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
dist[nb] = hop
nxt.append(nb)
frontier = nxt
ordered = seed_hits + sorted(
nodes - seed_set,
key=lambda n: (dist.get(n, 1 << 30), -G.degree(n), str(n)),
)
if scores:
# File-first (query only): rank files by their best-scoring node in the
# answer, then list the seeds, and after them the other nodes, file by
# file (best file first), by score, then by hop and degree as before.
# Nodes the question did not match keep the old order after every
# matched file.
file_best: dict[str, float] = {}
for n in nodes:
sc = scores.get(n, 0.0)
if sc > 0:
f = str(G.nodes[n].get("source_file") or "")
if sc > file_best.get(f, 0.0):
file_best[f] = sc
file_rank = {f: i for i, (f, _) in enumerate(sorted(file_best.items(), key=lambda kv: (-kv[1], kv[0])))}
unranked = len(file_rank)
def _order(n: str):
f = str(G.nodes[n].get("source_file") or "")
sc = scores.get(n, 0.0)
fr = file_rank.get(f, unranked) if sc > 0 else unranked
return (fr, -sc, dist.get(n, 1 << 30), -G.degree(n), str(n))
seed_hits = sorted(seed_hits, key=_order)
ordered = seed_hits + sorted(nodes - seed_set, key=_order)
else:
ordered = seed_hits + sorted(
nodes - seed_set,
key=lambda n: (dist.get(n, 1 << 30), -G.degree(n), str(n)),
)
for nid in ordered:
d = G.nodes[nid]
# Every LLM-derived field passes through sanitize_label before being
@@ -1472,7 +1643,7 @@ def _query_graph_text(
# — one combined + one per query token — re-walking the whole graph each
# time; on a 100k-node, three-term benchmark ~71% of scoring time was
# spent in those redundant per-term passes.
qs = _score_query(G, terms, collect_per_term_seeds=True)
qs = _score_query(G, terms, collect_per_term_seeds=True, path_weight=_query_path_weight(terms))
# Relational-intent verbs ("calls", "uses", ...) describe the relation the
# question asks about, not a symbol to seed from; drop them from the
# per-term seed GUARANTEE so an incidental verb match cannot seat a decoy
@@ -1490,7 +1661,8 @@ def _query_graph_text(
if not start_nodes:
return _QUERY_NO_MATCH
return _render_query(G, question, start_nodes, mode=mode, depth=depth, token_budget=token_budget,
context_filters=context_filters, graph_path=graph_path)
context_filters=context_filters, graph_path=graph_path,
scores={nid: sc for sc, nid in qs.ranked})
def _render_query(
@@ -1505,6 +1677,7 @@ def _render_query(
graph_path: str | None,
given: bool = False,
unresolved: list[str] | None = None,
scores: dict[str, float] | None = None,
) -> str:
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
traversal_graph = _filter_graph_by_context(_traversal_view(G), resolved_filters)
@@ -1533,7 +1706,7 @@ def _render_query(
# Pass the seeds so the queried symbol renders first and survives truncation
# (#BUG2): a branch merge had silently dropped this argument, leaving the
# seed-first ordering as dead code.
return header + _subgraph_to_text(traversal_graph, nodes, edges, token_budget, seeds=start_nodes)
return header + _subgraph_to_text(traversal_graph, nodes, edges, token_budget, seeds=start_nodes, scores=scores)
def _resolve_path_scoped_symbol(G: nx.Graph, path_part: str, symbol_part: str) -> list[str]:
@@ -2175,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.
@@ -2204,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.
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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 +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\"))
@@ -319,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'))
@@ -375,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)
"
@@ -461,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()`. 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 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()` 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 +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:
@@ -499,12 +510,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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 +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)
@@ -533,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'),
@@ -546,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
@@ -567,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)}
@@ -580,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).
@@ -595,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
@@ -635,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),
@@ -656,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).
@@ -668,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)
@@ -698,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):
```
+21 -10
View File
@@ -48,6 +48,10 @@ Use it for:
- A research corpus (citation graph + concept graph in one)
- Your personal /raw folder (drop everything in, let it grow, query it)
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -113,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
@@ -417,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
@@ -432,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 /
@@ -456,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 = {
@@ -473,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
@@ -494,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()}
@@ -506,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).
@@ -520,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
@@ -715,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)
@@ -798,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))
@@ -1091,6 +1100,8 @@ print(output)
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have no edge to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries:
```bash
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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 +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\"))
@@ -319,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'))
@@ -375,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)
"
@@ -461,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()`. 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 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()` 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 +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:
@@ -499,12 +510,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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 +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)
@@ -533,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'),
@@ -546,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
@@ -567,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)}
@@ -580,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).
@@ -595,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
@@ -635,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),
@@ -656,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).
@@ -668,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)
@@ -698,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -312,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\"))
@@ -322,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'))
@@ -378,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)
"
@@ -464,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()`. 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 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()` 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
@@ -479,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:
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -523,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)
@@ -536,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'),
@@ -549,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
@@ -570,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)}
@@ -583,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).
@@ -598,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
@@ -638,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),
@@ -659,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).
@@ -671,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)
@@ -701,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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 +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\"))
@@ -323,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'))
@@ -379,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)
"
@@ -465,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()`. 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 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()` 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 +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:
@@ -503,12 +514,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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 +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)
@@ -537,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'),
@@ -550,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
@@ -571,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)}
@@ -584,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).
@@ -599,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
@@ -639,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),
@@ -660,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).
@@ -672,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)
@@ -702,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -312,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\"))
@@ -322,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'))
@@ -378,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)
"
@@ -464,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()`. 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 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()` 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
@@ -479,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:
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -523,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)
@@ -536,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'),
@@ -549,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
@@ -570,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)}
@@ -583,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).
@@ -598,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
@@ -638,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),
@@ -659,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).
@@ -671,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)
@@ -701,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):
```
+21 -10
View File
@@ -59,6 +59,10 @@ Use it for:
- A research corpus (citation graph + concept graph in one)
- Your personal /raw folder (drop everything in, let it grow, query it)
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -126,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
@@ -482,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
@@ -497,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 /
@@ -521,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 = {
@@ -538,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
@@ -571,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).
@@ -585,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
@@ -833,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)
@@ -937,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))
@@ -1227,6 +1236,8 @@ print(output)
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have no edge to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries:
```bash
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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 +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\"))
@@ -319,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'))
@@ -375,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)
"
@@ -461,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()`. 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 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()` 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 +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:
@@ -499,12 +510,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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 +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)
@@ -533,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'),
@@ -546,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
@@ -567,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)}
@@ -580,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).
@@ -595,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
@@ -635,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),
@@ -656,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).
@@ -668,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)
@@ -698,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -312,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\"))
@@ -322,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'))
@@ -378,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)
"
@@ -464,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()`. 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 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()` 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
@@ -479,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:
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -523,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)
@@ -536,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'),
@@ -549,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
@@ -570,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)}
@@ -583,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).
@@ -598,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
@@ -638,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),
@@ -659,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).
@@ -671,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)
@@ -701,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -312,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\"))
@@ -322,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'))
@@ -378,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)
"
@@ -464,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()`. 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 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()` 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
@@ -479,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:
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -523,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)
@@ -536,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'),
@@ -549,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
@@ -570,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)}
@@ -583,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).
@@ -598,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
@@ -638,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),
@@ -659,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).
@@ -671,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)
@@ -701,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -304,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\"))
@@ -314,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'))
@@ -370,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)
"
@@ -456,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()`. 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 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()` 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
@@ -471,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:
@@ -494,12 +505,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -515,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)
@@ -528,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'),
@@ -541,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
@@ -562,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)}
@@ -575,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).
@@ -590,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
@@ -630,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),
@@ -651,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).
@@ -663,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)
@@ -693,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -306,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\"))
@@ -316,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'))
@@ -372,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)
"
@@ -458,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()`. 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 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()` 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
@@ -473,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:
@@ -496,12 +507,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -517,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)
@@ -530,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'),
@@ -543,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
@@ -564,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)}
@@ -577,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).
@@ -592,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
@@ -632,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),
@@ -653,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).
@@ -665,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)
@@ -695,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -310,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\"))
@@ -320,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'))
@@ -376,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)
"
@@ -462,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()`. 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 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()` 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
@@ -477,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:
@@ -500,12 +511,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -521,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)
@@ -534,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'),
@@ -547,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
@@ -568,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)}
@@ -581,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).
@@ -596,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
@@ -636,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),
@@ -657,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).
@@ -669,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)
@@ -699,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -308,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\"))
@@ -318,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'))
@@ -374,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)
"
@@ -460,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()`. 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 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()` 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
@@ -475,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:
@@ -498,12 +509,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -519,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)
@@ -532,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'),
@@ -545,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
@@ -566,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)}
@@ -579,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).
@@ -594,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
@@ -634,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),
@@ -655,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).
@@ -667,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)
@@ -697,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -147,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")
@@ -155,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
@@ -216,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)])
@@ -223,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:
@@ -270,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).
@@ -340,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"))
@@ -350,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'))
@@ -406,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) -
@@ -492,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()`. 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 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()` 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
@@ -507,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:
@@ -530,12 +541,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -551,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)
@@ -564,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'),
@@ -577,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
@@ -598,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)}
@@ -611,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).
@@ -626,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
@@ -666,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),
@@ -687,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).
@@ -699,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)
@@ -729,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):
```
+33 -19
View File
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
@@ -119,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\")
@@ -127,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
@@ -188,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)])
@@ -195,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:
@@ -242,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).
@@ -312,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\"))
@@ -322,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'))
@@ -378,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)
"
@@ -464,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()`. 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 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()` 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
@@ -479,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:
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
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()},
@@ -523,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)
@@ -536,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'),
@@ -549,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
@@ -570,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)}
@@ -583,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).
@@ -598,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
@@ -638,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),
@@ -659,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).
@@ -671,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)
@@ -701,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):
```
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"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}}
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.')
"
```
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"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}}
+2
View File
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.')
"
```
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"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}}
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.
@@ -30,10 +30,13 @@ Rules:
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
+15
View File
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
+2
View File
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.')
"
```
@@ -30,7 +30,7 @@ Rules:
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
+15
View File
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.')
"
```
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"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}}
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.')
"
```
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"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}}
+15
View File
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.')
"
```
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"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}}
+15
View File
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
+2
View File
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.
@@ -30,10 +30,13 @@ Rules:
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
+15
View File
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
+2
View File
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.')
"
```
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"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}}
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
```bash
graphify claude uninstall # remove the section
```
## Source-read freshness
The source-read guard treats a file newer than `graph.json` as potentially stale,
but a checkout can refresh timestamps without changing content. For newer files,
the guard checks the exact project-relative path (or an exact legacy absolute
path) in the configured output directory's extraction manifest. Every populated
AST/semantic hash must match the current content; a matching tier cannot hide a
stale tier. Unchanged content retains the normal graph guidance and strict-mode
first-read deny.
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
marker always softens the guard, even when content matches. Older-mtime files
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
@@ -171,6 +171,8 @@ print(output)
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
+16 -4
View File
@@ -14,7 +14,12 @@ 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()))
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
# 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)
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({
@@ -103,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
@@ -124,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')
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
# filter alone would stamp it and the next --update would never re-queue it. Pass the
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
# 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)
# 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')
@@ -171,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.
@@ -30,10 +30,13 @@ Rules:
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
Output exactly this JSON (no other text):
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
CHUNK_PATH
```
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more