Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5eedffa874 | ||
|
|
4067e31a88 | ||
|
|
6021290cf2 | ||
|
|
acae154d4c | ||
|
|
7058cbd612 | ||
|
|
b824c815d2 | ||
|
|
8f4317704a | ||
|
|
637e9c6d8e | ||
|
|
5bfb4241d8 | ||
|
|
7b1d14489f | ||
|
|
1c74ae85af | ||
|
|
b77380be5c | ||
|
|
130e072b8d | ||
|
|
41f82c11a6 | ||
|
|
caa6a0783b | ||
|
|
76a80a838c | ||
|
|
4e781ef8bc | ||
|
|
91cc31b05f | ||
|
|
eb9468a906 | ||
|
|
2643077a22 | ||
|
|
b327203c30 | ||
|
|
177b35e6a5 | ||
|
|
98dc02b1a1 | ||
|
|
d51dce6164 | ||
|
|
ae55b5b219 | ||
|
|
8fcec967ac | ||
|
|
107ddf0846 | ||
|
|
3192fdf1f4 | ||
|
|
913b8e3a56 | ||
|
|
bce80814d7 | ||
|
|
8a5756266a | ||
|
|
d63d41165b | ||
|
|
cbc48a69ab | ||
|
|
0a14069d7f | ||
|
|
1de3f09607 | ||
|
|
43e1d4650a | ||
|
|
ce66353f93 | ||
|
|
23390d21b1 | ||
|
|
d81c4a9556 | ||
|
|
73a1e861a0 | ||
|
|
549ae57159 | ||
|
|
6c8002eca4 | ||
|
|
433a57a002 | ||
|
|
cb5106e861 | ||
|
|
c3d5305eb2 | ||
|
|
1a6c252195 | ||
|
|
cd9634832c | ||
|
|
6ee8e2258e | ||
|
|
778c906a08 | ||
|
|
c018fc9f97 | ||
|
|
2ce70ce17d | ||
|
|
1192efc639 | ||
|
|
204b50854d | ||
|
|
bf1e19dce9 | ||
|
|
cd54401097 | ||
|
|
4feadeda0d | ||
|
|
c66ccae853 | ||
|
|
2394fd3f98 | ||
|
|
67c139e403 | ||
|
|
d458e272b9 | ||
|
|
444c164cfe | ||
|
|
b81d8e51da | ||
|
|
6271f3ed40 | ||
|
|
85ad8daa1e | ||
|
|
c3b6cfbd9f | ||
|
|
ebef2af2b9 | ||
|
|
8f3ce12426 | ||
|
|
76d8179218 | ||
|
|
122cede129 | ||
|
|
1bfdcfffd2 | ||
|
|
43360efb0c | ||
|
|
5212304ff8 | ||
|
|
b0a9d775d1 | ||
|
|
a4db00821c | ||
|
|
a4d4b03bc1 | ||
|
|
f67daeba58 | ||
|
|
53ef377a36 | ||
|
|
955c65de1e | ||
|
|
83ca144577 | ||
|
|
499137470d | ||
|
|
16218bfc80 | ||
|
|
c051a96ff3 | ||
|
|
03838fe3af | ||
|
|
17cf53666e | ||
|
|
79cfb37fe0 | ||
|
|
63cf60dd22 | ||
|
|
4c16a79817 | ||
|
|
892c452d8c | ||
|
|
d76b102905 | ||
|
|
e93821ff3c | ||
|
|
d329bcdfdb | ||
|
|
918b4b7558 | ||
|
|
8316033ce0 | ||
|
|
2b955d3b68 | ||
|
|
80b9a4caf4 | ||
|
|
d944c3f074 | ||
|
|
b3d967519f | ||
|
|
206169981c | ||
|
|
8317212754 | ||
|
|
52a7acb602 | ||
|
|
92622867d1 | ||
|
|
b227f7200f | ||
|
|
69954b537d | ||
|
|
7fc5312e91 | ||
|
|
fd1ee64528 | ||
|
|
82bde2b35b | ||
|
|
084c3fd121 | ||
|
|
0a9491d3d3 | ||
|
|
cb2befc171 | ||
|
|
13e05097a0 | ||
|
|
50cea7f614 | ||
|
|
fbfa4162ee | ||
|
|
a561caa274 | ||
|
|
3050664e04 | ||
|
|
95ae649a6e | ||
|
|
6b12463402 | ||
|
|
71eb28a770 | ||
|
|
59b5ab1151 | ||
|
|
e3d7877c9b | ||
|
|
5b8415f368 | ||
|
|
19eacc74a1 | ||
|
|
514fb6f6a9 | ||
|
|
5260578567 | ||
|
|
0696dfbf86 | ||
|
|
ba20b12bbc | ||
|
|
6dcba3377e | ||
|
|
6096f63407 | ||
|
|
858aa9f423 | ||
|
|
e10c7cef04 | ||
|
|
f4d62e7b8c | ||
|
|
789f2742b3 | ||
|
|
14485ab508 | ||
|
|
83f6142342 | ||
|
|
694c2d7e1a | ||
|
|
69c61eaaf3 | ||
|
|
a1ae1ff243 | ||
|
|
6ed7044288 | ||
|
|
00ad4fde5a | ||
|
|
87b1aae182 | ||
|
|
67cf4967bf | ||
|
|
edc74052ee | ||
|
|
a50ad2b419 | ||
|
|
b8ba9eb366 | ||
|
|
1c0d3d853c | ||
|
|
60349fe74c | ||
|
|
0ed3c32c55 | ||
|
|
227028de75 | ||
|
|
7433c0a805 | ||
|
|
2a5d442632 | ||
|
|
cb408949e1 | ||
|
|
2fc643effd | ||
|
|
088a40766f | ||
|
|
787f5fd026 | ||
|
|
123da822a5 | ||
|
|
924be16018 | ||
|
|
6be19949d6 | ||
|
|
d90f9f5342 | ||
|
|
8ed0f30698 | ||
|
|
d7bff93019 | ||
|
|
3844e681f2 | ||
|
|
209b2a5b4e | ||
|
|
be413f32a7 | ||
|
|
dce3af740e | ||
|
|
874173c583 | ||
|
|
ddf0c08bc1 | ||
|
|
5bab54d8d6 | ||
|
|
2460bab3b9 | ||
|
|
90e1b5f343 | ||
|
|
a328198f84 | ||
|
|
f9fbd6daf0 | ||
|
|
7fe71dda9f | ||
|
|
fde54b56c3 | ||
|
|
7a64ccfb61 | ||
|
|
8e6a6d2129 | ||
|
|
197db0140b | ||
|
|
0a4408b177 | ||
|
|
bd318e933c | ||
|
|
9466cac7e5 | ||
|
|
a1f7d89f1e | ||
|
|
b492c8f05b | ||
|
|
d3b314d92e | ||
|
|
ffbdae50c2 | ||
|
|
92bb7fd189 | ||
|
|
2128bca775 | ||
|
|
cfd9846667 | ||
|
|
18813bbb41 | ||
|
|
8daebd8e0f | ||
|
|
0c786ea667 | ||
|
|
1c2b17d8e6 | ||
|
|
7612ac7c30 | ||
|
|
863a024b3b | ||
|
|
7f7c0ed441 | ||
|
|
f5c126d8a3 | ||
|
|
19f865361d | ||
|
|
7566615de3 | ||
|
|
4c81e6f5a9 | ||
|
|
e7bf2adb33 | ||
|
|
ba6d292bae | ||
|
|
2ab621790f | ||
|
|
cd1400f25f | ||
|
|
739f34d8ce | ||
|
|
ff8ddf5458 | ||
|
|
99b8da78be | ||
|
|
5c4a858940 | ||
|
|
4d678b4ab9 | ||
|
|
bce0d5624e | ||
|
|
fdb288fd5b | ||
|
|
afb177911f | ||
|
|
07f61e1bdd | ||
|
|
3d772b9778 | ||
|
|
7750ba8cef | ||
|
|
93b7a9c1e3 | ||
|
|
b80cd8384b | ||
|
|
2207cf2265 | ||
|
|
9e6f271ae9 | ||
|
|
f3421ff133 | ||
|
|
f3cdf6b651 | ||
|
|
f2ef7024fe | ||
|
|
dea2e695bc | ||
|
|
049c8647df | ||
|
|
c6040bdbd3 | ||
|
|
32e5efe935 | ||
|
|
96fa042152 | ||
|
|
5f7d7e80ac | ||
|
|
87fa551c57 | ||
|
|
2fcbdc020d | ||
|
|
590c77d89c | ||
|
|
f3e50225ed | ||
|
|
6bb5913dac | ||
|
|
eaa4aba022 |
No files matched your search
+101
@@ -79,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).
|
||||
@@ -93,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.
|
||||
@@ -101,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:
|
||||
@@ -143,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
|
||||
@@ -151,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.
|
||||
+132
@@ -2,6 +2,138 @@
|
||||
|
||||
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).
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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. |
|
||||
|
||||
@@ -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")
|
||||
|
||||
+21
-18
@@ -318,19 +318,23 @@ def affected_nodes(
|
||||
# otherwise. The member nodes are seeds only (not reported as hits), and
|
||||
# `method`/`contains` stay out of the general relation-filtered walk, so this
|
||||
# adds no forward noise anywhere else.
|
||||
if hasattr(graph, "out_edges"):
|
||||
member_edges = graph.out_edges(seed, data=True)
|
||||
else:
|
||||
member_edges = (
|
||||
(s, t, d) for s, t, d in graph.edges(data=True) if s == seed
|
||||
)
|
||||
for _s, member, data in member_edges:
|
||||
if str(data.get("relation", "")) not in ("method", "contains"):
|
||||
continue
|
||||
member = str(member)
|
||||
if member not in seen:
|
||||
seen.add(member)
|
||||
queue.append((member, 0))
|
||||
member_queue = deque([seed])
|
||||
while member_queue:
|
||||
parent = member_queue.popleft()
|
||||
if hasattr(graph, "out_edges"):
|
||||
member_edges = graph.out_edges(parent, data=True)
|
||||
else:
|
||||
member_edges = (
|
||||
(s, t, d) for s, t, d in graph.edges(data=True) if s == parent
|
||||
)
|
||||
for _s, member, data in member_edges:
|
||||
if str(data.get("relation", "")) not in ("method", "contains"):
|
||||
continue
|
||||
member = str(member)
|
||||
if member not in seen:
|
||||
seen.add(member)
|
||||
queue.append((member, 0))
|
||||
member_queue.append(member)
|
||||
|
||||
supertype_cache: dict[str, list[str]] = {}
|
||||
# Overridden members walked without being reported; one that a real edge
|
||||
@@ -453,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}. "
|
||||
@@ -468,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")
|
||||
+310
-24
@@ -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
@@ -38,7 +38,7 @@ except Exception:
|
||||
_EXTRACTOR_VERSION = "unknown"
|
||||
|
||||
# Bump when AST cache-key semantics change independently of the package version.
|
||||
_AST_CACHE_SCHEMA = 33 # A Scala `extension (x: T)` method is scoped to its receiver type T (#2044, #4856); and a Terraform node carries its original scope so ids stay portable when the cached project is moved to a new directory (#4858, #4861), so cached Scala and Terraform extractions re-run; prior (32): A type and a function whose names differ only in case get separate node ids (#4904, #4908); and a PHP `Scope::MEMBER` access in a class-level initializer (const value, property/parameter default) emits a references_constant edge (#4648, #4895); R `setClass`/`setRefClass` `contains=` superclasses get inherits edges (#4902); an Elixir bare call resolves to the caller's own module first (#4900); a Dart mixin `on A, B` clause resolves every constraint (#4899); and a Fortran derived-type `extends` emits an inherits edge (#4897), so cached extractions for those languages re-run (#4904); Go credits a call in a 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 staLine 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("."),
|
||||
|
||||
+683
-100
File diff suppressed because it is too large.
Load diff
@@ -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
@@ -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
@@ -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
|
||||
|
||||
+31
-5
@@ -303,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():
|
||||
@@ -331,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)
|
||||
@@ -351,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)
|
||||
@@ -372,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(
|
||||
@@ -385,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()}
|
||||
@@ -458,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", {}):
|
||||
@@ -480,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:
|
||||
|
||||
+1450
-71
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
|
||||
@@ -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, []):
|
||||
|
||||
+700
-43
File diff suppressed because it is too large.
Load diff
+181
-63
@@ -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
@@ -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)
|
||||
|
||||
|
||||
@@ -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}
|
||||
@@ -1633,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.
|
||||
@@ -1690,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
|
||||
@@ -1818,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
|
||||
@@ -1835,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.
|
||||
@@ -1911,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()
|
||||
@@ -2020,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
|
||||
@@ -2033,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)
|
||||
@@ -2266,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",
|
||||
@@ -2286,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
|
||||
@@ -2298,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":
|
||||
@@ -2307,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)
|
||||
@@ -2337,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):
|
||||
@@ -2344,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
|
||||
@@ -2440,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)
|
||||
@@ -2462,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 (
|
||||
@@ -2483,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):
|
||||
@@ -2832,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:
|
||||
@@ -2862,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":
|
||||
@@ -2935,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)
|
||||
@@ -2963,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)
|
||||
@@ -2974,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)
|
||||
|
||||
@@ -3045,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)
|
||||
@@ -3222,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")
|
||||
@@ -3523,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:
|
||||
@@ -3533,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":
|
||||
@@ -3580,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
@@ -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:
|
||||
|
||||
+844
-35
File diff suppressed because it is too large.
Load diff
@@ -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
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):])
|
||||
+2
-2
@@ -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
|
||||
|
||||
@@ -143,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
@@ -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
|
||||
|
||||
|
||||
+171
-36
@@ -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"
|
||||
@@ -2236,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.
|
||||
|
||||
@@ -2256,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.
|
||||
@@ -2272,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:
|
||||
@@ -2393,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",
|
||||
@@ -2515,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():
|
||||
|
||||
@@ -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
|
||||
|
||||
+94
-10
@@ -22,6 +22,7 @@ from graphify.file_slice import (
|
||||
FileSlice,
|
||||
bisect_slice,
|
||||
expand_oversized_files,
|
||||
make_full_slice,
|
||||
read_slice_text,
|
||||
unit_path,
|
||||
)
|
||||
@@ -364,6 +365,34 @@ def _openai_max_tokens_kwarg(backend: str, max_tokens: int) -> dict[str, int]:
|
||||
return {key: max_tokens}
|
||||
|
||||
|
||||
def _provider_extra_headers(raw: object, name: str = "") -> dict[str, str] | None:
|
||||
"""Validate a custom provider's providers.json ``extra_headers`` map (#3680).
|
||||
|
||||
Some OpenAI-compatible gateways need request headers beyond Authorization
|
||||
(OpenCode Go rejects a request without ``x-opencode-session``). They are
|
||||
passed to the OpenAI client as ``default_headers``, the header counterpart
|
||||
of ``extra_body``. Only string-to-string entries are kept, and an
|
||||
``Authorization`` entry is dropped: the API key always comes from the
|
||||
provider's ``env_key``, so the config cannot swap in a different credential.
|
||||
Returns None when nothing usable remains.
|
||||
"""
|
||||
if raw is None:
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
print(f"[graphify] WARNING: provider {name!r} extra_headers is not an object; ignoring.", file=sys.stderr)
|
||||
return None
|
||||
headers: dict[str, str] = {}
|
||||
for key, value in raw.items():
|
||||
if not (isinstance(key, str) and isinstance(value, str)):
|
||||
print(f"[graphify] WARNING: provider {name!r} extra_headers entry {key!r} is not a string pair; ignoring it.", file=sys.stderr)
|
||||
continue
|
||||
if key.strip().lower() == "authorization":
|
||||
print(f"[graphify] WARNING: provider {name!r} extra_headers cannot set Authorization; ignoring it.", file=sys.stderr)
|
||||
continue
|
||||
headers[key] = value
|
||||
return headers or None
|
||||
|
||||
|
||||
# Model-name fragments for OpenAI-compatible "reasoning" models that reject an
|
||||
# explicit temperature: the API returns 400 "Unsupported value: 'temperature'
|
||||
# does not support 0 with this model. Only the default (1) value is supported."
|
||||
@@ -1557,6 +1586,7 @@ def _call_openai_compat(
|
||||
deep_mode: bool = False,
|
||||
images: list[_ImageRef] | None = None,
|
||||
extra_body: dict | None = None,
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
) -> dict:
|
||||
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
|
||||
ollama_seed = _resolve_ollama_seed() if backend == "ollama" else None
|
||||
@@ -1582,7 +1612,8 @@ def _call_openai_compat(
|
||||
if backend == "ollama" and not os.environ.get("GRAPHIFY_MAX_RETRIES", "").strip():
|
||||
_retries = 0
|
||||
client = OpenAI(api_key=api_key, base_url=base_url, timeout=_resolve_api_timeout(),
|
||||
max_retries=_retries)
|
||||
max_retries=_retries,
|
||||
**({"default_headers": extra_headers} if extra_headers else {}))
|
||||
kwargs: dict = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
@@ -2240,6 +2271,7 @@ def extract_files_direct(
|
||||
deep_mode=deep_mode,
|
||||
images=image_refs,
|
||||
extra_body=cfg.get("extra_body"),
|
||||
extra_headers=_provider_extra_headers(cfg.get("extra_headers"), backend),
|
||||
)
|
||||
|
||||
# Verify code-typed nodes against the source the model read and downgrade the
|
||||
@@ -2575,10 +2607,17 @@ def _extract_with_adaptive_retry(
|
||||
}
|
||||
|
||||
def _split_lone_slice() -> "tuple[FileSlice, FileSlice] | None":
|
||||
# When a single-unit chunk is a slice, bisect the slice so we can retry
|
||||
# on a smaller range rather than give up (#1369).
|
||||
if len(chunk) == 1 and isinstance(chunk[0], FileSlice) and _depth < max_depth:
|
||||
return bisect_slice(chunk[0])
|
||||
# When a single-unit chunk is a slice (or an eligible splittable text file
|
||||
# below the char cap), bisect the slice so we can retry on a smaller
|
||||
# range rather than give up (#1369, #5072).
|
||||
if len(chunk) == 1 and _depth < max_depth:
|
||||
unit = chunk[0]
|
||||
if isinstance(unit, FileSlice):
|
||||
return bisect_slice(unit)
|
||||
if isinstance(unit, (Path, str)):
|
||||
fs = make_full_slice(Path(unit))
|
||||
if fs is not None:
|
||||
return bisect_slice(fs)
|
||||
return None
|
||||
|
||||
try:
|
||||
@@ -2864,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
|
||||
@@ -2884,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).
|
||||
@@ -2922,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:
|
||||
@@ -2948,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.
|
||||
@@ -3286,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
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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 +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\"))
|
||||
@@ -323,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'))
|
||||
@@ -379,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)
|
||||
"
|
||||
@@ -465,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
|
||||
@@ -480,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:
|
||||
@@ -503,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()},
|
||||
@@ -524,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)
|
||||
|
||||
@@ -537,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'),
|
||||
@@ -550,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
|
||||
|
||||
@@ -571,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)}
|
||||
@@ -584,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).
|
||||
@@ -599,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
|
||||
|
||||
@@ -639,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),
|
||||
@@ -660,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).
|
||||
@@ -672,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)
|
||||
@@ -702,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):
|
||||
```
|
||||
|
||||
+17
-10
@@ -117,12 +117,13 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
print(json.dumps(result))
|
||||
" > .graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -421,7 +422,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears, the same way you substitute `INPUT_PATH` - do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears - do not leave the literal `IS_DIRECTED` in the code. INPUT_PATH is not substituted - each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -436,6 +437,7 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
G = build_from_json(extraction, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
@@ -460,7 +462,7 @@ wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
|
||||
analysis = {
|
||||
@@ -477,7 +479,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -498,6 +500,7 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
G = build_from_json(extraction, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -510,7 +513,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -524,7 +527,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -719,16 +722,17 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# Stamp only semantic files that produced output so a failed chunk is re-queued next run, not lost (#2015).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_corpus = detect.get('all_files') or detect['files']
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH))
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
|
||||
_stamped = {f for fl in _manifest_files.values() for f in fl}
|
||||
_cleared = _dispatched - _stamped
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -802,7 +806,8 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
@@ -1095,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
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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 +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\"))
|
||||
@@ -323,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'))
|
||||
@@ -379,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)
|
||||
"
|
||||
@@ -465,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
|
||||
@@ -480,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:
|
||||
@@ -503,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()},
|
||||
@@ -524,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)
|
||||
|
||||
@@ -537,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'),
|
||||
@@ -550,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
|
||||
|
||||
@@ -571,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)}
|
||||
@@ -584,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).
|
||||
@@ -599,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
|
||||
|
||||
@@ -639,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),
|
||||
@@ -660,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).
|
||||
@@ -672,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)
|
||||
@@ -702,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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).
|
||||
@@ -316,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\"))
|
||||
@@ -326,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'))
|
||||
@@ -382,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)
|
||||
"
|
||||
@@ -468,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
|
||||
@@ -483,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:
|
||||
@@ -506,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()},
|
||||
@@ -527,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)
|
||||
|
||||
@@ -540,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'),
|
||||
@@ -553,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
|
||||
|
||||
@@ -574,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)}
|
||||
@@ -587,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).
|
||||
@@ -602,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
|
||||
|
||||
@@ -642,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),
|
||||
@@ -663,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).
|
||||
@@ -675,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)
|
||||
@@ -705,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -317,6 +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\"))
|
||||
@@ -327,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'))
|
||||
@@ -383,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)
|
||||
"
|
||||
@@ -469,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
|
||||
@@ -484,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:
|
||||
@@ -507,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()},
|
||||
@@ -528,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)
|
||||
|
||||
@@ -541,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'),
|
||||
@@ -554,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
|
||||
|
||||
@@ -575,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)}
|
||||
@@ -588,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).
|
||||
@@ -603,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
|
||||
|
||||
@@ -643,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),
|
||||
@@ -664,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).
|
||||
@@ -676,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)
|
||||
@@ -706,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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).
|
||||
@@ -316,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\"))
|
||||
@@ -326,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'))
|
||||
@@ -382,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)
|
||||
"
|
||||
@@ -468,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
|
||||
@@ -483,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:
|
||||
@@ -506,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()},
|
||||
@@ -527,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)
|
||||
|
||||
@@ -540,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'),
|
||||
@@ -553,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
|
||||
|
||||
@@ -574,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)}
|
||||
@@ -587,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).
|
||||
@@ -602,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
|
||||
|
||||
@@ -642,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),
|
||||
@@ -663,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).
|
||||
@@ -675,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)
|
||||
@@ -705,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):
|
||||
```
|
||||
|
||||
+17
-10
@@ -130,12 +130,13 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
print(json.dumps(result))
|
||||
" > graphify-out/.graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -486,7 +487,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears, the same way you substitute `INPUT_PATH` - do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears - do not leave the literal `IS_DIRECTED` in the code. INPUT_PATH is not substituted - each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -501,6 +502,7 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
G = build_from_json(extraction, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
@@ -525,7 +527,7 @@ wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
|
||||
analysis = {
|
||||
@@ -542,7 +544,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -575,7 +577,8 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -589,7 +592,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -837,16 +840,17 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# Stamp only semantic files that produced output so a failed chunk is re-queued next run, not lost (#2015).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_corpus = detect.get('all_files') or detect['files']
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH))
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
|
||||
_stamped = {f for fl in _manifest_files.values() for f in fl}
|
||||
_cleared = _dispatched - _stamped
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -941,7 +945,8 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
|
||||
@@ -1231,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
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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 +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\"))
|
||||
@@ -323,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'))
|
||||
@@ -379,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)
|
||||
"
|
||||
@@ -465,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
|
||||
@@ -480,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:
|
||||
@@ -503,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()},
|
||||
@@ -524,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)
|
||||
|
||||
@@ -537,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'),
|
||||
@@ -550,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
|
||||
|
||||
@@ -571,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)}
|
||||
@@ -584,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).
|
||||
@@ -599,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
|
||||
|
||||
@@ -639,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),
|
||||
@@ -660,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).
|
||||
@@ -672,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)
|
||||
@@ -702,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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).
|
||||
@@ -316,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\"))
|
||||
@@ -326,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'))
|
||||
@@ -382,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)
|
||||
"
|
||||
@@ -468,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
|
||||
@@ -483,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:
|
||||
@@ -506,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()},
|
||||
@@ -527,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)
|
||||
|
||||
@@ -540,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'),
|
||||
@@ -553,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
|
||||
|
||||
@@ -574,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)}
|
||||
@@ -587,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).
|
||||
@@ -602,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
|
||||
|
||||
@@ -642,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),
|
||||
@@ -663,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).
|
||||
@@ -675,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)
|
||||
@@ -705,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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).
|
||||
@@ -316,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\"))
|
||||
@@ -326,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'))
|
||||
@@ -382,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)
|
||||
"
|
||||
@@ -468,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
|
||||
@@ -483,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:
|
||||
@@ -506,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()},
|
||||
@@ -527,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)
|
||||
|
||||
@@ -540,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'),
|
||||
@@ -553,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
|
||||
|
||||
@@ -574,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)}
|
||||
@@ -587,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).
|
||||
@@ -602,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
|
||||
|
||||
@@ -642,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),
|
||||
@@ -663,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).
|
||||
@@ -675,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)
|
||||
@@ -705,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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 +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\"))
|
||||
@@ -318,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'))
|
||||
@@ -374,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)
|
||||
"
|
||||
@@ -460,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
|
||||
@@ -475,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:
|
||||
@@ -498,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()},
|
||||
@@ -519,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)
|
||||
|
||||
@@ -532,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'),
|
||||
@@ -545,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
|
||||
|
||||
@@ -566,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)}
|
||||
@@ -579,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).
|
||||
@@ -594,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
|
||||
|
||||
@@ -634,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),
|
||||
@@ -655,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).
|
||||
@@ -667,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)
|
||||
@@ -697,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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 +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\"))
|
||||
@@ -320,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'))
|
||||
@@ -376,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)
|
||||
"
|
||||
@@ -462,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
|
||||
@@ -477,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:
|
||||
@@ -500,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()},
|
||||
@@ -521,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)
|
||||
|
||||
@@ -534,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'),
|
||||
@@ -547,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
|
||||
|
||||
@@ -568,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)}
|
||||
@@ -581,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).
|
||||
@@ -596,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
|
||||
|
||||
@@ -636,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),
|
||||
@@ -657,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).
|
||||
@@ -669,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)
|
||||
@@ -699,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -314,6 +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\"))
|
||||
@@ -324,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'))
|
||||
@@ -380,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)
|
||||
"
|
||||
@@ -466,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
|
||||
@@ -481,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:
|
||||
@@ -504,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()},
|
||||
@@ -525,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)
|
||||
|
||||
@@ -538,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'),
|
||||
@@ -551,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
|
||||
|
||||
@@ -572,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)}
|
||||
@@ -585,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).
|
||||
@@ -600,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
|
||||
|
||||
@@ -640,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),
|
||||
@@ -661,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).
|
||||
@@ -673,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)
|
||||
@@ -703,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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 +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\"))
|
||||
@@ -322,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'))
|
||||
@@ -378,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)
|
||||
"
|
||||
@@ -464,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
|
||||
@@ -479,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:
|
||||
@@ -502,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()},
|
||||
@@ -523,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)
|
||||
|
||||
@@ -536,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'),
|
||||
@@ -549,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
|
||||
|
||||
@@ -570,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)}
|
||||
@@ -583,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).
|
||||
@@ -598,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
|
||||
|
||||
@@ -638,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),
|
||||
@@ -659,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).
|
||||
@@ -671,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)
|
||||
@@ -701,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -151,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")
|
||||
@@ -159,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
|
||||
@@ -220,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)])
|
||||
|
||||
@@ -227,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:
|
||||
@@ -274,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).
|
||||
@@ -344,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"))
|
||||
@@ -354,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'))
|
||||
@@ -410,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) -
|
||||
@@ -496,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
|
||||
@@ -511,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:
|
||||
@@ -534,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()},
|
||||
@@ -555,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)
|
||||
|
||||
@@ -568,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'),
|
||||
@@ -581,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
|
||||
|
||||
@@ -602,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)}
|
||||
@@ -615,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).
|
||||
@@ -630,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
|
||||
|
||||
@@ -670,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),
|
||||
@@ -691,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).
|
||||
@@ -703,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)
|
||||
@@ -733,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):
|
||||
```
|
||||
|
||||
+29
-19
@@ -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
|
||||
@@ -123,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\")
|
||||
@@ -131,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
|
||||
@@ -192,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)])
|
||||
|
||||
@@ -199,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:
|
||||
@@ -246,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).
|
||||
@@ -316,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\"))
|
||||
@@ -326,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'))
|
||||
@@ -382,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)
|
||||
"
|
||||
@@ -468,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
|
||||
@@ -483,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:
|
||||
@@ -506,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()},
|
||||
@@ -527,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)
|
||||
|
||||
@@ -540,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'),
|
||||
@@ -553,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
|
||||
|
||||
@@ -574,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)}
|
||||
@@ -587,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).
|
||||
@@ -602,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
|
||||
|
||||
@@ -642,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),
|
||||
@@ -663,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).
|
||||
@@ -675,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)
|
||||
@@ -705,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):
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
|
||||
|
||||
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
|
||||
|
||||
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -36,4 +36,7 @@ Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
|
||||
|
||||
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -6,6 +6,7 @@ import ast
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
@@ -325,6 +326,92 @@ def resolve_python_import_guided_calls(
|
||||
return resolved_edges
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def _rust_crate_root(source_file: str) -> str | None:
|
||||
"""The crate a Rust file belongs to: the nearest directory holding a
|
||||
``Cargo.toml``, else the directory above the nearest ``src``. None when
|
||||
neither is found (a flat layout this pass cannot place)."""
|
||||
path = Path(source_file)
|
||||
for parent in path.parents:
|
||||
try:
|
||||
if (parent / "Cargo.toml").is_file():
|
||||
return str(parent)
|
||||
except OSError:
|
||||
break
|
||||
parts = path.parts
|
||||
if "src" in parts[:-1]:
|
||||
idx = len(parts) - 1 - parts[::-1].index("src")
|
||||
return str(Path(*parts[:idx])) if idx else ""
|
||||
return None
|
||||
|
||||
|
||||
def rust_scoped_call_survivors(
|
||||
qualifier: str,
|
||||
candidates: Sequence[str],
|
||||
nid_to_source_file: dict[str, str],
|
||||
caller_file: str = "",
|
||||
nid_to_label: "dict[str, str] | None" = None,
|
||||
) -> list[str]:
|
||||
"""Return the candidates a Rust ``module::function()`` qualifier verifies.
|
||||
|
||||
The qualifier is matched right-to-left against each candidate's file path:
|
||||
the last segment must BE the defining module (``<seg>.rs`` or
|
||||
``<seg>/mod.rs``), and every remaining segment must match the successive
|
||||
parent directory. Matching stops at ``crate``/``super``/``self`` — those
|
||||
are root-relative, and resolving the root needs a module-tree model this
|
||||
deliberately does not attempt; segments to their right are still verified.
|
||||
Matching only the last segment let ``std::fs::read()`` bind to an
|
||||
unrelated local ``fs.rs`` (shadowing std module names with wrapper modules
|
||||
is common Rust); the directory walk fails that on ``std`` vs ``src``.
|
||||
Candidates not defined in a ``.rs`` file are skipped — a bare stem match
|
||||
let a Rust ``b::helper()`` bind to a Python ``b.py``.
|
||||
|
||||
A candidate must live in the caller's crate (see ``_rust_crate_root``):
|
||||
``crate::util::f()`` in crate_a never means crate_b's ``util.rs``. Methods
|
||||
are skipped, since a module path names a free function, never an impl's.
|
||||
|
||||
Returns [] outright when the qualifier disqualifies resolution: a bare
|
||||
``crate``/``super``/``self`` names no module file, and an UpperCamelCase
|
||||
segment is a type (``Type::method()`` / ``Enum::Variant`` — rustc enforces
|
||||
the case convention), which keeps its pre-existing skipped behavior.
|
||||
"""
|
||||
segments = [s.split("<", 1)[0].strip() for s in qualifier.split("::")]
|
||||
segments = [s for s in segments if s]
|
||||
if not segments:
|
||||
return []
|
||||
last = segments[-1]
|
||||
if last in ("crate", "super", "self") or last[:1].isupper():
|
||||
return []
|
||||
caller_crate = _rust_crate_root(caller_file) if caller_file else None
|
||||
survivors: list[str] = []
|
||||
for cand in candidates:
|
||||
cand_file = str(nid_to_source_file.get(cand, ""))
|
||||
if not cand_file.endswith(".rs"):
|
||||
continue
|
||||
if nid_to_label is not None and nid_to_label.get(cand, "").startswith("."):
|
||||
continue
|
||||
if caller_file and _rust_crate_root(cand_file) != caller_crate:
|
||||
continue
|
||||
path = Path(cand_file)
|
||||
if path.stem == last:
|
||||
cursor = path.parent
|
||||
elif path.stem == "mod" and path.parent.name == last:
|
||||
cursor = path.parent.parent
|
||||
else:
|
||||
continue
|
||||
matched = True
|
||||
for seg in reversed(segments[:-1]):
|
||||
if seg in ("crate", "super", "self"):
|
||||
break
|
||||
if cursor.name != seg:
|
||||
matched = False
|
||||
break
|
||||
cursor = cursor.parent
|
||||
if matched:
|
||||
survivors.append(cand)
|
||||
return survivors
|
||||
|
||||
|
||||
def resolve_cross_file_raw_calls(
|
||||
per_file: Sequence[dict[str, Any] | None],
|
||||
all_nodes: list[dict[str, Any]],
|
||||
@@ -348,6 +435,7 @@ def resolve_cross_file_raw_calls(
|
||||
for n in all_nodes
|
||||
if n.get("id")
|
||||
}
|
||||
nid_to_label = {str(n.get("id")): str(n.get("label", "")) for n in all_nodes if n.get("id")}
|
||||
resolved: list[dict[str, Any]] = []
|
||||
|
||||
for raw_call in iter_raw_calls(per_file):
|
||||
@@ -356,6 +444,51 @@ def resolve_cross_file_raw_calls(
|
||||
continue
|
||||
if raw_call.get("is_member_call"):
|
||||
continue
|
||||
if raw_call.get("is_scoped_call"):
|
||||
# Rust module-qualified call (`module::function()`), enqueued by
|
||||
# extractors/rust.py with its qualifier path. These must NEVER fall
|
||||
# through to the bare-name branch below — bare last-segment lookup
|
||||
# across crate boundaries is exactly what produced the spurious
|
||||
# INFERRED edges that motivated dropping scoped calls (#908).
|
||||
# Instead the qualifier is verified against the candidate's file
|
||||
# path (see rust_scoped_call_survivors); require exactly one
|
||||
# survivor or bail (god-node guard preserved). Emitted as EXTRACTED
|
||||
# because the source names the module explicitly — same reasoning
|
||||
# as the Python qualified-class-method pass (#1446/#1533).
|
||||
qualifier = str(raw_call.get("scope_qualifier", "")).strip()
|
||||
survivors = rust_scoped_call_survivors(
|
||||
qualifier, label_index.get(callee.lower(), []), nid_to_source_file,
|
||||
caller_file=str(raw_call.get("source_file", "")),
|
||||
nid_to_label=nid_to_label,
|
||||
)
|
||||
if len(survivors) != 1:
|
||||
continue
|
||||
target = survivors[0]
|
||||
caller = str(raw_call.get("caller_nid", ""))
|
||||
if not caller or target == caller:
|
||||
continue
|
||||
pair = (caller, target, "calls")
|
||||
if pair in known_pairs:
|
||||
continue
|
||||
known_pairs.add(pair)
|
||||
resolved.append(
|
||||
{
|
||||
"source": caller,
|
||||
"target": target,
|
||||
"relation": "calls",
|
||||
"context": "call",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": raw_call.get("source_file", ""),
|
||||
"source_location": raw_call.get("source_location"),
|
||||
"weight": 1.0,
|
||||
"metadata": sanitize_metadata({
|
||||
"resolver": "rust_scoped_module_call",
|
||||
"scope_qualifier": qualifier,
|
||||
}),
|
||||
}
|
||||
)
|
||||
continue
|
||||
candidates = label_index.get(callee.lower(), [])
|
||||
if not candidates:
|
||||
continue
|
||||
|
||||
+41
-10
@@ -49,7 +49,7 @@ DEFAULT_MAX_CHILDREN = 200
|
||||
def _common_root(paths: List[str]) -> str:
|
||||
if not paths:
|
||||
return ""
|
||||
parts = [Path(p).parts for p in paths if p]
|
||||
parts = [Path(p).parent.parts for p in paths if p]
|
||||
if not parts:
|
||||
return ""
|
||||
common = parts[0]
|
||||
@@ -61,8 +61,14 @@ def _common_root(paths: List[str]) -> str:
|
||||
return str(Path(*common)) if common else ""
|
||||
|
||||
|
||||
def _make_truncation_leaf(extra: int) -> Dict[str, Any]:
|
||||
return {"name": f"(+{extra} more)", "total_count": extra, "children": []}
|
||||
def _make_truncation_leaf(
|
||||
extra: int, total_count: Optional[int] = None,
|
||||
) -> Dict[str, Any]:
|
||||
return {
|
||||
"name": f"(+{extra} more)",
|
||||
"total_count": extra if total_count is None else total_count,
|
||||
"children": [],
|
||||
}
|
||||
|
||||
|
||||
def _attach_files(
|
||||
@@ -71,6 +77,7 @@ def _attach_files(
|
||||
root: str,
|
||||
max_children: int,
|
||||
label: Optional[str],
|
||||
directory_ids: set[int],
|
||||
) -> "tuple[Dict[str, Any], int, Dict[str, List[Dict[str, Any]]]]":
|
||||
"""Build one directory tree from ``file_nodes`` (all carry ``source_file``).
|
||||
|
||||
@@ -92,6 +99,7 @@ def _attach_files(
|
||||
"name": label_root, "total_count": 0, "children": [],
|
||||
}
|
||||
dir_index[str(root_path)] = root_node
|
||||
directory_ids.add(id(root_node))
|
||||
|
||||
def _ensure_dir(abs_path: Path) -> Dict[str, Any]:
|
||||
key = str(abs_path)
|
||||
@@ -103,6 +111,7 @@ def _attach_files(
|
||||
if abs_path.parent != abs_path else root_node)
|
||||
node = {"name": abs_path.name, "total_count": 0, "children": []}
|
||||
dir_index[key] = node
|
||||
directory_ids.add(id(node))
|
||||
parent["children"].append(node)
|
||||
return node
|
||||
|
||||
@@ -186,7 +195,9 @@ def build_tree(
|
||||
|
||||
Each leaf is either a code symbol (class / top-level function) or
|
||||
a synthetic "(+N more)" placeholder for truncated wide directories.
|
||||
Each interior node carries ``total_count = sum of leaf counts``.
|
||||
Each interior node carries the full descendant leaf count, including
|
||||
entries hidden by ``max_children``. Directory omission labels count hidden
|
||||
immediate entries; their totals count all leaves behind those entries.
|
||||
|
||||
A graph whose nodes carry two or more distinct ``repo`` tags (a
|
||||
``merge-graphs`` / ``global add`` result) gets one top-level root per
|
||||
@@ -194,11 +205,25 @@ def build_tree(
|
||||
in different repos stay separate. Graphs with fewer than two tags are
|
||||
built exactly as before.
|
||||
|
||||
Raises ``ValueError`` when an explicit ``root`` matches none of the
|
||||
Raises ``ValueError`` for negative ``max_children`` or when an explicit
|
||||
``root`` matches none of the
|
||||
graph's ``source_file`` paths — every file would silently attach flat
|
||||
to the root and the hierarchy would be lost (#2534).
|
||||
"""
|
||||
if max_children < 0:
|
||||
raise ValueError("--max-children must be nonnegative")
|
||||
directory_ids: set[int] = set()
|
||||
nodes: List[Dict[str, Any]] = list(graph.get("nodes", []))
|
||||
for n in nodes:
|
||||
if not n.get("source_file"):
|
||||
# Same alias order as build._fold_node_aliases (`src` last), so a node
|
||||
# carrying two conflicting aliases resolves to the identical
|
||||
# source_file in the built graph and in this viewer.
|
||||
for alias in ("file", "path", "filepath", "src"):
|
||||
val = n.get(alias)
|
||||
if isinstance(val, str) and val.strip():
|
||||
n["source_file"] = n.pop(alias).strip()
|
||||
break
|
||||
file_nodes = [n for n in nodes if n.get("source_file")]
|
||||
if not file_nodes:
|
||||
return {"name": "(empty graph)", "total_count": 0, "children": []}
|
||||
@@ -213,7 +238,7 @@ def build_tree(
|
||||
root = _common_root([n["source_file"] for n in file_nodes])
|
||||
root_node, matched_files, by_file = _attach_files(
|
||||
file_nodes, root=root, max_children=max_children,
|
||||
label=project_label,
|
||||
label=project_label, directory_ids=directory_ids,
|
||||
)
|
||||
total_matched, total_files = matched_files, len(by_file)
|
||||
sample = min(by_file)
|
||||
@@ -223,6 +248,7 @@ def build_tree(
|
||||
"total_count": 0,
|
||||
"children": [],
|
||||
}
|
||||
directory_ids.add(id(root_node))
|
||||
total_matched = total_files = 0
|
||||
sample = ""
|
||||
ordered = sorted(groups.items())
|
||||
@@ -240,6 +266,7 @@ def build_tree(
|
||||
group_root = _common_root(paths)
|
||||
repo_node, matched, by_file = _attach_files(
|
||||
group, root=group_root, max_children=max_children, label=tag,
|
||||
directory_ids=directory_ids,
|
||||
)
|
||||
root_node["children"].append(repo_node)
|
||||
total_matched += matched
|
||||
@@ -265,10 +292,14 @@ def build_tree(
|
||||
))
|
||||
if not kids:
|
||||
return d.get("total_count") or 1
|
||||
n = 0
|
||||
for c in kids:
|
||||
n += _finalise(c)
|
||||
d["total_count"] = n or 1
|
||||
child_totals = [_finalise(c) for c in kids]
|
||||
d["total_count"] = sum(child_totals) or 1
|
||||
if id(d) in directory_ids and len(kids) > max_children:
|
||||
d["children"] = kids[:max_children] + [
|
||||
_make_truncation_leaf(
|
||||
len(kids) - max_children, sum(child_totals[max_children:]),
|
||||
),
|
||||
]
|
||||
return d["total_count"]
|
||||
|
||||
_finalise(root_node)
|
||||
|
||||
@@ -45,7 +45,9 @@ def validate_extraction(data: dict) -> list[str]:
|
||||
)
|
||||
else:
|
||||
node_ids.add(node["id"])
|
||||
if "file_type" in node and node["file_type"] not in VALID_FILE_TYPES:
|
||||
if "file_type" in node and (
|
||||
not isinstance(node["file_type"], str) or node["file_type"] not in VALID_FILE_TYPES
|
||||
):
|
||||
errors.append(
|
||||
f"Node {i} (id={node.get('id', '?')!r}) has invalid file_type "
|
||||
f"'{node['file_type']}' - must be one of {sorted(VALID_FILE_TYPES)}"
|
||||
@@ -65,7 +67,10 @@ def validate_extraction(data: dict) -> list[str]:
|
||||
for field in REQUIRED_EDGE_FIELDS:
|
||||
if field not in edge:
|
||||
errors.append(f"Edge {i} missing required field '{field}'")
|
||||
if "confidence" in edge and edge["confidence"] not in VALID_CONFIDENCES:
|
||||
if "confidence" in edge and (
|
||||
not isinstance(edge["confidence"], str)
|
||||
or edge["confidence"] not in VALID_CONFIDENCES
|
||||
):
|
||||
errors.append(
|
||||
f"Edge {i} has invalid confidence '{edge['confidence']}' "
|
||||
f"- must be one of {sorted(VALID_CONFIDENCES)}"
|
||||
|
||||
+599
-43
@@ -1,6 +1,8 @@
|
||||
# monitor a folder and auto-trigger --update when files change
|
||||
from __future__ import annotations
|
||||
import contextlib
|
||||
import errno
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -25,6 +27,7 @@ from graphify.paths import (
|
||||
logger = logging.getLogger(__name__)
|
||||
_PENDING_FILENAME = ".pending_changes"
|
||||
_PENDING_FULL_FILENAME = ".pending_full"
|
||||
_PENDING_INCREMENTAL_FILENAME = ".pending_incremental"
|
||||
_PENDING_DRAIN_MAX_PASSES = 20
|
||||
|
||||
|
||||
@@ -88,6 +91,10 @@ def _queue_pending_full(out_dir: Path) -> None:
|
||||
Full requests (watcher, post-checkout hook) have no path list to append to
|
||||
``.pending_changes``, so they leave a marker file instead. The lock-holder
|
||||
consumes it and runs one more full pass before releasing (#4274).
|
||||
|
||||
A derived incremental request has no path list either, but it needs a pass of
|
||||
its own kind rather than a full one; that is
|
||||
:func:`_queue_pending_incremental`.
|
||||
"""
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / _PENDING_FULL_FILENAME).touch()
|
||||
@@ -102,6 +109,29 @@ def _drain_pending_full(out_dir: Path) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _queue_pending_incremental(out_dir: Path) -> None:
|
||||
"""Record that an incremental rebuild was requested but could not run.
|
||||
|
||||
An incremental request names no paths: it derives its change set from the
|
||||
manifest *inside* the lock (#4740). So it cannot append to
|
||||
``.pending_changes``, and ``.pending_full`` would be a lie — the drain runs
|
||||
after the lock the caller then wins, so a full marker would upgrade that
|
||||
caller's own pass to a full rebuild. This third marker says the one thing the
|
||||
other two cannot: run an incremental pass.
|
||||
"""
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / _PENDING_INCREMENTAL_FILENAME).touch()
|
||||
|
||||
|
||||
def _drain_pending_incremental(out_dir: Path) -> bool:
|
||||
"""Consume the incremental-rebuild marker. Returns True if one was queued."""
|
||||
try:
|
||||
(out_dir / _PENDING_INCREMENTAL_FILENAME).unlink()
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# Build options that must survive into later rebuilds. The initial `extract`
|
||||
# scan honours `--exclude`, but `update`/`watch`/hook rebuilds re-run detect()
|
||||
# and would silently re-include excluded paths unless the patterns are persisted
|
||||
@@ -114,12 +144,15 @@ def _write_build_config(
|
||||
*,
|
||||
excludes: "list[str] | None",
|
||||
gitignore: bool | None = None,
|
||||
code_only: bool | None = None,
|
||||
) -> None:
|
||||
"""Persist corpus-shaping options under ``out_dir``.
|
||||
|
||||
Best effort and non clobbering: omitted options retain their existing values.
|
||||
``code_only`` records that the graph was built with ``extract --code-only``
|
||||
so a later hook/update/watch rebuild keeps that scope (#4923).
|
||||
"""
|
||||
if not excludes and gitignore is None:
|
||||
if not excludes and gitignore is None and code_only is None:
|
||||
return
|
||||
try:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -134,6 +167,8 @@ def _write_build_config(
|
||||
config["excludes"] = list(excludes)
|
||||
if gitignore is not None:
|
||||
config["gitignore"] = gitignore
|
||||
if code_only is not None:
|
||||
config["code_only"] = code_only
|
||||
path.write_text(json.dumps(config), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
@@ -166,6 +201,23 @@ def _read_build_gitignore(out_dir: Path) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _read_build_code_only(out_dir: Path) -> bool:
|
||||
"""Return whether the graph was built with ``--code-only`` (default False).
|
||||
|
||||
A rebuild has no CLI flag of its own, so this record is the only way it can
|
||||
tell a deliberately code-only graph from a full one (#4923).
|
||||
"""
|
||||
try:
|
||||
path = out_dir / _BUILD_CONFIG_FILENAME
|
||||
if path.is_file():
|
||||
cfg = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(cfg, dict) and cfg.get("code_only") is True:
|
||||
return True
|
||||
except (OSError, json.JSONDecodeError):
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _merge_changed_paths(*sources: "list[Path] | None") -> list[Path]:
|
||||
"""Concatenate path lists, preserving order and dropping duplicates.
|
||||
|
||||
@@ -187,6 +239,22 @@ def _merge_changed_paths(*sources: "list[Path] | None") -> list[Path]:
|
||||
return out
|
||||
|
||||
|
||||
# msvcrt.locking reports a byte range held by another handle as EACCES
|
||||
# (EDEADLOCK is the LK_LOCK flavour). Any other errno means the lock call
|
||||
# itself is unsupported on this filesystem, so waiting for it is pointless.
|
||||
_WIN_LOCK_CONTENDED_ERRNOS = frozenset({errno.EACCES, errno.EDEADLK})
|
||||
|
||||
|
||||
def _win_try_lock(fh, msvcrt, offset: int) -> OSError | None:
|
||||
"""One non-blocking msvcrt lock attempt: None on success, else the error."""
|
||||
try:
|
||||
fh.seek(offset)
|
||||
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
except OSError as exc:
|
||||
return exc
|
||||
return None
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
|
||||
"""Per-repo advisory lock around a rebuild.
|
||||
@@ -202,6 +270,11 @@ def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
|
||||
waits for the lock to clear by polling for its absence unblocks promptly.
|
||||
|
||||
Falls back to a no-op yield(True) on platforms without fcntl or msvcrt.
|
||||
On Windows, a filesystem where msvcrt.locking is unsupported (e.g. the WSL
|
||||
share \\wsl.localhost) also gets yield(True), with a warning on stderr,
|
||||
instead of waiting forever for a lock that can never be taken (#4924). That
|
||||
path leaves an existing ``.rebuild.lock`` untouched: it may belong to a
|
||||
flock holder on the other side of the share.
|
||||
"""
|
||||
try:
|
||||
import fcntl
|
||||
@@ -221,6 +294,7 @@ def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
|
||||
# "a+" creates the file if missing without truncating an existing holder's
|
||||
# PID payload — important because another process may have already written
|
||||
# its PID before we attempt the flock.
|
||||
created_lock_file = not lock_path.exists()
|
||||
fh = open(lock_path, "a+", encoding="utf-8")
|
||||
acquired = False
|
||||
# On Windows, byte-range locks are mandatory. Locking byte offset 4096 allows
|
||||
@@ -279,21 +353,39 @@ def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
|
||||
yield False
|
||||
return
|
||||
else:
|
||||
if blocking:
|
||||
while True:
|
||||
try:
|
||||
fh.seek(_win_lock_offset)
|
||||
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.05)
|
||||
else:
|
||||
try:
|
||||
fh.seek(_win_lock_offset)
|
||||
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
except OSError:
|
||||
while True:
|
||||
lock_error = _win_try_lock(fh, msvcrt, _win_lock_offset)
|
||||
if lock_error is None:
|
||||
break
|
||||
if lock_error.errno not in _WIN_LOCK_CONTENDED_ERRNOS:
|
||||
# The filesystem cannot byte-range lock at all (EINVAL on
|
||||
# the WSL share \\wsl.localhost seen from Windows, #4924).
|
||||
# Retrying can never succeed, and treating it as "held"
|
||||
# made blocking callers spin forever and non-blocking ones
|
||||
# never rebuild. Proceed unlocked, like the no-locking-API
|
||||
# fallback above, without taking over the lock file: a
|
||||
# WSL-side flock holder may own it, and writing our PID
|
||||
# into it or unlinking it on release would let a second
|
||||
# WSL-side caller in on a fresh inode (#4273). Only undo
|
||||
# our own creation of an empty file, before the rebuild.
|
||||
print(
|
||||
f"[graphify watch] cannot lock {lock_path} "
|
||||
f"({lock_error.__class__.__name__}: {lock_error}); this "
|
||||
"filesystem does not support byte-range locks, so "
|
||||
"rebuilds of this graph are not serialized.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
fh.close()
|
||||
if created_lock_file:
|
||||
with contextlib.suppress(OSError):
|
||||
if lock_path.stat().st_size == 0:
|
||||
lock_path.unlink()
|
||||
yield True
|
||||
return
|
||||
if not blocking:
|
||||
yield False
|
||||
return
|
||||
time.sleep(0.05)
|
||||
acquired = True
|
||||
# Replace any prior owner's PID with ours so external readers see a
|
||||
# single parseable line, not a digit-concatenation across rebuilds.
|
||||
@@ -395,6 +487,7 @@ from graphify.detect import (
|
||||
IMAGE_EXTENSIONS,
|
||||
_load_graphifyignore,
|
||||
_is_ignored,
|
||||
ignored_predicate,
|
||||
)
|
||||
from graphify.rcfile import (
|
||||
RC_FILENAME,
|
||||
@@ -839,10 +932,24 @@ def _reconcile_markdown_links(
|
||||
and not _is_file_node(target)
|
||||
)
|
||||
|
||||
def _is_code_file_citation(edge: dict) -> bool:
|
||||
"""A page -> source-file link citation minted by markdown resolution (#4804)."""
|
||||
if edge.get("relation") != "references" or edge.get("target_file"):
|
||||
return False
|
||||
target = nodes_by_id.get(edge.get("target"))
|
||||
source = nodes_by_id.get(edge.get("source"))
|
||||
return (
|
||||
target is not None
|
||||
and target.get("file_type") == "code"
|
||||
and _is_file_node(target)
|
||||
and source is not None
|
||||
and source.get("file_type") == "document"
|
||||
)
|
||||
|
||||
def _keep_edge(edge: dict) -> bool:
|
||||
if not (_is_ast_tier(edge) and edge.get("relation") == "references"):
|
||||
return True
|
||||
if _is_code_span_mention(edge):
|
||||
if _is_code_span_mention(edge) or _is_code_file_citation(edge):
|
||||
return True
|
||||
owner = source_paths.normalize(edge.get("source_file"))
|
||||
if owner not in parsed_sources:
|
||||
@@ -1073,8 +1180,10 @@ def _reconcile_existing_graph(
|
||||
# Deletion evicts edges regardless of tier; re-extraction only owns a
|
||||
# source's AST-tier edges (checked per-edge below, #1865).
|
||||
edge_evicted_source_identities = set(deleted_source_identities)
|
||||
if not full_rebuild:
|
||||
node_evicted_source_identities.update(rebuilt_source_identities)
|
||||
# Re-extraction only owns AST-tier nodes. Adding rebuilt sources to
|
||||
# provenance-blind node eviction would delete semantic nodes from the
|
||||
# exact YAML file being incrementally rebuilt (#4896 follow-up).
|
||||
# Node eviction below is reserved for actual deletion/ignore evidence.
|
||||
|
||||
# Reconcile every rebuild against the current watched corpus. Hook change
|
||||
# lists can contain only a rename destination, so explicit paths alone
|
||||
@@ -1129,6 +1238,19 @@ def _reconcile_existing_graph(
|
||||
)
|
||||
_ignored_cache[identity] = ignored
|
||||
return ignored
|
||||
|
||||
# #4978: is this source AST-owned? A per-file question, so answer it once
|
||||
# per file. It is keyed by identity, not source_file, because one file can
|
||||
# appear as both "big.h" and an absolute path in the same graph.
|
||||
_ast_owned_cache: dict[str, bool] = {}
|
||||
|
||||
def _ast_owned(source: str) -> bool:
|
||||
owned = _ast_owned_cache.get(source)
|
||||
if owned is None:
|
||||
owned = _get_extractor(Path(source), sniff_headers=False) is not None
|
||||
_ast_owned_cache[source] = owned
|
||||
return owned
|
||||
|
||||
for node in existing.get("nodes", []):
|
||||
source_file = node.get("source_file")
|
||||
if not source_file or _is_remote_source(source_file):
|
||||
@@ -1136,7 +1258,7 @@ def _reconcile_existing_graph(
|
||||
identity = source_paths.identity(source_file)
|
||||
if not source_paths.in_watch_root(source_file):
|
||||
continue
|
||||
if _get_extractor(Path(source_file)) is None:
|
||||
if not _ast_owned(identity or source_file):
|
||||
# Non-AST source (semantic doc/paper/image — .txt/.pdf/.png/...):
|
||||
# never present in current_sources (built from AST-extractable
|
||||
# code_files), so corpus absence is meaningless. Deletion
|
||||
@@ -1191,6 +1313,23 @@ def _reconcile_existing_graph(
|
||||
node_evicted_source_identities.add(identity)
|
||||
edge_evicted_source_identities.add(identity)
|
||||
hyperedge_evicted_source_identities.add(identity)
|
||||
# Edges and hyperedges may own a source with no corresponding node.
|
||||
# Positive exclusion evidence applies to these records too (#4912).
|
||||
seen_record_sources: set[str] = set()
|
||||
for item in existing.get("links", existing.get("edges", [])) + existing.get("hyperedges", []):
|
||||
source_file = item.get("source_file")
|
||||
if source_file in seen_record_sources:
|
||||
continue
|
||||
if source_file:
|
||||
seen_record_sources.add(source_file)
|
||||
if (not source_file or _is_remote_source(source_file)
|
||||
or not source_paths.in_watch_root(source_file)):
|
||||
continue
|
||||
identity = source_paths.identity(source_file)
|
||||
if identity and identity not in current_sources and Path(identity).exists() and _ignored_now(identity):
|
||||
edge_evicted_source_identities.add(identity)
|
||||
hyperedge_evicted_source_identities.add(identity)
|
||||
newly_ignored_files.add(identity)
|
||||
if newly_ignored_files:
|
||||
print(
|
||||
f"[graphify watch] pruned {newly_ignored_nodes} node(s) from "
|
||||
@@ -1205,6 +1344,70 @@ def _reconcile_existing_graph(
|
||||
"changed?). Add them to .graphifyignore if the exclusion is intentional."
|
||||
)
|
||||
|
||||
# #4896 follow-up: an extractor upgrade can mint an AST node with
|
||||
# exactly the ID of a saved independently evidenced semantic node.
|
||||
# Pure ID-based replacement below would silently replace its rationale,
|
||||
# author, and capture information, and _check_shrink would miss it
|
||||
# because the ID still exists. Keep the existing semantic ID stable;
|
||||
# move the new AST node to a stable source-qualified ID and retarget
|
||||
# *fresh AST* edges/hyperedges, never the preserved semantic edges.
|
||||
from graphify.build import _has_independent_semantic_evidence
|
||||
from hashlib import sha256
|
||||
old_nodes_by_id = {
|
||||
n["id"]: n for n in existing.get("nodes", [])
|
||||
if isinstance(n, dict) and isinstance(n.get("id"), str)
|
||||
}
|
||||
collisions = {}
|
||||
for fresh in result["nodes"]:
|
||||
nid = fresh.get("id")
|
||||
old = old_nodes_by_id.get(nid)
|
||||
if (
|
||||
not isinstance(nid, str) or not old
|
||||
or _is_ast_tier(old)
|
||||
or not _has_independent_semantic_evidence(old)
|
||||
or source_paths.is_evicted(old, node_evicted_source_identities)
|
||||
):
|
||||
continue
|
||||
if fresh.get("_origin") != "ast":
|
||||
raise ValueError(
|
||||
f"Cannot safely reconcile same-ID semantic and non-AST node: {nid}"
|
||||
)
|
||||
# Different AST extractors may emit multiple source records with
|
||||
# the same legacy AST ID. These already coalesce in build_from_json.
|
||||
# Alias by the *original AST ID* (not a varying source) so every
|
||||
# occurrence and its edges use the same stable successor across
|
||||
# full/incremental rebuilds. This preserves existing AST collision
|
||||
# behavior while keeping the independent semantic record separate.
|
||||
salt = sha256(nid.encode("utf-8")).hexdigest()[:16]
|
||||
alias = nid + "__ast_" + salt
|
||||
former = old_nodes_by_id.get(alias)
|
||||
if alias in new_ast_ids or (
|
||||
former is not None and not _is_ast_tier(former)
|
||||
):
|
||||
raise ValueError(f"AST ID collision cannot be safely rekeyed: {nid}")
|
||||
if nid in collisions and collisions[nid] != alias:
|
||||
raise ValueError(f"Ambiguous AST successor ID: {nid}")
|
||||
collisions[nid] = alias
|
||||
fresh["id"] = alias
|
||||
if collisions:
|
||||
for edge in result.get("edges", []):
|
||||
for field in ("source", "target"):
|
||||
if edge.get(field) in collisions:
|
||||
edge[field] = collisions[edge[field]]
|
||||
for hyperedge in result.get("hyperedges", []):
|
||||
for field in ("nodes", "members", "node_ids"):
|
||||
vals = hyperedge.get(field)
|
||||
if isinstance(vals, list):
|
||||
hyperedge[field] = [
|
||||
collisions.get(value, value) if isinstance(value, str) else value
|
||||
for value in vals
|
||||
]
|
||||
new_ast_ids = {n["id"] for n in result["nodes"]}
|
||||
print(
|
||||
"[graphify watch] preserved "
|
||||
f"{len(collisions)} independent semantic node(s) from AST ID collision"
|
||||
)
|
||||
|
||||
# A full re-extraction owns the AST nodes of every source it actually
|
||||
# re-extracted (extract_targets, via rebuilt_source_identities) — NOT
|
||||
# every AST node under watch_root: a semantic-backed doc is excluded
|
||||
@@ -1218,7 +1421,8 @@ def _reconcile_existing_graph(
|
||||
preserved_nodes = [
|
||||
node
|
||||
for node in existing.get("nodes", [])
|
||||
if node["id"] not in new_ast_ids
|
||||
if (node["id"] not in new_ast_ids
|
||||
or (node.get("_origin") == "semantic" and node.get("source_file")))
|
||||
and not (
|
||||
_is_ast_tier(node)
|
||||
and (
|
||||
@@ -1227,8 +1431,7 @@ def _reconcile_existing_graph(
|
||||
and (full_rebuild or not code_files)
|
||||
)
|
||||
or (
|
||||
full_rebuild
|
||||
and source_paths.is_evicted(node, rebuilt_source_identities)
|
||||
source_paths.is_evicted(node, rebuilt_source_identities)
|
||||
and not source_paths.is_evicted(node, excluded_alive_files)
|
||||
)
|
||||
)
|
||||
@@ -1343,10 +1546,25 @@ def _reconcile_existing_graph(
|
||||
for item in preserved_nodes + preserved_edges + preserved_hyperedges:
|
||||
source_paths.rebase_preserved(item)
|
||||
|
||||
from graphify.dedup import _namespace_reference_stub_collisions
|
||||
merged_hyperedges = result.get("hyperedges", []) + preserved_hyperedges
|
||||
merged_nodes, merged_edges = _namespace_reference_stub_collisions(
|
||||
result["nodes"] + preserved_nodes,
|
||||
result["edges"] + preserved_edges,
|
||||
merged_hyperedges,
|
||||
project_root,
|
||||
preserve_saved_semantics=True,
|
||||
)
|
||||
# Unattributed or same-source copies must not overwrite fresh AST facts.
|
||||
merged_nodes = [
|
||||
node for node in merged_nodes
|
||||
if node["id"] not in new_ast_ids or _is_ast_tier(node)
|
||||
]
|
||||
|
||||
return {
|
||||
"nodes": result["nodes"] + preserved_nodes,
|
||||
"edges": result["edges"] + preserved_edges,
|
||||
"hyperedges": result.get("hyperedges", []) + preserved_hyperedges,
|
||||
"nodes": merged_nodes,
|
||||
"edges": merged_edges,
|
||||
"hyperedges": merged_hyperedges,
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
}, existing_graph_data
|
||||
@@ -1552,6 +1770,42 @@ def _check_shrink(
|
||||
file=sys.stderr,
|
||||
)
|
||||
return False
|
||||
# A node ID can remain present while its independent semantic metadata
|
||||
# disappears (e.g. a newly supported YAML AST extractor mints the same ID).
|
||||
# This is semantic data loss, not an ordinary node-count change. Fail closed.
|
||||
from graphify.build import _has_independent_semantic_evidence, _is_ast_tier
|
||||
new_by_id = {
|
||||
node.get("id"): node for node in new_nodes
|
||||
if isinstance(node, dict) and isinstance(node.get("id"), str)
|
||||
}
|
||||
provenance_fields = (
|
||||
"rationale", "source_url", "author", "contributor", "captured_at", "metadata"
|
||||
)
|
||||
stripped = []
|
||||
for old in existing_nodes:
|
||||
if not isinstance(old, dict) or _is_ast_tier(old):
|
||||
continue
|
||||
if not _has_independent_semantic_evidence(old):
|
||||
continue
|
||||
fresh = new_by_id.get(old.get("id"))
|
||||
if fresh is None:
|
||||
continue # Missing IDs are already checked above.
|
||||
if any(
|
||||
old.get(field) not in (None, "", [], {})
|
||||
and fresh.get(field) in (None, "", [], {})
|
||||
for field in provenance_fields
|
||||
):
|
||||
stripped.append(old["id"])
|
||||
if stripped:
|
||||
if tmp is not None:
|
||||
tmp.unlink(missing_ok=True)
|
||||
print(
|
||||
"[graphify] WARNING: Refusing to overwrite — saved semantic "
|
||||
"provenance field(s) stripped from "
|
||||
f"{len(stripped)} node(s): {', '.join(str(x) for x in stripped[:10])}.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return False
|
||||
if len(new_nodes) >= len(existing_nodes):
|
||||
return True
|
||||
if rebuilt_sources is not None:
|
||||
@@ -1737,6 +1991,7 @@ def _current_build_state(
|
||||
gitignore: bool,
|
||||
excludes: list[str] | None,
|
||||
scan_digest: str,
|
||||
code_only: bool = False,
|
||||
) -> dict:
|
||||
"""Everything besides file content that a rebuild's output depends on (#4740).
|
||||
|
||||
@@ -1763,6 +2018,7 @@ def _current_build_state(
|
||||
"no_cluster": bool(no_cluster),
|
||||
"gitignore": bool(gitignore),
|
||||
"excludes": sorted(excludes or []),
|
||||
"code_only": bool(code_only),
|
||||
"rcfile": rc_digest,
|
||||
# Env knobs that change the written output rather than just the timing:
|
||||
# the viz cap removes graph.html outright, and the ambiguous-edge scale
|
||||
@@ -1958,6 +2214,7 @@ def _rebuild_code(
|
||||
watch_path: Path,
|
||||
*,
|
||||
changed_paths: list[Path] | None = None,
|
||||
incremental: bool = False,
|
||||
follow_symlinks: bool = False,
|
||||
force: bool = False,
|
||||
no_cluster: bool = False,
|
||||
@@ -1976,6 +2233,13 @@ def _rebuild_code(
|
||||
the preserved set. When ``changed_paths`` is None the full code corpus is
|
||||
re-extracted (used by the watcher and post-checkout hook).
|
||||
|
||||
``incremental`` asks for the change set to be derived from the manifest
|
||||
instead of from ``changed_paths`` (#4740). It applies only when
|
||||
``changed_paths`` is None and ``force`` is False, so an explicit list always
|
||||
wins and ``--force`` always means a full rebuild. A manifest that is
|
||||
missing, unreadable or empty leaves the full path in place: "no rows" means
|
||||
"unknown", never "nothing changed".
|
||||
|
||||
``acquire_lock`` (default True) takes a non-blocking per-repo flock around
|
||||
the rebuild so concurrent post-commit hooks across multiple repos do not
|
||||
pile up. Returns False with a log line if the lock is held. Pass
|
||||
@@ -1995,11 +2259,24 @@ def _rebuild_code(
|
||||
# #1059: a hook must not drop its request when another rebuild is
|
||||
# already running. Queue before attempting the lock so a non-blocking
|
||||
# failure still records the work; the lock-holder drains the queue.
|
||||
# Incremental requests append their paths to .pending_changes; full-
|
||||
# corpus requests leave a .pending_full marker (#4274).
|
||||
#
|
||||
# Three request kinds, three records:
|
||||
# explicit paths -> .pending_changes, one path per line
|
||||
# full corpus -> .pending_full, a marker meaning "re-extract all"
|
||||
# derived -> .pending_incremental, a marker meaning "run an
|
||||
# incremental pass"; it has no paths of its own, and
|
||||
# a full marker would upgrade the holder that then
|
||||
# drains it (#4274, #4769)
|
||||
queued = False
|
||||
if not block_on_lock:
|
||||
if changed_paths is None:
|
||||
if incremental and changed_paths is None:
|
||||
# #4740: this request derives its change set from the manifest
|
||||
# inside the lock, so it names no paths. Without a record of its
|
||||
# own, losing the lock below drops it. The marker says "run an
|
||||
# incremental pass", which a later full pass also satisfies.
|
||||
_queue_pending_incremental(out)
|
||||
queued = True
|
||||
elif changed_paths is None:
|
||||
_queue_pending_full(out)
|
||||
queued = True
|
||||
elif changed_paths:
|
||||
@@ -2015,12 +2292,39 @@ def _rebuild_code(
|
||||
# (including, importantly, what we just queued ourselves). A
|
||||
# queued full request upgrades this run to a full rebuild, which
|
||||
# supersedes any incremental work queued before it starts.
|
||||
full = _drain_pending_full(out) or changed_paths is None
|
||||
#
|
||||
# #4740: an incremental request is NOT a full one even though it
|
||||
# also arrives with changed_paths unset. It derives its own change
|
||||
# set in the call below, and a drained path hint adds nothing to
|
||||
# that: the derivation compares the whole scan against the manifest,
|
||||
# so every add, edit and on-disk deletion a hint could name is
|
||||
# already in it. That is why merged stays None here — passing the
|
||||
# hints would suppress the derivation and re-extract only them.
|
||||
queued_full = _drain_pending_full(out)
|
||||
queued_incremental = _drain_pending_incremental(out)
|
||||
pending = _drain_pending(out)
|
||||
merged = None if full else _merge_changed_paths(changed_paths, pending)
|
||||
# A queued incremental request has to be honoured even when this
|
||||
# caller's own flag is off. The marker exists because that request
|
||||
# lost the lock; its change set is the manifest diff, which this
|
||||
# holder can compute just as well.
|
||||
incremental_effective = incremental or queued_incremental
|
||||
if queued_full:
|
||||
full = True
|
||||
elif changed_paths is None:
|
||||
full = not incremental_effective
|
||||
else:
|
||||
full = False
|
||||
merged = (
|
||||
_merge_changed_paths(changed_paths, pending)
|
||||
if changed_paths is not None and not full
|
||||
else None
|
||||
)
|
||||
ok = _rebuild_code(
|
||||
watch_path,
|
||||
changed_paths=merged,
|
||||
# A queued full request overrides the hint: a hook saw a tree
|
||||
# change it could not describe, so re-extract everything.
|
||||
incremental=incremental_effective and not queued_full,
|
||||
follow_symlinks=follow_symlinks,
|
||||
force=force,
|
||||
no_cluster=no_cluster,
|
||||
@@ -2033,12 +2337,14 @@ def _rebuild_code(
|
||||
# quiesces without livelocking.
|
||||
for _ in range(_PENDING_DRAIN_MAX_PASSES):
|
||||
late_full = _drain_pending_full(out)
|
||||
late_incremental = _drain_pending_incremental(out)
|
||||
late = _drain_pending(out)
|
||||
if not late_full and not late:
|
||||
if not late_full and not late and not late_incremental:
|
||||
break
|
||||
ok = _rebuild_code(
|
||||
watch_path,
|
||||
changed_paths=None if late_full else late,
|
||||
changed_paths=None if (late_full or late_incremental) else late,
|
||||
incremental=(incremental or late_incremental) and not late_full,
|
||||
follow_symlinks=follow_symlinks,
|
||||
force=force,
|
||||
no_cluster=no_cluster,
|
||||
@@ -2055,7 +2361,13 @@ def _rebuild_code(
|
||||
report_root = _report_root_label(watch_path)
|
||||
try:
|
||||
from graphify.extract import extract, _get_extractor
|
||||
from graphify.detect import detect
|
||||
from graphify.detect import (
|
||||
classify_manifest_deletions,
|
||||
classify_manifest_files,
|
||||
detect,
|
||||
is_resolution_input,
|
||||
load_manifest,
|
||||
)
|
||||
from graphify.build import build_from_json, _is_ast_tier, _norm_source_file as _nsf
|
||||
from graphify.cluster import cluster, remap_communities_to_previous, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
@@ -2068,6 +2380,9 @@ def _rebuild_code(
|
||||
# (#1886).
|
||||
_persisted_excludes = _read_build_excludes(out)
|
||||
_gitignore_enabled = _read_build_gitignore(out)
|
||||
# #4923: honour the scope the graph was built with. Without this a
|
||||
# `--code-only` graph silently grows doc nodes on the next hook rebuild.
|
||||
_code_only = _read_build_code_only(out)
|
||||
detected = detect(
|
||||
watch_path, follow_symlinks=follow_symlinks,
|
||||
extra_excludes=_persisted_excludes or None,
|
||||
@@ -2088,6 +2403,12 @@ def _rebuild_code(
|
||||
f"[graphify watch] {len(_unclassified)} file(s) not classified "
|
||||
f"(no supported extension or shebang), skipped: {_names}{_more}"
|
||||
)
|
||||
# #2942: when that count is a large SHARE of the corpus, the count
|
||||
# alone reads as routine noise; say plainly that the graph is missing
|
||||
# a structurally significant part of the codebase.
|
||||
_unclassified_warning = detected.get("unclassified_warning") if isinstance(detected, dict) else None
|
||||
if _unclassified_warning:
|
||||
print(f"[graphify watch] warning: {_unclassified_warning}")
|
||||
|
||||
# #4740: stop before extraction when nothing that reaches the code graph
|
||||
# has changed. The only no-change exit today sits at the very end of the
|
||||
@@ -2107,6 +2428,7 @@ def _rebuild_code(
|
||||
gitignore=_gitignore_enabled,
|
||||
excludes=_persisted_excludes,
|
||||
scan_digest=_scan_digest(detected),
|
||||
code_only=_code_only,
|
||||
)
|
||||
|
||||
if changed_paths is None and not force:
|
||||
@@ -2120,6 +2442,62 @@ def _rebuild_code(
|
||||
)
|
||||
return True
|
||||
|
||||
# #4740: the caller asked for an incremental update. The manifest already
|
||||
# records the ast_hash of every file the last build extracted, so the
|
||||
# change set can be read off it instead of re-extracting the whole
|
||||
# corpus. `detected` was computed above for the full path anyway, so this
|
||||
# costs one manifest read, not a second scan. A manifest cannot
|
||||
# restore unchanged nodes when the graph it describes is missing.
|
||||
#
|
||||
# A manifest that is missing, unreadable or empty leaves changed_paths
|
||||
# None — the full path. "No rows" means the baseline is unknown, and the
|
||||
# only safe reading of unknown is "do the work"; `detect_incremental`
|
||||
# makes the same call for `graphify extract` (#1925).
|
||||
if incremental and changed_paths is None and not force and (out / "graph.json").is_file():
|
||||
manifest = load_manifest(str(out / "manifest.json"), root=watch_root)
|
||||
if manifest:
|
||||
resolution_inputs = detected.get("resolution_inputs") or []
|
||||
_changed_buckets, _unchanged_buckets = classify_manifest_files(
|
||||
{**detected["files"], "resolution_inputs": resolution_inputs},
|
||||
manifest,
|
||||
kind="ast",
|
||||
)
|
||||
modified = [f for bucket in _changed_buckets.values() for f in bucket]
|
||||
# Rows that left the corpus belong in the change set too. A row
|
||||
# whose file is gone from disk must reach the deleted branch
|
||||
# below, or its nodes survive and the shrink guard refuses the
|
||||
# write (_accounted only excuses a source in rebuilt_sources).
|
||||
# A row that is still alive but out of scan is an ignore-rule
|
||||
# change, which the corpus sweep handles on positive evidence
|
||||
# alone (#2495), so it stays out of the change set.
|
||||
deleted_rows, excluded_rows = classify_manifest_deletions(
|
||||
manifest,
|
||||
[
|
||||
*resolution_inputs,
|
||||
*(f for bucket in detected["files"].values() for f in bucket),
|
||||
],
|
||||
root=watch_root,
|
||||
)
|
||||
if any(is_resolution_input(f) for f in (*modified, *deleted_rows, *excluded_rows)):
|
||||
# An unchanged importer may resolve differently when its
|
||||
# config or workspace layout changes. Re-resolve the corpus.
|
||||
print(
|
||||
"[graphify watch] JS/TS resolution inputs changed; rebuilding the full code graph."
|
||||
)
|
||||
else:
|
||||
changed_paths = [Path(f) for f in (*modified, *deleted_rows)]
|
||||
scanned = sum(len(v) for v in detected["files"].values())
|
||||
if changed_paths:
|
||||
print(
|
||||
f"[graphify watch] Incremental: re-extracting {len(changed_paths)} "
|
||||
f"of {scanned} scanned files that changed since the last build."
|
||||
)
|
||||
else:
|
||||
print(
|
||||
f"[graphify watch] Incremental: none of the {scanned} scanned "
|
||||
"files differ from the last build."
|
||||
)
|
||||
|
||||
# #2495: hand reconcile the same ignore decisions the detect() call
|
||||
# above made, so a newly-ignored file that still exists on disk is
|
||||
# purged from the graph instead of preserved forever by the fail-closed
|
||||
@@ -2143,9 +2521,12 @@ def _rebuild_code(
|
||||
# zero nodes with no warning (#4750). Only formats with an extractor
|
||||
# qualify (.md/.mdx/.qmd today): PDFs and plain .txt still have none, so
|
||||
# the _get_extractor filter keeps them out exactly as before.
|
||||
# A `--code-only` graph (#4923) opted out of documents entirely, so the
|
||||
# quick-scan is skipped; doc nodes already in the graph are preserved
|
||||
# untouched (they are not in code_files, so reconcile keeps them).
|
||||
ast_doc_files: list[Path] = []
|
||||
for doc_file in [*detected['files'].get('document', []),
|
||||
*detected['files'].get('paper', [])]:
|
||||
for doc_file in ([] if _code_only else [*detected['files'].get('document', []),
|
||||
*detected['files'].get('paper', [])]):
|
||||
p = Path(doc_file)
|
||||
if _get_extractor(p) is not None:
|
||||
code_files.append(p)
|
||||
@@ -2338,7 +2719,15 @@ def _rebuild_code(
|
||||
if not node.get("id") or not _is_ast_tier(node):
|
||||
continue
|
||||
source_file = node.get("source_file")
|
||||
if not source_file or ctx_paths.identity(source_file) not in ctx_live:
|
||||
# ctx_live is built from project_root-anchored paths, so the
|
||||
# membership test has to use the same anchoring. identity()
|
||||
# resolves a stored relative path against the root recorded
|
||||
# in graphify-out/.graphify_root, and a copied checkout left
|
||||
# that pointing at its original location — every stored node
|
||||
# then read as corpus-absent, the context came back empty,
|
||||
# and the changed batch lost its cross-file edges (#2406).
|
||||
ctx_identity = ctx_paths.absolute_identity(source_file, project_root)
|
||||
if not source_file or ctx_identity not in ctx_live:
|
||||
continue
|
||||
ctx_node = {
|
||||
"id": node["id"],
|
||||
@@ -2351,11 +2740,12 @@ def _rebuild_code(
|
||||
# label: callability protects indirect calls (#2438), and
|
||||
# Rust impl identity connects alpha-renamed generic blocks.
|
||||
for marker in (
|
||||
"_callable", "_callable_class", "_elixir_module",
|
||||
"_callable", "_callable_class", "_elixir_module", "_cpp_qualified",
|
||||
"_rust_impl_key", "_rust_declaration_count",
|
||||
"_ts_public_twin", "_py_property", "_java_ret",
|
||||
"_ts_fields", "_ts_static_fields",
|
||||
"_py_fixture", "_py_return_type", "_go_fields",
|
||||
"_go_package_path",
|
||||
):
|
||||
if node.get(marker):
|
||||
ctx_node[marker] = node[marker]
|
||||
@@ -2405,7 +2795,11 @@ def _rebuild_code(
|
||||
if not _is_ast_tier(edge):
|
||||
continue
|
||||
source_file = edge.get("source_file")
|
||||
if not source_file or ctx_paths.identity(source_file) not in ctx_live:
|
||||
# Same anchoring as the nodes above, or an unchanged file's
|
||||
# import edge drops out of the resolve context and a changed
|
||||
# file's call into it cannot be resolved (#2437).
|
||||
ctx_identity = ctx_paths.absolute_identity(source_file, project_root)
|
||||
if not source_file or ctx_identity not in ctx_live:
|
||||
continue
|
||||
context_edge = {
|
||||
"source": edge.get("source"),
|
||||
@@ -2701,6 +3095,7 @@ def _rebuild_code(
|
||||
"total_files": len(code_files),
|
||||
"total_words": detected.get("total_words", 0),
|
||||
"unclassified": detected.get("unclassified", []),
|
||||
"unclassified_warning": detected.get("unclassified_warning"),
|
||||
}
|
||||
|
||||
# Inherit the existing graph's directed flag (#2342) so `graphify
|
||||
@@ -3075,6 +3470,42 @@ def _batch_triggers_rebuild(batch: list[Path]) -> bool:
|
||||
return has_code or has_deletion
|
||||
|
||||
|
||||
def _watch_event_filter():
|
||||
"""Watchdog events that mean a file actually changed, not just was read.
|
||||
|
||||
Passing this as ``event_filter`` keeps ``IN_OPEN`` and
|
||||
``IN_CLOSE_NOWRITE`` out of the inotify mask. The recursive watch-setup
|
||||
walk then produces no events of its own, so it cannot overflow the kernel
|
||||
queue and trigger watchdog's rebuild loop (#5033).
|
||||
"""
|
||||
from watchdog import events as we
|
||||
|
||||
return [
|
||||
we.FileCreatedEvent,
|
||||
we.FileModifiedEvent,
|
||||
we.FileDeletedEvent,
|
||||
we.FileMovedEvent,
|
||||
we.FileClosedEvent,
|
||||
we.DirCreatedEvent,
|
||||
we.DirDeletedEvent,
|
||||
we.DirMovedEvent,
|
||||
]
|
||||
|
||||
|
||||
def _observer_accepts_event_filter(observer) -> bool:
|
||||
"""True when this watchdog's ``schedule()`` declares ``event_filter``.
|
||||
|
||||
``event_filter`` was added in watchdog 4.0. Graphify does not pin a minimum
|
||||
watchdog version, so detect support instead of raising TypeError on older
|
||||
installs. Introspection failures are treated as unsupported; the caller
|
||||
warns on that path so a future signature change is visible.
|
||||
"""
|
||||
try:
|
||||
return "event_filter" in inspect.signature(observer.schedule).parameters
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
_READ_ONLY_EVENT_TYPES = frozenset({"opened", "closed_no_write"})
|
||||
|
||||
|
||||
@@ -3165,7 +3596,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
try:
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.observers.polling import PollingObserver
|
||||
from watchdog.events import FileSystemEventHandler
|
||||
from watchdog.events import FileCreatedEvent, FileSystemEventHandler
|
||||
except ImportError as e:
|
||||
raise ImportError("watchdog not installed. Run: pip install watchdog") from e
|
||||
|
||||
@@ -3180,22 +3611,59 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
# without this short-circuit a busy volume can saturate a CPU core
|
||||
# discarding events one extension at a time. (gh-928)
|
||||
watch_root_for_ignore = watch_path.resolve()
|
||||
ignore_gitignore = _read_build_gitignore(watch_path / _GRAPHIFY_OUT)
|
||||
ignore_patterns = _load_graphifyignore(
|
||||
watch_root_for_ignore,
|
||||
gitignore=_read_build_gitignore(watch_path / _GRAPHIFY_OUT),
|
||||
gitignore=ignore_gitignore,
|
||||
)
|
||||
ignored = ignored_predicate(watch_root_for_ignore, gitignore=ignore_gitignore)
|
||||
|
||||
# Observer and dispatch threads need the same root-specific snapshot.
|
||||
root_config_path = watch_root_for_ignore / RC_FILENAME
|
||||
override_snapshot: dict[str, str] = activate_language_overrides(watch_root_for_ignore)
|
||||
config_changed = False
|
||||
# Only Linux prunes the recursive watch tree. macOS and Windows keep the
|
||||
# recursive schedule, so their handler must not require a `watched` entry.
|
||||
manual = sys.platform.startswith("linux")
|
||||
|
||||
class Handler(FileSystemEventHandler):
|
||||
def on_any_event(self, event):
|
||||
nonlocal last_trigger, pending, override_snapshot, config_changed
|
||||
if event.is_directory or _is_read_only_event(event):
|
||||
nonlocal ignore_patterns, ignored
|
||||
if event.is_directory:
|
||||
if not manual or _is_read_only_event(event):
|
||||
return
|
||||
path = Path(os.fsdecode(event.src_path)).resolve()
|
||||
if path.parent not in watched:
|
||||
return
|
||||
if event.event_type == "created":
|
||||
add_tree(path, emit_existing=True)
|
||||
elif event.event_type == "deleted":
|
||||
remove_tree(path)
|
||||
elif event.event_type == "moved":
|
||||
remove_tree(path)
|
||||
dest = Path(os.fsdecode(event.dest_path)).resolve()
|
||||
if under_root(dest):
|
||||
add_tree(dest, emit_existing=True)
|
||||
return
|
||||
if _is_read_only_event(event):
|
||||
return
|
||||
path = Path(os.fsdecode(event.src_path))
|
||||
if manual and (
|
||||
path.parent not in watched or not path.parent.exists()
|
||||
):
|
||||
return
|
||||
if path.name in {".graphifyignore", ".gitignore"}:
|
||||
ignore_patterns = _load_graphifyignore(
|
||||
watch_root_for_ignore, gitignore=ignore_gitignore
|
||||
)
|
||||
ignored = ignored_predicate(
|
||||
watch_root_for_ignore, gitignore=ignore_gitignore
|
||||
)
|
||||
if manual:
|
||||
remove_tree(watch_root_for_ignore)
|
||||
add_tree(watch_root_for_ignore, emit_existing=False)
|
||||
return
|
||||
# Atomic replacement reports the new root config in dest_path.
|
||||
dest_raw = getattr(event, "dest_path", None)
|
||||
dest_path = Path(os.fsdecode(dest_raw)) if dest_raw else None
|
||||
@@ -3228,9 +3696,97 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
changed.add(path)
|
||||
|
||||
handler = Handler()
|
||||
# Use polling observer on macOS — FSEvents can miss rapid saves in some editors
|
||||
observer = PollingObserver() if sys.platform == "darwin" else Observer()
|
||||
observer.schedule(handler, str(watch_root_for_ignore), recursive=True)
|
||||
observer = (
|
||||
Observer()
|
||||
if manual
|
||||
else (PollingObserver() if sys.platform == "darwin" else Observer())
|
||||
)
|
||||
watched: dict[Path, object] = {}
|
||||
warned_no_filter = False
|
||||
|
||||
def under_root(path: Path) -> bool:
|
||||
try:
|
||||
path.resolve().relative_to(watch_root_for_ignore)
|
||||
return True
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
def schedule_one(path: Path) -> None:
|
||||
nonlocal warned_no_filter
|
||||
path = path.resolve()
|
||||
if path in watched or not under_root(path):
|
||||
return
|
||||
if path != watch_root_for_ignore and ignored(path):
|
||||
return
|
||||
if path == watch_root_for_ignore / _GRAPHIFY_OUT:
|
||||
return
|
||||
kwargs = {"recursive": False}
|
||||
if _observer_accepts_event_filter(observer):
|
||||
kwargs["event_filter"] = _watch_event_filter()
|
||||
elif not warned_no_filter:
|
||||
warned_no_filter = True
|
||||
logger.warning(
|
||||
"watchdog does not declare event_filter; read-only inotify "
|
||||
"events may overflow the queue and lose changes (#5033)"
|
||||
)
|
||||
try:
|
||||
watched[path] = observer.schedule(handler, str(path), **kwargs)
|
||||
except OSError as exc:
|
||||
if exc.errno == errno.ENOSPC:
|
||||
logger.warning(
|
||||
"inotify watch limit reached while watching %s; "
|
||||
"changes below it will be missed", path
|
||||
)
|
||||
return
|
||||
raise
|
||||
|
||||
def remove_tree(path: Path) -> None:
|
||||
path = path.resolve()
|
||||
prefix = str(path) + os.sep
|
||||
for key in [p for p in watched if str(p) == str(path) or str(p).startswith(prefix)]:
|
||||
watch = watched.pop(key)
|
||||
try:
|
||||
observer.unschedule(watch)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def add_tree(path: Path, *, emit_existing: bool) -> None:
|
||||
path = path.resolve()
|
||||
stack = [path]
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
if not under_root(current):
|
||||
continue
|
||||
if current != watch_root_for_ignore and ignored(current):
|
||||
continue
|
||||
if current == watch_root_for_ignore / _GRAPHIFY_OUT:
|
||||
continue
|
||||
schedule_one(current)
|
||||
try:
|
||||
entries = list(os.scandir(current))
|
||||
except OSError:
|
||||
continue
|
||||
for entry in entries:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
stack.append(Path(entry.path))
|
||||
elif emit_existing and entry.is_file(follow_symlinks=False):
|
||||
handler.on_any_event(FileCreatedEvent(entry.path))
|
||||
|
||||
if manual:
|
||||
add_tree(watch_root_for_ignore, emit_existing=False)
|
||||
elif _observer_accepts_event_filter(observer):
|
||||
observer.schedule(
|
||||
handler,
|
||||
str(watch_root_for_ignore),
|
||||
recursive=True,
|
||||
event_filter=_watch_event_filter(),
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"watchdog does not declare event_filter; read-only inotify events "
|
||||
"may overflow the queue and lose changes (#5033)"
|
||||
)
|
||||
observer.schedule(handler, str(watch_root_for_ignore), recursive=True)
|
||||
observer.start()
|
||||
|
||||
print(f"[graphify watch] Watching {watch_path.resolve()} - press Ctrl+C to stop")
|
||||
|
||||
Loaded 100 of 286 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user